@copilotkit/mcp-apps-renderer 2.0.0-rc.4 → 2.0.0-rc.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"session.mjs","names":[],"sources":["../src/session.ts"],"sourcesContent":["import {\n AppBridge,\n LATEST_PROTOCOL_VERSION,\n PostMessageTransport,\n} from \"@modelcontextprotocol/ext-apps/app-bridge\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport type { CallToolResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport { z } from \"zod\";\nimport { randomUUID } from \"@copilotkit/shared\";\nimport { buildSandboxHTML, ɵmcpAppSandboxFlags } from \"./sandbox\";\nimport {\n mcpAppsRequestQueue,\n MCP_APPS_QUEUE_IDLE_TIMEOUT_MS,\n MCPAppsQueueThreadChangedError,\n} from \"./request-queue\";\nimport { ɵrunMcpFollowUp } from \"./follow-up\";\nimport type { ɵMcpFollowUpHost } from \"./follow-up\";\nimport {\n MCP_OPEN_LINK_BLOCKED_SCHEMES,\n MCPAppsActivityType,\n} from \"./constants\";\nimport { MCPAppsActivityContentSchema } from \"./content-schema\";\nimport type { MCPAppsActivityContent } from \"./content-schema\";\n\n/** Structural shape of an ag-ui activity message (avoids a hard type import). */\ninterface ActivityLike {\n id?: string;\n activityType?: string;\n content?: unknown;\n}\n\n/** JSON key for dedup; falls back to empty string on a cyclic/unserializable value. */\nfunction keyOf(value: unknown): string {\n try {\n return JSON.stringify(value) ?? \"\";\n } catch {\n return \"\";\n }\n}\n\n/**\n * Decode a base64 resource body as UTF-8.\n *\n * @internal exported for testing.\n *\n * `atob` alone yields a latin1 string, which mangles non-ASCII widget HTML\n * (`<p>Été ☀️</p>` decoded to `<p>Été ☀ï¸</p>`). Decode to bytes first, then\n * run them through a UTF-8 TextDecoder.\n */\nexport function ɵdecodeBase64(value: string): string {\n try {\n const binary = atob(value);\n const bytes = Uint8Array.from(binary, (character) =>\n character.charCodeAt(0),\n );\n return new TextDecoder().decode(bytes);\n } catch {\n throw new Error(\"The MCP App resource contains invalid base64 content.\");\n }\n}\n\n/**\n * Pick the resource this session asked for.\n *\n * A `resources/read` response may carry several contents; taking the first one\n * can hand the widget a different resource than the one it is bound to. Match on\n * the requested URI, and fall back to a lone content only when the server\n * returned exactly one (some servers normalize the URI they echo back).\n */\nfunction selectResource(\n contents: FetchedResource[] | undefined,\n resourceUri: string,\n requireExact = false,\n): FetchedResource | undefined {\n const match = contents?.find((candidate) => candidate.uri === resourceUri);\n if (match) return match;\n return !requireExact && contents?.length === 1 ? contents[0] : undefined;\n}\n\n/**\n * Stable key for the widget resource a session is bound to. A session fetches\n * and renders exactly ONE resource. If the store activity for this messageId is\n * later replaced by a different resource (resourceUri/serverHash/serverId), the\n * store subscription must NOT push the new widget's tool input/result into this\n * (old) iframe - the adapter re-binds a fresh session for the new identity.\n */\nfunction identityKeyOf(content: {\n resourceUri?: string;\n serverHash?: string;\n serverId?: string;\n}): string {\n // Serialised as a tuple rather than joined with a delimiter: a resourceUri is\n // arbitrary text, so any separator can appear inside it and make two distinct\n // widgets share a key (`\"a::b\" + \"c\"` vs `\"a\" + \"b::c\"`). JSON also keeps\n // `undefined` distinct from `\"\"` instead of collapsing both to empty.\n return JSON.stringify([\n content.resourceUri ?? null,\n content.serverHash ?? null,\n content.serverId ?? null,\n ]);\n}\n\n/**\n * The MCP Apps protocol version this host negotiates. Sourced directly from the\n * ext-apps bridge (single source of truth, no hand-maintained literal). It lives\n * here (a bridge-side module) rather than in the bridge-free `./constants` /\n * `./activity` entry so the lightweight activity-registration surface stays free\n * of the ext-apps bundle; consumers that need the version import it from the\n * package root, which already loads the bridge.\n */\nexport const MCP_APPS_PROTOCOL_VERSION = LATEST_PROTOCOL_VERSION;\n\n/**\n * Permissive `ui/message` schema. ext-apps restricts the request to\n * `role: \"user\"` with no `followUp`, but CopilotKit intentionally extends\n * `ui/message` with `role` (\"user\" | \"assistant\") and `followUp` (documented\n * behavior with dedicated tests). We register our own handler (instead of the\n * bridge's strict `onmessage`) so those extensions survive.\n *\n * Going forward, widgets SHOULD pass the extensions under\n * `params._meta.copilotkit`; the top-level `role`/`followUp` fields are the\n * legacy channel, kept for backward compatibility and slated for deprecation.\n */\nconst CopilotKitUiMessageSchema = z.object({\n method: z.literal(\"ui/message\"),\n params: z\n .object({\n role: z.string().optional(),\n content: z.array(z.any()).optional(),\n followUp: z.boolean().optional(),\n _meta: z.record(z.string(), z.any()).optional(),\n })\n .passthrough(),\n});\n\n/** A resource fetched from the MCP server via the agent proxy. */\nexport interface FetchedResource {\n uri: string;\n mimeType?: string;\n text?: string;\n blob?: string;\n _meta?: {\n ui?: {\n prefersBorder?: boolean;\n csp?: {\n connectDomains?: string[];\n resourceDomains?: string[];\n };\n };\n };\n}\n\n/** Reactive callbacks the framework adapter wires to its own state. */\nexport interface McpAppSessionHooks {\n /** The widget reported a new content size (ui/notifications/size-changed). */\n onSizeChanged?(size: { width?: number; height?: number }): void;\n /** The widget finished initializing (safe to push tool input/result). */\n onInitialized?(): void;\n /** The sandbox proxy is ready and its resource has been sent. */\n onSandboxReady?(): void;\n /** The fetched resource metadata (e.g. prefersBorder) is available. */\n onResource?(resource: FetchedResource): void;\n /**\n * FATAL setup failure (resource fetch, bridge connect, sandbox timeout).\n * The session cannot serve this widget; the host keeps showing the error\n * until it re-binds.\n */\n onError?(err: Error): void;\n /** A queued ui/message follow-up failed. */\n onFollowUpError?(err: Error): void;\n /**\n * RECOVERABLE content problem: an activity update was rejected by the content\n * schema and therefore not forwarded to the widget. Reported the same way\n * whether the content came from the agent's store or from an adapter prop.\n *\n * Called with the `Error` when content is rejected, and with `null` as soon as\n * valid content arrives again - the widget resumes, so the host must clear the\n * message rather than leave a stale error on screen.\n */\n onContentError?(err: Error | null): void;\n}\n\nexport interface BindMcpAppOptions {\n /**\n * The sandbox iframe. The adapter creates and OWNS this element (mounts it in\n * its render model, sizes it, removes it on unmount). The session only\n * configures the sandbox contract (sandbox attr, testid, srcdoc) and talks to\n * it through the bridge - it never creates, moves, or removes the iframe.\n */\n iframe: HTMLIFrameElement;\n /** Returns the current activity content (resourceUri, serverHash, tool input/result). */\n getContent: () => MCPAppsActivityContent;\n /** Returns the current agent (may change across renders). */\n getAgent: () => AbstractAgent | undefined;\n /** CopilotKit host, for ui/message follow-up runs (issue #5819). */\n host: ɵMcpFollowUpHost;\n /**\n * The id of the activity message this session renders. When provided, the\n * session subscribes to the agent's message store, finds this activity, and\n * pushes its tool input/result to the widget itself (self-driving), so the\n * adapter does not re-implement the agent-driven forwarding loop.\n *\n * The store is authoritative only for activities that live in it. When a host\n * renders an activity from an EXTERNAL message list (e.g. CopilotChatView's\n * `messages` prop), that activity is not in `agent.messages`; the adapter must\n * then call `syncContent` on content change so the widget still receives its\n * tool input/result. Both paths share one dedup, so they never double-send.\n */\n messageId?: string;\n hooks?: McpAppSessionHooks;\n /**\n * Host identity, capabilities and UI context announced during the MCP Apps\n * initialization handshake, plus the two timeouts. Every field is optional and\n * merged over {@link MCP_APPS_SESSION_DEFAULTS}, so a frontend only overrides\n * what it exposes to its users.\n */\n options?: McpAppSessionOptions;\n /**\n * Decides whether `ui/open-link` may open a URL, and with what final value.\n *\n * Defaults to {@link denyDangerousSchemes}, the single policy every CopilotKit\n * frontend uses - no adapter overrides it, so a widget behaves the same in\n * React, Vue and Angular. This hook exists for a host with a genuinely\n * different security contract; prefer changing the shared policy over setting\n * it, otherwise widget behaviour becomes framework-dependent again.\n */\n openLinkPolicy?: McpAppOpenLinkPolicy;\n /**\n * Whether `teardown` also cancels a queued `ui/message` follow-up run.\n *\n * Defaults to `false`: the follow-up carries the user's message onwards, so it\n * outlives the widget that sent it. Hosts that scope follow-ups to the widget\n * (the Angular contract) can opt in.\n */\n cancelFollowUpsOnTeardown?: boolean;\n /** Require the fetched resource URI to match exactly (Angular compatibility). */\n requireExactResourceUri?: boolean;\n /** Release already-started proxy/follow-up waits on teardown, without aborting the underlying run. */\n cancelRunningWaitOnTeardown?: boolean;\n}\n\n/** Host identity announced during the initialization handshake. */\nexport interface McpAppHostInfo {\n name: string;\n version: string;\n}\n\nexport interface McpAppSessionOptions {\n /** Maximum time a queued request waits for a busy agent. Default 30s. */\n idleTimeoutMs?: number;\n /**\n * Maximum time to wait for the sandbox proxy handshake\n * (`ui/notifications/sandbox-proxy-ready`). Default 30s.\n *\n * This measures the SANDBOX step, not `ui/notifications/initialized`: a widget\n * that loads its proxy but never reports initialized is a different failure.\n */\n initializationTimeoutMs?: number;\n /** Host identity announced during the initialization handshake. */\n hostInfo?: McpAppHostInfo;\n /** Protocol capabilities announced to embedded MCP Apps. */\n hostCapabilities?: Record<string, unknown>;\n /** Non-secret UI context announced to embedded MCP Apps. */\n hostContext?: Record<string, unknown>;\n /**\n * Restore `allow-same-origin` on the sandbox frames. Default `false`.\n *\n * **Unsafe.** The sandbox proxy is loaded via `srcdoc`, so with this flag the\n * widget runs with the host page's origin: it can read the host's cookies,\n * storage and DOM, and call the host's APIs as the signed-in user. Only set\n * it for widgets you wrote and trust that genuinely need `localStorage`,\n * `IndexedDB` or cookies. By default widgets get an opaque origin.\n */\n allowSameOriginFallback?: boolean;\n}\n\n/** Defaults every frontend inherits unless it overrides them. */\nexport const MCP_APPS_SESSION_DEFAULTS: Readonly<\n Required<McpAppSessionOptions>\n> = {\n idleTimeoutMs: MCP_APPS_QUEUE_IDLE_TIMEOUT_MS,\n initializationTimeoutMs: 30_000,\n hostInfo: { name: \"CopilotKit MCP Apps Host\", version: \"1.0.0\" },\n hostCapabilities: { openLinks: {}, logging: {}, message: { text: {} } },\n hostContext: { platform: \"web\" },\n allowSameOriginFallback: false,\n};\n\n/**\n * Returns the URL to open, or `undefined` to refuse. Receiving the raw string\n * (not a parsed URL) lets a policy resolve relative links itself.\n */\nexport type McpAppOpenLinkPolicy = (url: string) => string | undefined;\n\n/**\n * The MCP Apps link policy, shared by every frontend.\n *\n * Three independent rules, deliberately kept as ONE policy so a widget behaves\n * the same whichever framework hosts it:\n *\n * 1. **Scheme denylist**, not an allowlist. Only the schemes that execute script\n * or render attacker-controlled HTML are refused (`javascript:`, `data:`,\n * `vbscript:`, `blob:`, `file:`). Everything else is allowed, including\n * app-defined deep links (`myapp:`, `whatsapp:`), which hand off to an OS\n * handler rather than executing in the page. An allowlist could never\n * enumerate those, and restricting to http/https would break them.\n * 2. **Embedded credentials refused** (`https://user:pw@host`): a widget must not\n * hand the browser a URL carrying someone's credentials.\n * 3. **Path-relative links resolved** against the host document, so `/docs`,\n * `./x` and `../x` open instead of failing URL parsing. Only those three\n * forms: every string is technically a valid relative reference, so anything\n * else stays refused rather than becoming a navigation on the host origin.\n * This does mean a widget can reach a path of the HOST application - the same\n * reach a normal anchor in the page would have.\n *\n * Rules 2 and 3 come from the Angular host, which enforced them before it moved\n * onto this session; rule 1 is the CopilotKit product decision (it matches the\n * Anthropic Software Directory policy: https origins plus owned custom URI\n * schemes). Merging them means no frontend overrides anything.\n */\nexport const denyDangerousSchemes: McpAppOpenLinkPolicy = (url) => {\n let parsed: URL;\n let absolute = true;\n try {\n parsed = new URL(url);\n } catch {\n // Not absolute. Resolve only what is unambiguously a path reference: per the\n // URL spec ANY string is a valid relative reference, so resolving blindly\n // would turn \"not a url\" into a navigation on the host origin.\n if (!/^(\\/|\\.\\/|\\.\\.\\/)/.test(url)) return undefined;\n absolute = false;\n try {\n parsed = new URL(url, window.location.href);\n } catch {\n return undefined;\n }\n // A leading \"/\" does not guarantee the resolution stays on the host: per the\n // URL spec a backslash is normalized to \"/\" inside the path of a\n // special-scheme base, so \"/\\evil.com\" parses as a protocol-relative\n // authority and resolves to \"http://evil.com/\". Rule 3 promises a relative\n // link reaches a path of the HOST application, so require the origin to be\n // unchanged. Only reachable through the relative branch, so an absolute URL\n // is still handed back exactly as the widget wrote it.\n if (parsed.origin !== window.location.origin) return undefined;\n }\n if (MCP_OPEN_LINK_BLOCKED_SCHEMES.has(parsed.protocol)) return undefined;\n if (parsed.username || parsed.password) return undefined;\n // An absolute URL is handed back exactly as the widget wrote it: `href`\n // normalisation would rewrite it (adding a trailing slash, reserialising a\n // custom-scheme deep link). Only a relative link needs the resolved form,\n // since the raw string is not openable on its own.\n return absolute ? url : parsed.href;\n};\n\nexport interface McpAppSession {\n /** Forward the tool call input to the widget (host -> app). Buffered until ready. */\n sendToolInput(args: Record<string, unknown>): void;\n /** Forward the tool result to the widget (host -> app). Buffered until ready. */\n sendToolResult(result: CallToolResult): void;\n /**\n * Forward the tool input/result carried by `content` to the widget, deduped so\n * an unchanged value is not re-sent. The prop-driven counterpart to the agent\n * subscription: the adapter calls this on content change so activities rendered\n * from an external message list (absent from `agent.messages`) still reach the\n * widget. No-op for values already sent (shared dedup with the subscription).\n *\n * Content is validated here exactly as it is on the store path: a rejected\n * value is not forwarded and surfaces through `onContentError`.\n */\n syncContent(content: MCPAppsActivityContent): void;\n /** Disconnect the bridge and release listeners. Does NOT remove the iframe. */\n teardown(): void;\n}\n\n/**\n * Bind an MCP App to a host-provided sandbox iframe: fetch the widget resource\n * through the agent, connect the ext-apps `AppBridge` over a PostMessage\n * transport, and wire the app<->host protocol (ui/message, ui/open-link,\n * tools/call + resources/read proxy, size, host context). Framework-agnostic:\n * the React/Vue/Angular renderers create the iframe and wire reactive state via\n * `hooks`, but all protocol logic lives here.\n */\nexport function bindMcpApp(opts: BindMcpAppOptions): McpAppSession {\n const {\n iframe,\n getContent,\n getAgent,\n host,\n messageId,\n hooks,\n options,\n openLinkPolicy = denyDangerousSchemes,\n cancelFollowUpsOnTeardown = false,\n } = opts;\n // Frontend-supplied options merged over the shared defaults, so a host only\n // overrides what it actually exposes (Angular's provideMCPApps merge, lifted).\n const settings = { ...MCP_APPS_SESSION_DEFAULTS, ...options };\n\n // The widget resource identity this session is bound to, captured once at bind\n // time. The store subscription refuses to forward content for any other\n // identity (see `pushFromContent`).\n const boundIdentity = identityKeyOf(getContent());\n\n // Ownership token for this session's queued work. Widget-scoped requests\n // (resources/read, tools/call) exist only to feed THIS iframe, so `teardown`\n // cancels the ones still waiting.\n //\n // The `ui/message` follow-up run is owned only when the host asks for it via\n // `cancelFollowUpsOnTeardown` (the Angular contract). Left unowned - the\n // default, used by React and Vue - it survives the widget, because it carries\n // the user's message onwards rather than feeding the iframe.\n const queueOwner = {};\n\n let disposed = false;\n let ready = false;\n let bridge: AppBridge | null = null;\n let pendingToolInput: Record<string, unknown> | undefined;\n let pendingToolResult: CallToolResult | undefined;\n // Self-driving mode (messageId set): dedup keys so a re-emitted activity with\n // unchanged tool input/result does not re-notify the widget, and the agent\n // subscription handle so teardown can unsubscribe.\n let lastToolInputKey: string | undefined;\n let lastToolResultKey: string | undefined;\n // Last content that failed validation, so the same rejection is not reported\n // again on every subsequent update. Shared by both sources: the widget has a\n // single error state, whether the content came from the store or from a prop.\n let lastInvalidContentKey: string | undefined;\n let activitySub: { unsubscribe(): void } | null = null;\n // Sandbox handshake watchdog (see initializationTimeoutMs).\n let sandboxTimer: ReturnType<typeof setTimeout> | undefined;\n let sandboxReady = false;\n let sandboxTimedOut = false;\n\n /** Flush any buffered tool input/result to the widget once it is initialized. */\n const flushPending = () => {\n if (!ready || !bridge) return;\n if (pendingToolInput !== undefined) {\n void bridge.sendToolInput({ arguments: pendingToolInput });\n pendingToolInput = undefined;\n }\n if (pendingToolResult !== undefined) {\n void bridge.sendToolResult(pendingToolResult);\n pendingToolResult = undefined;\n }\n };\n\n /**\n * Report content the schema rejected. RECOVERABLE: the session keeps running\n * and resumes as soon as valid content arrives, so this never goes through the\n * fatal `onError` channel. Deduped on the offending value, since store updates\n * fire for every message change, not just this activity's.\n */\n const reportContentRejected = (\n value: unknown,\n error: { message: string },\n ) => {\n const key = keyOf(value);\n if (key === lastInvalidContentKey) return;\n lastInvalidContentKey = key;\n hooks?.onContentError?.(\n new Error(\n `[MCPAppsRenderer] Activity content for message \"${messageId ?? \"(no id)\"}\" does not match the MCP Apps content schema, so it was not forwarded to the widget: ${error.message}`,\n ),\n );\n };\n\n /** Valid content resumed: clear the message the host shows for a rejection. */\n const clearContentRejection = () => {\n if (lastInvalidContentKey === undefined) return;\n lastInvalidContentKey = undefined;\n hooks?.onContentError?.(null);\n };\n\n /**\n * Push tool input/result from an activity content to the widget, deduped so an\n * unchanged value (e.g. a re-emitted snapshot) is not re-sent. Buffered by the\n * imperative sender until the widget is initialized.\n *\n * The single forwarding path for BOTH sources - the store subscription\n * (`pushFromMessages`) and the adapter props (`syncContent`) - so validation,\n * the identity guard and recoverable-error reporting behave identically\n * whichever one produced the content.\n */\n const pushFromContent = (content: MCPAppsActivityContent) => {\n // Identity guard: only forward tool input/result for the resource this\n // session is bound to. If the store activity for this messageId has been\n // replaced by a different widget (resourceUri/serverHash/serverId), pushing\n // here would leak the new widget's data into this (old, still-mounted) iframe\n // before the adapter tears the session down and re-binds for the new\n // identity. Refuse it; the fresh session will forward the new widget's data.\n // Validate the WHOLE content before anything is forwarded. `toolInput` and\n // `result` describe one exchange: sending the input and only then finding\n // the result invalid would leave the widget half-updated, and a toolInput\n // that is not a record must not reach it just because the result happens to\n // parse. Content arriving from an adapter prop is as untrusted as the\n // store's, so both go through the same schema here. A rejection is\n // RECOVERABLE (reported through onContentError, cleared when valid content\n // returns), not a fatal session error.\n const parsedContent = MCPAppsActivityContentSchema.safeParse(content);\n if (!parsedContent.success) {\n reportContentRejected(content, parsedContent.error);\n return;\n }\n const validated = parsedContent.data;\n if (identityKeyOf(validated) !== boundIdentity) return;\n const { toolInput } = validated;\n const validResult = validated.result as CallToolResult | undefined;\n clearContentRejection();\n\n if (toolInput !== undefined) {\n const key = keyOf(toolInput);\n if (key !== lastToolInputKey) {\n lastToolInputKey = key;\n pendingToolInput = toolInput;\n flushPending();\n }\n }\n if (validResult !== undefined) {\n const key = keyOf(validResult);\n if (key !== lastToolResultKey) {\n lastToolResultKey = key;\n pendingToolResult = validResult;\n flushPending();\n }\n }\n };\n\n /**\n * Push the CURRENT content of this activity (read from the agent's message\n * store, the authoritative post-apply source) to the widget. Used both at\n * initialize and on every `onMessagesChanged`, so the widget always reflects\n * the applied state - never a stale React prop or a pre-apply activity message.\n * Store path only (requires `messageId`); the props path goes through\n * `syncContent`. `messages` overrides the store lookup when provided.\n */\n const pushFromMessages = (messages?: readonly ActivityLike[]) => {\n if (disposed || !messageId) return;\n const list = (messages ??\n (getAgent()?.messages as readonly ActivityLike[] | undefined)) as\n | readonly ActivityLike[]\n | undefined;\n const msg = list?.find((m) => m?.id === messageId);\n if (!msg || msg.activityType !== MCPAppsActivityType) return;\n const parsed = MCPAppsActivityContentSchema.safeParse(msg.content);\n if (!parsed.success) {\n // Rejected content is NOT forwarded, but the failure must be observable\n // rather than a silent no-op: otherwise the widget simply never receives\n // its result and nothing says why.\n reportContentRejected(msg.content, parsed.error);\n return;\n }\n // pushFromContent clears the rejection once it has validated the result.\n pushFromContent(parsed.data);\n };\n\n /** True when this activity currently lives in the agent's message store. */\n const activityInStore = (): boolean =>\n !!(getAgent()?.messages as readonly ActivityLike[] | undefined)?.some(\n (m) => m?.id === messageId && m?.activityType === MCPAppsActivityType,\n );\n\n /** Fetch the widget resource (`resources/read`) through the agent proxy queue. */\n const fetchResource = async (): Promise<FetchedResource> => {\n const agent = getAgent();\n if (!agent) {\n throw new Error(\"No agent available to fetch resource\");\n }\n const { resourceUri, serverHash, serverId } = getContent();\n const readOnlyAgent = agent as AbstractAgent & {\n ɵrunMcpResourceRead?: AbstractAgent[\"runAgent\"];\n };\n const runResult = await mcpAppsRequestQueue.enqueue(\n agent,\n () => {\n const parameters = {\n forwardedProps: {\n __proxiedMCPRequest: {\n serverHash,\n serverId,\n method: \"resources/read\",\n params: { uri: resourceUri },\n },\n },\n };\n return readOnlyAgent.ɵrunMcpResourceRead\n ? readOnlyAgent.ɵrunMcpResourceRead(parameters)\n : agent.runAgent(parameters);\n },\n {\n owner: queueOwner,\n timeoutMs: settings.idleTimeoutMs,\n cancelRunningWait: opts.cancelRunningWaitOnTeardown,\n // The widget belongs to the thread it was rendered in: running its fetch\n // against a thread the host switched to would load it into the wrong\n // conversation.\n dropAfterThreadSwitch: true,\n },\n );\n const resultData = runResult.result as\n | { contents?: FetchedResource[] }\n | undefined;\n const resource = selectResource(\n resultData?.contents,\n resourceUri,\n opts.requireExactResourceUri,\n );\n if (!resource) {\n throw new Error(\"No resource content in response\");\n }\n return resource;\n };\n\n /**\n * Terminal shutdown, owned by the session itself.\n *\n * Used by `teardown()` AND by the sandbox watchdog: once the handshake window\n * closes, the session must stop serving this widget rather than leave the\n * bridge and its handlers live until the adapter happens to unmount. It does\n * NOT remove the iframe - the adapter owns that element.\n *\n * Idempotent.\n */\n const closeSession = () => {\n if (disposed) return;\n disposed = true;\n if (sandboxTimer !== undefined) {\n clearTimeout(sandboxTimer);\n sandboxTimer = undefined;\n }\n // Drop this widget's still-waiting proxy requests: they only exist to feed\n // an iframe that is going away. Requests already in flight keep running\n // (runAgent has no abort), and other widgets' queued work is untouched.\n mcpAppsRequestQueue.cancelOwner(queueOwner);\n activitySub?.unsubscribe();\n activitySub = null;\n const b = bridge;\n bridge = null;\n void b?.close();\n };\n\n /**\n * Fetch the resource, configure + load the sandbox iframe, construct the\n * AppBridge, wire the app->host handlers, and connect the transport.\n */\n const setup = async () => {\n try {\n const resource = await fetchResource();\n if (disposed) return;\n hooks?.onResource?.(resource);\n\n // Configure the sandbox iframe (contract shared across frontends). The\n // same flags go to the widget frame in sandbox-resource-ready below.\n const sandbox = ɵmcpAppSandboxFlags(settings.allowSameOriginFallback);\n iframe.setAttribute(\"sandbox\", sandbox);\n // Cross-frontend MCP-apps surface contract: every frontend must expose the\n // sandbox iframe under the SAME testid so one shared probe (harness\n // `d5-mcp-apps`) and one shared e2e spec can assert the surface mounted\n // without per-frontend selectors.\n iframe.setAttribute(\"data-testid\", \"mcp-app-iframe\");\n iframe.setAttribute(\"title\", \"Interactive MCP application\");\n\n const cspDomains = resource._meta?.ui?.csp?.resourceDomains;\n iframe.srcdoc = buildSandboxHTML(cspDomains);\n\n const win = iframe.contentWindow;\n if (!win) {\n throw new Error(\"Sandbox iframe has no contentWindow\");\n }\n\n let html: string;\n if (resource.text) {\n html = resource.text;\n } else if (resource.blob) {\n html = ɵdecodeBase64(resource.blob);\n } else {\n throw new Error(\"Resource has no text or blob content\");\n }\n\n bridge = new AppBridge(\n null,\n settings.hostInfo,\n settings.hostCapabilities,\n // Seed the host context at construction so it is already in place when\n // the widget's ui/initialize is handled (deterministic, not a race).\n {\n hostContext: {\n // The theme follows CopilotKit's dark selector (a `.dark`\n // ancestor) unless the host configured one explicitly.\n theme: iframe.closest(\".dark\") ? \"dark\" : \"light\",\n ...settings.hostContext,\n },\n },\n );\n\n // Sandbox handshake: on proxy ready, load the widget HTML into the inner\n // sandboxed iframe.\n // The sandbox proxy must report back within initializationTimeoutMs. This\n // measures the SANDBOX handshake (sandbox-proxy-ready), not the widget's\n // later `initialized` notification - a widget that loads but never reports\n // initialized is a different failure and is not covered here.\n sandboxTimer = setTimeout(() => {\n if (disposed || sandboxReady) return;\n // Mark the handshake window closed: a proxy that reports ready after the\n // deadline must not silently resurrect a session the host already\n // surfaced as failed.\n sandboxTimedOut = true;\n // Report first (closeSession sets `disposed`, which gates the hooks),\n // then terminate: the widget never handshaked, so keeping the bridge and\n // its handlers alive would let a late iframe still proxy runs through us.\n hooks?.onError?.(\n new Error(\n `[MCPAppsRenderer] Timed out after ${settings.initializationTimeoutMs}ms waiting for the MCP App sandbox to initialize.`,\n ),\n );\n closeSession();\n }, settings.initializationTimeoutMs);\n\n bridge.onsandboxready = () => {\n if (sandboxTimedOut) {\n console.warn(\n \"[MCPAppsRenderer] Ignoring a sandbox handshake that arrived after the initialization timeout.\",\n );\n return;\n }\n sandboxReady = true;\n if (sandboxTimer !== undefined) {\n clearTimeout(sandboxTimer);\n sandboxTimer = undefined;\n }\n void bridge?.sendSandboxResourceReady({ html, sandbox }).then(() => {\n if (!disposed) hooks?.onSandboxReady?.();\n });\n };\n\n // --- App -> host requests ---\n // ui/message: custom handler preserving CopilotKit role/followUp extensions\n // (via _meta.copilotkit first, then legacy top-level fields).\n bridge.setRequestHandler(CopilotKitUiMessageSchema, async (req) => {\n const currentAgent = getAgent();\n if (!currentAgent) {\n console.warn(\"[MCPAppsRenderer] ui/message: No agent available\");\n return { isError: false };\n }\n try {\n const params = req.params;\n const ck = (params._meta?.copilotkit ?? {}) as {\n role?: string;\n followUp?: boolean;\n };\n const role =\n (ck.role as \"user\" | \"assistant\") ||\n (params.role as \"user\" | \"assistant\") ||\n \"user\";\n const textContent =\n (\n params.content as\n | Array<{ type: string; text?: string }>\n | undefined\n )\n ?.filter((c) => c.type === \"text\" && c.text)\n .map((c) => c.text)\n .join(\"\\n\") || \"\";\n if (textContent) {\n currentAgent.addMessage({\n id: randomUUID(),\n role,\n content: textContent,\n });\n }\n const followUp = ck.followUp ?? params.followUp;\n const shouldFollowUp = followUp ?? role === \"user\";\n if (shouldFollowUp && textContent) {\n const capturedThreadId = currentAgent.threadId || \"default\";\n mcpAppsRequestQueue\n .enqueue(\n currentAgent,\n () =>\n ɵrunMcpFollowUp({\n host,\n agent: currentAgent,\n capturedThreadId,\n }),\n {\n // Honour the configured wait like the other proxied requests.\n // Ownership is deliberate policy, see cancelFollowUpsOnTeardown.\n timeoutMs: settings.idleTimeoutMs,\n owner: cancelFollowUpsOnTeardown ? queueOwner : undefined,\n cancelRunningWait: opts.cancelRunningWaitOnTeardown,\n },\n )\n .catch((err) => {\n if (disposed && cancelFollowUpsOnTeardown) return;\n console.error(\n \"[MCPAppsRenderer] ui/message agent run failed:\",\n err,\n );\n hooks?.onFollowUpError?.(\n err instanceof Error ? err : new Error(String(err)),\n );\n });\n }\n return { isError: false };\n } catch (err) {\n console.error(\"[MCPAppsRenderer] ui/message error:\", err);\n return { isError: true };\n }\n });\n\n bridge.onopenlink = async ({ url }) => {\n // The bridge validates `url` as a string but not its scheme. The policy\n // decides (and may rewrite, e.g. resolving a relative link).\n const allowed = openLinkPolicy(url);\n if (!allowed) {\n console.warn(\n \"[MCPAppsRenderer] ui/open-link rejected by policy:\",\n url,\n );\n return { isError: true };\n }\n window.open(allowed, \"_blank\", \"noopener,noreferrer\");\n return { isError: false };\n };\n\n bridge.oncalltool = async (params) => {\n const { serverHash, serverId } = getContent();\n const currentAgent = getAgent();\n if (!serverHash) {\n throw new Error(\"No server hash available for proxying\");\n }\n if (!currentAgent) {\n throw new Error(\"No agent available for proxying\");\n }\n let runResult;\n try {\n runResult = await mcpAppsRequestQueue.enqueue(\n currentAgent,\n () =>\n currentAgent.runAgent({\n forwardedProps: {\n __proxiedMCPRequest: {\n serverHash,\n serverId,\n method: \"tools/call\",\n params,\n },\n },\n }),\n {\n owner: queueOwner,\n timeoutMs: settings.idleTimeoutMs,\n cancelRunningWait: opts.cancelRunningWaitOnTeardown,\n dropAfterThreadSwitch: true,\n },\n );\n } catch (err) {\n // A call dropped by the thread guard must come back to the widget as\n // an explicit JSON-RPC error. Swallowing it would leave the caller\n // waiting for a response that can never arrive.\n if (err instanceof MCPAppsQueueThreadChangedError) {\n throw new Error(\n `tools/call was not executed: ${err.message} Retry from the current thread.`,\n { cause: err },\n );\n }\n throw err;\n }\n return MCPAppsActivityContentSchema.shape.result.parse(\n runResult.result ?? {},\n );\n };\n\n // --- App -> host notifications ---\n bridge.onsizechange = (p) => {\n if (disposed) return;\n const { width, height } = (p || {}) as {\n width?: number;\n height?: number;\n };\n hooks?.onSizeChanged?.({\n width: typeof width === \"number\" ? width : undefined,\n height: typeof height === \"number\" ? height : undefined,\n });\n };\n bridge.oninitialized = () => {\n if (disposed) return;\n ready = true;\n hooks?.onInitialized?.();\n // Self-driving: reconcile the buffers BEFORE the first flush. When this\n // activity lives in the store, the store is authoritative, so discard any\n // prop-seeded buffers - e.g. an activity that was absent at bind time and\n // seeded via syncContent, then appeared in the store with the applied\n // content during the resource fetch - and push the CURRENT store content\n // instead. Clearing first means a stale pre-init value is never sent\n // ahead of (or instead of) the applied one; reading from the store - not\n // getContent() - honors an update that arrived before initialize.\n if (messageId && activityInStore()) {\n pendingToolInput = undefined;\n pendingToolResult = undefined;\n lastToolInputKey = undefined;\n lastToolResultKey = undefined;\n pushFromMessages();\n }\n flushPending();\n };\n bridge.onloggingmessage = (p) => {\n console.log(\"[MCPAppsRenderer] App log:\", p);\n };\n\n const transport = new PostMessageTransport(win, win);\n await bridge.connect(transport);\n if (disposed) {\n await bridge.close();\n bridge = null;\n return;\n }\n\n // Self-driving: subscribe to the agent and push tool input/result for THIS\n // activity to the widget, so the framework adapter does not forward them.\n //\n // We read from `onMessagesChanged`, NOT `onActivitySnapshotEvent` /\n // `onActivityDeltaEvent`: those fire with the PRE-update `activityMessage`\n // (the snapshot's new content / the delta patch is applied only after the\n // callback returns), so reading them yields stale content and the dedup\n // below can suppress the send entirely. `onMessagesChanged` fires AFTER the\n // store is updated, so `messages` holds the applied content - and it also\n // covers full messages-snapshot updates, which the activity callbacks miss.\n if (messageId) {\n activitySub =\n getAgent()?.subscribe({\n onMessagesChanged: ({ messages }) =>\n pushFromMessages(messages as readonly ActivityLike[]),\n }) ?? null;\n }\n } catch (err) {\n console.error(\"[MCPAppsRenderer] Setup error:\", err);\n if (!disposed) {\n hooks?.onError?.(err instanceof Error ? err : new Error(String(err)));\n }\n }\n };\n\n void setup();\n\n return {\n sendToolInput(args) {\n pendingToolInput = args;\n flushPending();\n },\n sendToolResult(result) {\n pendingToolResult =\n MCPAppsActivityContentSchema.shape.result.parse(result);\n flushPending();\n },\n syncContent(content) {\n // Store precedence: when this activity lives in the agent's message store,\n // the subscription is authoritative (it reads the applied post-update\n // content), so ignore the prop to avoid pushing a possibly-stale React\n // prop over it. Forward props only for activities absent from the store\n // (rendered from an external messages list).\n if (messageId && activityInStore()) return;\n pushFromContent(content);\n },\n teardown() {\n closeSession();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;AAgCA,SAAS,MAAM,OAAwB;AACrC,KAAI;AACF,SAAO,KAAK,UAAU,MAAM,IAAI;SAC1B;AACN,SAAO;;;;;;;;;;;;AAaX,SAAgB,cAAc,OA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,SAAS;KAC/C,CAAC;;AAEJ,UAAO,sBAAsB;AAC3B,QAAI,SAAU;AACd,YAAQ;AACR,WAAO,iBAAiB;AASxB,QAAI,aAAa,iBAAiB,EAAE;AAClC,wBAAmB;AACnB,yBAAoB;AACpB,wBAAmB;AACnB,yBAAoB;AACpB,uBAAkB;;AAEpB,kBAAc;;AAEhB,UAAO,oBAAoB,MAAM;AAC/B,YAAQ,IAAI,8BAA8B,EAAE;;GAG9C,MAAM,YAAY,IAAI,qBAAqB,KAAK,IAAI;AACpD,SAAM,OAAO,QAAQ,UAAU;AAC/B,OAAI,UAAU;AACZ,UAAM,OAAO,OAAO;AACpB,aAAS;AACT;;AAaF,OAAI,UACF,eACE,UAAU,EAAE,UAAU,EACpB,oBAAoB,EAAE,eACpB,iBAAiB,SAAoC,EACxD,CAAC,IAAI;WAEH,KAAK;AACZ,WAAQ,MAAM,kCAAkC,IAAI;AACpD,OAAI,CAAC,SACH,QAAO,UAAU,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,IAAI,CAAC,CAAC;;;AAK3E,CAAK,OAAO;AAEZ,QAAO;EACL,cAAc,MAAM;AAClB,sBAAmB;AACnB,iBAAc;;EAEhB,eAAe,QAAQ;AACrB,uBACE,6BAA6B,MAAM,OAAO,MAAM,OAAO;AACzD,iBAAc;;EAEhB,YAAY,SAAS;AAMnB,OAAI,aAAa,iBAAiB,CAAE;AACpC,mBAAgB,QAAQ;;EAE1B,WAAW;AACT,iBAAc;;EAEjB"}
1
+ {"version":3,"file":"session.mjs","names":[],"sources":["../src/session.ts"],"sourcesContent":["import {\n AppBridge,\n LATEST_PROTOCOL_VERSION,\n PostMessageTransport,\n} from \"@modelcontextprotocol/ext-apps/app-bridge\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport type { CallToolResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport * as z from \"zod\";\nimport { randomUUID } from \"@copilotkit/shared\";\nimport { buildSandboxHTML, ɵmcpAppSandboxFlags } from \"./sandbox\";\nimport {\n mcpAppsRequestQueue,\n MCP_APPS_QUEUE_IDLE_TIMEOUT_MS,\n MCPAppsQueueThreadChangedError,\n} from \"./request-queue\";\nimport { ɵrunMcpFollowUp } from \"./follow-up\";\nimport type { ɵMcpFollowUpHost } from \"./follow-up\";\nimport {\n MCP_OPEN_LINK_BLOCKED_SCHEMES,\n MCPAppsActivityType,\n} from \"./constants\";\nimport { MCPAppsActivityContentSchema } from \"./content-schema\";\nimport type { MCPAppsActivityContent } from \"./content-schema\";\n\n/** Structural shape of an ag-ui activity message (avoids a hard type import). */\ninterface ActivityLike {\n id?: string;\n activityType?: string;\n content?: unknown;\n}\n\n/** JSON key for dedup; falls back to empty string on a cyclic/unserializable value. */\nfunction keyOf(value: unknown): string {\n try {\n return JSON.stringify(value) ?? \"\";\n } catch {\n return \"\";\n }\n}\n\n/**\n * Decode a base64 resource body as UTF-8.\n *\n * @internal exported for testing.\n *\n * `atob` alone yields a latin1 string, which mangles non-ASCII widget HTML\n * (`<p>Été ☀️</p>` decoded to `<p>Été ☀ï¸</p>`). Decode to bytes first, then\n * run them through a UTF-8 TextDecoder.\n */\nexport function ɵdecodeBase64(value: string): string {\n try {\n const binary = atob(value);\n const bytes = Uint8Array.from(binary, (character) =>\n character.charCodeAt(0),\n );\n return new TextDecoder().decode(bytes);\n } catch {\n throw new Error(\"The MCP App resource contains invalid base64 content.\");\n }\n}\n\n/**\n * Pick the resource this session asked for.\n *\n * A `resources/read` response may carry several contents; taking the first one\n * can hand the widget a different resource than the one it is bound to. Match on\n * the requested URI, and fall back to a lone content only when the server\n * returned exactly one (some servers normalize the URI they echo back).\n */\nfunction selectResource(\n contents: FetchedResource[] | undefined,\n resourceUri: string,\n requireExact = false,\n): FetchedResource | undefined {\n const match = contents?.find((candidate) => candidate.uri === resourceUri);\n if (match) return match;\n return !requireExact && contents?.length === 1 ? contents[0] : undefined;\n}\n\n/**\n * Stable key for the widget resource a session is bound to. A session fetches\n * and renders exactly ONE resource. If the store activity for this messageId is\n * later replaced by a different resource (resourceUri/serverHash/serverId), the\n * store subscription must NOT push the new widget's tool input/result into this\n * (old) iframe - the adapter re-binds a fresh session for the new identity.\n */\nfunction identityKeyOf(content: {\n resourceUri?: string;\n serverHash?: string;\n serverId?: string;\n}): string {\n // Serialised as a tuple rather than joined with a delimiter: a resourceUri is\n // arbitrary text, so any separator can appear inside it and make two distinct\n // widgets share a key (`\"a::b\" + \"c\"` vs `\"a\" + \"b::c\"`). JSON also keeps\n // `undefined` distinct from `\"\"` instead of collapsing both to empty.\n return JSON.stringify([\n content.resourceUri ?? null,\n content.serverHash ?? null,\n content.serverId ?? null,\n ]);\n}\n\n/**\n * The MCP Apps protocol version this host negotiates. Sourced directly from the\n * ext-apps bridge (single source of truth, no hand-maintained literal). It lives\n * here (a bridge-side module) rather than in the bridge-free `./constants` /\n * `./activity` entry so the lightweight activity-registration surface stays free\n * of the ext-apps bundle; consumers that need the version import it from the\n * package root, which already loads the bridge.\n */\nexport const MCP_APPS_PROTOCOL_VERSION = LATEST_PROTOCOL_VERSION;\n\n/**\n * Permissive `ui/message` schema. ext-apps restricts the request to\n * `role: \"user\"` with no `followUp`, but CopilotKit intentionally extends\n * `ui/message` with `role` (\"user\" | \"assistant\") and `followUp` (documented\n * behavior with dedicated tests). We register our own handler (instead of the\n * bridge's strict `onmessage`) so those extensions survive.\n *\n * Going forward, widgets SHOULD pass the extensions under\n * `params._meta.copilotkit`; the top-level `role`/`followUp` fields are the\n * legacy channel, kept for backward compatibility and slated for deprecation.\n */\nconst CopilotKitUiMessageSchema = z.object({\n method: z.literal(\"ui/message\"),\n params: z\n .object({\n role: z.string().optional(),\n content: z.array(z.any()).optional(),\n followUp: z.boolean().optional(),\n _meta: z.record(z.string(), z.any()).optional(),\n })\n .loose(),\n});\n\n/** A resource fetched from the MCP server via the agent proxy. */\nexport interface FetchedResource {\n uri: string;\n mimeType?: string;\n text?: string;\n blob?: string;\n _meta?: {\n ui?: {\n prefersBorder?: boolean;\n csp?: {\n connectDomains?: string[];\n resourceDomains?: string[];\n };\n };\n };\n}\n\n/** Reactive callbacks the framework adapter wires to its own state. */\nexport interface McpAppSessionHooks {\n /** The widget reported a new content size (ui/notifications/size-changed). */\n onSizeChanged?(size: { width?: number; height?: number }): void;\n /** The widget finished initializing (safe to push tool input/result). */\n onInitialized?(): void;\n /** The sandbox proxy is ready and its resource has been sent. */\n onSandboxReady?(): void;\n /** The fetched resource metadata (e.g. prefersBorder) is available. */\n onResource?(resource: FetchedResource): void;\n /**\n * FATAL setup failure (resource fetch, bridge connect, sandbox timeout).\n * The session cannot serve this widget; the host keeps showing the error\n * until it re-binds.\n */\n onError?(err: Error): void;\n /** A queued ui/message follow-up failed. */\n onFollowUpError?(err: Error): void;\n /**\n * RECOVERABLE content problem: an activity update was rejected by the content\n * schema and therefore not forwarded to the widget. Reported the same way\n * whether the content came from the agent's store or from an adapter prop.\n *\n * Called with the `Error` when content is rejected, and with `null` as soon as\n * valid content arrives again - the widget resumes, so the host must clear the\n * message rather than leave a stale error on screen.\n */\n onContentError?(err: Error | null): void;\n}\n\nexport interface BindMcpAppOptions {\n /**\n * The sandbox iframe. The adapter creates and OWNS this element (mounts it in\n * its render model, sizes it, removes it on unmount). The session only\n * configures the sandbox contract (sandbox attr, testid, srcdoc) and talks to\n * it through the bridge - it never creates, moves, or removes the iframe.\n */\n iframe: HTMLIFrameElement;\n /** Returns the current activity content (resourceUri, serverHash, tool input/result). */\n getContent: () => MCPAppsActivityContent;\n /** Returns the current agent (may change across renders). */\n getAgent: () => AbstractAgent | undefined;\n /** CopilotKit host, for ui/message follow-up runs (issue #5819). */\n host: ɵMcpFollowUpHost;\n /**\n * The id of the activity message this session renders. When provided, the\n * session subscribes to the agent's message store, finds this activity, and\n * pushes its tool input/result to the widget itself (self-driving), so the\n * adapter does not re-implement the agent-driven forwarding loop.\n *\n * The store is authoritative only for activities that live in it. When a host\n * renders an activity from an EXTERNAL message list (e.g. CopilotChatView's\n * `messages` prop), that activity is not in `agent.messages`; the adapter must\n * then call `syncContent` on content change so the widget still receives its\n * tool input/result. Both paths share one dedup, so they never double-send.\n */\n messageId?: string;\n hooks?: McpAppSessionHooks;\n /**\n * Host identity, capabilities and UI context announced during the MCP Apps\n * initialization handshake, plus the two timeouts. Every field is optional and\n * merged over {@link MCP_APPS_SESSION_DEFAULTS}, so a frontend only overrides\n * what it exposes to its users.\n */\n options?: McpAppSessionOptions;\n /**\n * Decides whether `ui/open-link` may open a URL, and with what final value.\n *\n * Defaults to {@link denyDangerousSchemes}, the single policy every CopilotKit\n * frontend uses - no adapter overrides it, so a widget behaves the same in\n * React, Vue and Angular. This hook exists for a host with a genuinely\n * different security contract; prefer changing the shared policy over setting\n * it, otherwise widget behaviour becomes framework-dependent again.\n */\n openLinkPolicy?: McpAppOpenLinkPolicy;\n /**\n * Whether `teardown` also cancels a queued `ui/message` follow-up run.\n *\n * Defaults to `false`: the follow-up carries the user's message onwards, so it\n * outlives the widget that sent it. Hosts that scope follow-ups to the widget\n * (the Angular contract) can opt in.\n */\n cancelFollowUpsOnTeardown?: boolean;\n /** Require the fetched resource URI to match exactly (Angular compatibility). */\n requireExactResourceUri?: boolean;\n /** Release already-started proxy/follow-up waits on teardown, without aborting the underlying run. */\n cancelRunningWaitOnTeardown?: boolean;\n}\n\n/** Host identity announced during the initialization handshake. */\nexport interface McpAppHostInfo {\n name: string;\n version: string;\n}\n\nexport interface McpAppSessionOptions {\n /** Maximum time a queued request waits for a busy agent. Default 30s. */\n idleTimeoutMs?: number;\n /**\n * Maximum time to wait for the sandbox proxy handshake\n * (`ui/notifications/sandbox-proxy-ready`). Default 30s.\n *\n * This measures the SANDBOX step, not `ui/notifications/initialized`: a widget\n * that loads its proxy but never reports initialized is a different failure.\n */\n initializationTimeoutMs?: number;\n /** Host identity announced during the initialization handshake. */\n hostInfo?: McpAppHostInfo;\n /** Protocol capabilities announced to embedded MCP Apps. */\n hostCapabilities?: Record<string, unknown>;\n /** Non-secret UI context announced to embedded MCP Apps. */\n hostContext?: Record<string, unknown>;\n /**\n * Restore `allow-same-origin` on the sandbox frames. Default `false`.\n *\n * **Unsafe.** The sandbox proxy is loaded via `srcdoc`, so with this flag the\n * widget runs with the host page's origin: it can read the host's cookies,\n * storage and DOM, and call the host's APIs as the signed-in user. Only set\n * it for widgets you wrote and trust that genuinely need `localStorage`,\n * `IndexedDB` or cookies. By default widgets get an opaque origin.\n */\n allowSameOriginFallback?: boolean;\n}\n\n/** Defaults every frontend inherits unless it overrides them. */\nexport const MCP_APPS_SESSION_DEFAULTS: Readonly<\n Required<McpAppSessionOptions>\n> = {\n idleTimeoutMs: MCP_APPS_QUEUE_IDLE_TIMEOUT_MS,\n initializationTimeoutMs: 30_000,\n hostInfo: { name: \"CopilotKit MCP Apps Host\", version: \"1.0.0\" },\n hostCapabilities: { openLinks: {}, logging: {}, message: { text: {} } },\n hostContext: { platform: \"web\" },\n allowSameOriginFallback: false,\n};\n\n/**\n * Returns the URL to open, or `undefined` to refuse. Receiving the raw string\n * (not a parsed URL) lets a policy resolve relative links itself.\n */\nexport type McpAppOpenLinkPolicy = (url: string) => string | undefined;\n\n/**\n * The MCP Apps link policy, shared by every frontend.\n *\n * Three independent rules, deliberately kept as ONE policy so a widget behaves\n * the same whichever framework hosts it:\n *\n * 1. **Scheme denylist**, not an allowlist. Only the schemes that execute script\n * or render attacker-controlled HTML are refused (`javascript:`, `data:`,\n * `vbscript:`, `blob:`, `file:`). Everything else is allowed, including\n * app-defined deep links (`myapp:`, `whatsapp:`), which hand off to an OS\n * handler rather than executing in the page. An allowlist could never\n * enumerate those, and restricting to http/https would break them.\n * 2. **Embedded credentials refused** (`https://user:pw@host`): a widget must not\n * hand the browser a URL carrying someone's credentials.\n * 3. **Path-relative links resolved** against the host document, so `/docs`,\n * `./x` and `../x` open instead of failing URL parsing. Only those three\n * forms: every string is technically a valid relative reference, so anything\n * else stays refused rather than becoming a navigation on the host origin.\n * This does mean a widget can reach a path of the HOST application - the same\n * reach a normal anchor in the page would have.\n *\n * Rules 2 and 3 come from the Angular host, which enforced them before it moved\n * onto this session; rule 1 is the CopilotKit product decision (it matches the\n * Anthropic Software Directory policy: https origins plus owned custom URI\n * schemes). Merging them means no frontend overrides anything.\n */\nexport const denyDangerousSchemes: McpAppOpenLinkPolicy = (url) => {\n let parsed: URL;\n let absolute = true;\n try {\n parsed = new URL(url);\n } catch {\n // Not absolute. Resolve only what is unambiguously a path reference: per the\n // URL spec ANY string is a valid relative reference, so resolving blindly\n // would turn \"not a url\" into a navigation on the host origin.\n if (!/^(\\/|\\.\\/|\\.\\.\\/)/.test(url)) return undefined;\n absolute = false;\n try {\n parsed = new URL(url, window.location.href);\n } catch {\n return undefined;\n }\n // A leading \"/\" does not guarantee the resolution stays on the host: per the\n // URL spec a backslash is normalized to \"/\" inside the path of a\n // special-scheme base, so \"/\\evil.com\" parses as a protocol-relative\n // authority and resolves to \"http://evil.com/\". Rule 3 promises a relative\n // link reaches a path of the HOST application, so require the origin to be\n // unchanged. Only reachable through the relative branch, so an absolute URL\n // is still handed back exactly as the widget wrote it.\n if (parsed.origin !== window.location.origin) return undefined;\n }\n if (MCP_OPEN_LINK_BLOCKED_SCHEMES.has(parsed.protocol)) return undefined;\n if (parsed.username || parsed.password) return undefined;\n // An absolute URL is handed back exactly as the widget wrote it: `href`\n // normalisation would rewrite it (adding a trailing slash, reserialising a\n // custom-scheme deep link). Only a relative link needs the resolved form,\n // since the raw string is not openable on its own.\n return absolute ? url : parsed.href;\n};\n\nexport interface McpAppSession {\n /** Forward the tool call input to the widget (host -> app). Buffered until ready. */\n sendToolInput(args: Record<string, unknown>): void;\n /** Forward the tool result to the widget (host -> app). Buffered until ready. */\n sendToolResult(result: CallToolResult): void;\n /**\n * Forward the tool input/result carried by `content` to the widget, deduped so\n * an unchanged value is not re-sent. The prop-driven counterpart to the agent\n * subscription: the adapter calls this on content change so activities rendered\n * from an external message list (absent from `agent.messages`) still reach the\n * widget. No-op for values already sent (shared dedup with the subscription).\n *\n * Content is validated here exactly as it is on the store path: a rejected\n * value is not forwarded and surfaces through `onContentError`.\n */\n syncContent(content: MCPAppsActivityContent): void;\n /** Disconnect the bridge and release listeners. Does NOT remove the iframe. */\n teardown(): void;\n}\n\n/**\n * Bind an MCP App to a host-provided sandbox iframe: fetch the widget resource\n * through the agent, connect the ext-apps `AppBridge` over a PostMessage\n * transport, and wire the app<->host protocol (ui/message, ui/open-link,\n * tools/call + resources/read proxy, size, host context). Framework-agnostic:\n * the React/Vue/Angular renderers create the iframe and wire reactive state via\n * `hooks`, but all protocol logic lives here.\n */\nexport function bindMcpApp(opts: BindMcpAppOptions): McpAppSession {\n const {\n iframe,\n getContent,\n getAgent,\n host,\n messageId,\n hooks,\n options,\n openLinkPolicy = denyDangerousSchemes,\n cancelFollowUpsOnTeardown = false,\n } = opts;\n // Frontend-supplied options merged over the shared defaults, so a host only\n // overrides what it actually exposes (Angular's provideMCPApps merge, lifted).\n const settings = { ...MCP_APPS_SESSION_DEFAULTS, ...options };\n\n // The widget resource identity this session is bound to, captured once at bind\n // time. The store subscription refuses to forward content for any other\n // identity (see `pushFromContent`).\n const boundIdentity = identityKeyOf(getContent());\n\n // Ownership token for this session's queued work. Widget-scoped requests\n // (resources/read, tools/call) exist only to feed THIS iframe, so `teardown`\n // cancels the ones still waiting.\n //\n // The `ui/message` follow-up run is owned only when the host asks for it via\n // `cancelFollowUpsOnTeardown` (the Angular contract). Left unowned - the\n // default, used by React and Vue - it survives the widget, because it carries\n // the user's message onwards rather than feeding the iframe.\n const queueOwner = {};\n\n let disposed = false;\n let ready = false;\n let bridge: AppBridge | null = null;\n let pendingToolInput: Record<string, unknown> | undefined;\n let pendingToolResult: CallToolResult | undefined;\n // Self-driving mode (messageId set): dedup keys so a re-emitted activity with\n // unchanged tool input/result does not re-notify the widget, and the agent\n // subscription handle so teardown can unsubscribe.\n let lastToolInputKey: string | undefined;\n let lastToolResultKey: string | undefined;\n // Last content that failed validation, so the same rejection is not reported\n // again on every subsequent update. Shared by both sources: the widget has a\n // single error state, whether the content came from the store or from a prop.\n let lastInvalidContentKey: string | undefined;\n let activitySub: { unsubscribe(): void } | null = null;\n // Sandbox handshake watchdog (see initializationTimeoutMs).\n let sandboxTimer: ReturnType<typeof setTimeout> | undefined;\n let sandboxReady = false;\n let sandboxTimedOut = false;\n\n /** Flush any buffered tool input/result to the widget once it is initialized. */\n const flushPending = () => {\n if (!ready || !bridge) return;\n if (pendingToolInput !== undefined) {\n void bridge.sendToolInput({ arguments: pendingToolInput });\n pendingToolInput = undefined;\n }\n if (pendingToolResult !== undefined) {\n void bridge.sendToolResult(pendingToolResult);\n pendingToolResult = undefined;\n }\n };\n\n /**\n * Report content the schema rejected. RECOVERABLE: the session keeps running\n * and resumes as soon as valid content arrives, so this never goes through the\n * fatal `onError` channel. Deduped on the offending value, since store updates\n * fire for every message change, not just this activity's.\n */\n const reportContentRejected = (\n value: unknown,\n error: { message: string },\n ) => {\n const key = keyOf(value);\n if (key === lastInvalidContentKey) return;\n lastInvalidContentKey = key;\n hooks?.onContentError?.(\n new Error(\n `[MCPAppsRenderer] Activity content for message \"${messageId ?? \"(no id)\"}\" does not match the MCP Apps content schema, so it was not forwarded to the widget: ${error.message}`,\n ),\n );\n };\n\n /** Valid content resumed: clear the message the host shows for a rejection. */\n const clearContentRejection = () => {\n if (lastInvalidContentKey === undefined) return;\n lastInvalidContentKey = undefined;\n hooks?.onContentError?.(null);\n };\n\n /**\n * Push tool input/result from an activity content to the widget, deduped so an\n * unchanged value (e.g. a re-emitted snapshot) is not re-sent. Buffered by the\n * imperative sender until the widget is initialized.\n *\n * The single forwarding path for BOTH sources - the store subscription\n * (`pushFromMessages`) and the adapter props (`syncContent`) - so validation,\n * the identity guard and recoverable-error reporting behave identically\n * whichever one produced the content.\n */\n const pushFromContent = (content: MCPAppsActivityContent) => {\n // Identity guard: only forward tool input/result for the resource this\n // session is bound to. If the store activity for this messageId has been\n // replaced by a different widget (resourceUri/serverHash/serverId), pushing\n // here would leak the new widget's data into this (old, still-mounted) iframe\n // before the adapter tears the session down and re-binds for the new\n // identity. Refuse it; the fresh session will forward the new widget's data.\n // Validate the WHOLE content before anything is forwarded. `toolInput` and\n // `result` describe one exchange: sending the input and only then finding\n // the result invalid would leave the widget half-updated, and a toolInput\n // that is not a record must not reach it just because the result happens to\n // parse. Content arriving from an adapter prop is as untrusted as the\n // store's, so both go through the same schema here. A rejection is\n // RECOVERABLE (reported through onContentError, cleared when valid content\n // returns), not a fatal session error.\n const parsedContent = MCPAppsActivityContentSchema.safeParse(content);\n if (!parsedContent.success) {\n reportContentRejected(content, parsedContent.error);\n return;\n }\n const validated = parsedContent.data;\n if (identityKeyOf(validated) !== boundIdentity) return;\n const { toolInput } = validated;\n const validResult = validated.result as CallToolResult | undefined;\n clearContentRejection();\n\n if (toolInput !== undefined) {\n const key = keyOf(toolInput);\n if (key !== lastToolInputKey) {\n lastToolInputKey = key;\n pendingToolInput = toolInput;\n flushPending();\n }\n }\n if (validResult !== undefined) {\n const key = keyOf(validResult);\n if (key !== lastToolResultKey) {\n lastToolResultKey = key;\n pendingToolResult = validResult;\n flushPending();\n }\n }\n };\n\n /**\n * Push the CURRENT content of this activity (read from the agent's message\n * store, the authoritative post-apply source) to the widget. Used both at\n * initialize and on every `onMessagesChanged`, so the widget always reflects\n * the applied state - never a stale React prop or a pre-apply activity message.\n * Store path only (requires `messageId`); the props path goes through\n * `syncContent`. `messages` overrides the store lookup when provided.\n */\n const pushFromMessages = (messages?: readonly ActivityLike[]) => {\n if (disposed || !messageId) return;\n const list = (messages ??\n (getAgent()?.messages as readonly ActivityLike[] | undefined)) as\n | readonly ActivityLike[]\n | undefined;\n const msg = list?.find((m) => m?.id === messageId);\n if (!msg || msg.activityType !== MCPAppsActivityType) return;\n const parsed = MCPAppsActivityContentSchema.safeParse(msg.content);\n if (!parsed.success) {\n // Rejected content is NOT forwarded, but the failure must be observable\n // rather than a silent no-op: otherwise the widget simply never receives\n // its result and nothing says why.\n reportContentRejected(msg.content, parsed.error);\n return;\n }\n // pushFromContent clears the rejection once it has validated the result.\n pushFromContent(parsed.data);\n };\n\n /** True when this activity currently lives in the agent's message store. */\n const activityInStore = (): boolean =>\n !!(getAgent()?.messages as readonly ActivityLike[] | undefined)?.some(\n (m) => m?.id === messageId && m?.activityType === MCPAppsActivityType,\n );\n\n /** Fetch the widget resource (`resources/read`) through the agent proxy queue. */\n const fetchResource = async (): Promise<FetchedResource> => {\n const agent = getAgent();\n if (!agent) {\n throw new Error(\"No agent available to fetch resource\");\n }\n const { resourceUri, serverHash, serverId } = getContent();\n const readOnlyAgent = agent as AbstractAgent & {\n ɵrunMcpResourceRead?: AbstractAgent[\"runAgent\"];\n };\n const runResult = await mcpAppsRequestQueue.enqueue(\n agent,\n () => {\n const parameters = {\n forwardedProps: {\n __proxiedMCPRequest: {\n serverHash,\n serverId,\n method: \"resources/read\",\n params: { uri: resourceUri },\n },\n },\n };\n return readOnlyAgent.ɵrunMcpResourceRead\n ? readOnlyAgent.ɵrunMcpResourceRead(parameters)\n : agent.runAgent(parameters);\n },\n {\n owner: queueOwner,\n timeoutMs: settings.idleTimeoutMs,\n cancelRunningWait: opts.cancelRunningWaitOnTeardown,\n // The widget belongs to the thread it was rendered in: running its fetch\n // against a thread the host switched to would load it into the wrong\n // conversation.\n dropAfterThreadSwitch: true,\n },\n );\n const resultData = runResult.result as\n | { contents?: FetchedResource[] }\n | undefined;\n const resource = selectResource(\n resultData?.contents,\n resourceUri,\n opts.requireExactResourceUri,\n );\n if (!resource) {\n throw new Error(\"No resource content in response\");\n }\n return resource;\n };\n\n /**\n * Terminal shutdown, owned by the session itself.\n *\n * Used by `teardown()` AND by the sandbox watchdog: once the handshake window\n * closes, the session must stop serving this widget rather than leave the\n * bridge and its handlers live until the adapter happens to unmount. It does\n * NOT remove the iframe - the adapter owns that element.\n *\n * Idempotent.\n */\n const closeSession = () => {\n if (disposed) return;\n disposed = true;\n if (sandboxTimer !== undefined) {\n clearTimeout(sandboxTimer);\n sandboxTimer = undefined;\n }\n // Drop this widget's still-waiting proxy requests: they only exist to feed\n // an iframe that is going away. Requests already in flight keep running\n // (runAgent has no abort), and other widgets' queued work is untouched.\n mcpAppsRequestQueue.cancelOwner(queueOwner);\n activitySub?.unsubscribe();\n activitySub = null;\n const b = bridge;\n bridge = null;\n void b?.close();\n };\n\n /**\n * Fetch the resource, configure + load the sandbox iframe, construct the\n * AppBridge, wire the app->host handlers, and connect the transport.\n */\n const setup = async () => {\n try {\n const resource = await fetchResource();\n if (disposed) return;\n hooks?.onResource?.(resource);\n\n // Configure the sandbox iframe (contract shared across frontends). The\n // same flags go to the widget frame in sandbox-resource-ready below.\n const sandbox = ɵmcpAppSandboxFlags(settings.allowSameOriginFallback);\n iframe.setAttribute(\"sandbox\", sandbox);\n // Cross-frontend MCP-apps surface contract: every frontend must expose the\n // sandbox iframe under the SAME testid so one shared probe (harness\n // `d5-mcp-apps`) and one shared e2e spec can assert the surface mounted\n // without per-frontend selectors.\n iframe.setAttribute(\"data-testid\", \"mcp-app-iframe\");\n iframe.setAttribute(\"title\", \"Interactive MCP application\");\n\n const cspDomains = resource._meta?.ui?.csp?.resourceDomains;\n iframe.srcdoc = buildSandboxHTML(cspDomains);\n\n const win = iframe.contentWindow;\n if (!win) {\n throw new Error(\"Sandbox iframe has no contentWindow\");\n }\n\n let html: string;\n if (resource.text) {\n html = resource.text;\n } else if (resource.blob) {\n html = ɵdecodeBase64(resource.blob);\n } else {\n throw new Error(\"Resource has no text or blob content\");\n }\n\n bridge = new AppBridge(\n null,\n settings.hostInfo,\n settings.hostCapabilities,\n // Seed the host context at construction so it is already in place when\n // the widget's ui/initialize is handled (deterministic, not a race).\n {\n hostContext: {\n // The theme follows CopilotKit's dark selector (a `.dark`\n // ancestor) unless the host configured one explicitly.\n theme: iframe.closest(\".dark\") ? \"dark\" : \"light\",\n ...settings.hostContext,\n },\n },\n );\n\n // Sandbox handshake: on proxy ready, load the widget HTML into the inner\n // sandboxed iframe.\n // The sandbox proxy must report back within initializationTimeoutMs. This\n // measures the SANDBOX handshake (sandbox-proxy-ready), not the widget's\n // later `initialized` notification - a widget that loads but never reports\n // initialized is a different failure and is not covered here.\n sandboxTimer = setTimeout(() => {\n if (disposed || sandboxReady) return;\n // Mark the handshake window closed: a proxy that reports ready after the\n // deadline must not silently resurrect a session the host already\n // surfaced as failed.\n sandboxTimedOut = true;\n // Report first (closeSession sets `disposed`, which gates the hooks),\n // then terminate: the widget never handshaked, so keeping the bridge and\n // its handlers alive would let a late iframe still proxy runs through us.\n hooks?.onError?.(\n new Error(\n `[MCPAppsRenderer] Timed out after ${settings.initializationTimeoutMs}ms waiting for the MCP App sandbox to initialize.`,\n ),\n );\n closeSession();\n }, settings.initializationTimeoutMs);\n\n bridge.onsandboxready = () => {\n if (sandboxTimedOut) {\n console.warn(\n \"[MCPAppsRenderer] Ignoring a sandbox handshake that arrived after the initialization timeout.\",\n );\n return;\n }\n sandboxReady = true;\n if (sandboxTimer !== undefined) {\n clearTimeout(sandboxTimer);\n sandboxTimer = undefined;\n }\n void bridge?.sendSandboxResourceReady({ html, sandbox }).then(() => {\n if (!disposed) hooks?.onSandboxReady?.();\n });\n };\n\n // --- App -> host requests ---\n // ui/message: custom handler preserving CopilotKit role/followUp extensions\n // (via _meta.copilotkit first, then legacy top-level fields).\n bridge.setRequestHandler(CopilotKitUiMessageSchema, async (req) => {\n const currentAgent = getAgent();\n if (!currentAgent) {\n console.warn(\"[MCPAppsRenderer] ui/message: No agent available\");\n return { isError: false };\n }\n try {\n const params = req.params;\n const ck = (params._meta?.copilotkit ?? {}) as {\n role?: string;\n followUp?: boolean;\n };\n const role =\n (ck.role as \"user\" | \"assistant\") ||\n (params.role as \"user\" | \"assistant\") ||\n \"user\";\n const textContent =\n (\n params.content as\n | Array<{ type: string; text?: string }>\n | undefined\n )\n ?.filter((c) => c.type === \"text\" && c.text)\n .map((c) => c.text)\n .join(\"\\n\") || \"\";\n if (textContent) {\n currentAgent.addMessage({\n id: randomUUID(),\n role,\n content: textContent,\n });\n }\n const followUp = ck.followUp ?? params.followUp;\n const shouldFollowUp = followUp ?? role === \"user\";\n if (shouldFollowUp && textContent) {\n const capturedThreadId = currentAgent.threadId || \"default\";\n mcpAppsRequestQueue\n .enqueue(\n currentAgent,\n () =>\n ɵrunMcpFollowUp({\n host,\n agent: currentAgent,\n capturedThreadId,\n }),\n {\n // Honour the configured wait like the other proxied requests.\n // Ownership is deliberate policy, see cancelFollowUpsOnTeardown.\n timeoutMs: settings.idleTimeoutMs,\n owner: cancelFollowUpsOnTeardown ? queueOwner : undefined,\n cancelRunningWait: opts.cancelRunningWaitOnTeardown,\n },\n )\n .catch((err) => {\n if (disposed && cancelFollowUpsOnTeardown) return;\n console.error(\n \"[MCPAppsRenderer] ui/message agent run failed:\",\n err,\n );\n hooks?.onFollowUpError?.(\n err instanceof Error ? err : new Error(String(err)),\n );\n });\n }\n return { isError: false };\n } catch (err) {\n console.error(\"[MCPAppsRenderer] ui/message error:\", err);\n return { isError: true };\n }\n });\n\n bridge.onopenlink = async ({ url }) => {\n // The bridge validates `url` as a string but not its scheme. The policy\n // decides (and may rewrite, e.g. resolving a relative link).\n const allowed = openLinkPolicy(url);\n if (!allowed) {\n console.warn(\n \"[MCPAppsRenderer] ui/open-link rejected by policy:\",\n url,\n );\n return { isError: true };\n }\n window.open(allowed, \"_blank\", \"noopener,noreferrer\");\n return { isError: false };\n };\n\n bridge.oncalltool = async (params) => {\n const { serverHash, serverId } = getContent();\n const currentAgent = getAgent();\n if (!serverHash) {\n throw new Error(\"No server hash available for proxying\");\n }\n if (!currentAgent) {\n throw new Error(\"No agent available for proxying\");\n }\n let runResult;\n try {\n runResult = await mcpAppsRequestQueue.enqueue(\n currentAgent,\n () =>\n currentAgent.runAgent({\n forwardedProps: {\n __proxiedMCPRequest: {\n serverHash,\n serverId,\n method: \"tools/call\",\n params,\n },\n },\n }),\n {\n owner: queueOwner,\n timeoutMs: settings.idleTimeoutMs,\n cancelRunningWait: opts.cancelRunningWaitOnTeardown,\n dropAfterThreadSwitch: true,\n },\n );\n } catch (err) {\n // A call dropped by the thread guard must come back to the widget as\n // an explicit JSON-RPC error. Swallowing it would leave the caller\n // waiting for a response that can never arrive.\n if (err instanceof MCPAppsQueueThreadChangedError) {\n throw new Error(\n `tools/call was not executed: ${err.message} Retry from the current thread.`,\n { cause: err },\n );\n }\n throw err;\n }\n return MCPAppsActivityContentSchema.shape.result.parse(\n runResult.result ?? {},\n );\n };\n\n // --- App -> host notifications ---\n bridge.onsizechange = (p) => {\n if (disposed) return;\n const { width, height } = (p || {}) as {\n width?: number;\n height?: number;\n };\n hooks?.onSizeChanged?.({\n width: typeof width === \"number\" ? width : undefined,\n height: typeof height === \"number\" ? height : undefined,\n });\n };\n bridge.oninitialized = () => {\n if (disposed) return;\n ready = true;\n hooks?.onInitialized?.();\n // Self-driving: reconcile the buffers BEFORE the first flush. When this\n // activity lives in the store, the store is authoritative, so discard any\n // prop-seeded buffers - e.g. an activity that was absent at bind time and\n // seeded via syncContent, then appeared in the store with the applied\n // content during the resource fetch - and push the CURRENT store content\n // instead. Clearing first means a stale pre-init value is never sent\n // ahead of (or instead of) the applied one; reading from the store - not\n // getContent() - honors an update that arrived before initialize.\n if (messageId && activityInStore()) {\n pendingToolInput = undefined;\n pendingToolResult = undefined;\n lastToolInputKey = undefined;\n lastToolResultKey = undefined;\n pushFromMessages();\n }\n flushPending();\n };\n bridge.onloggingmessage = (p) => {\n console.log(\"[MCPAppsRenderer] App log:\", p);\n };\n\n const transport = new PostMessageTransport(win, win);\n await bridge.connect(transport);\n if (disposed) {\n await bridge.close();\n bridge = null;\n return;\n }\n\n // Self-driving: subscribe to the agent and push tool input/result for THIS\n // activity to the widget, so the framework adapter does not forward them.\n //\n // We read from `onMessagesChanged`, NOT `onActivitySnapshotEvent` /\n // `onActivityDeltaEvent`: those fire with the PRE-update `activityMessage`\n // (the snapshot's new content / the delta patch is applied only after the\n // callback returns), so reading them yields stale content and the dedup\n // below can suppress the send entirely. `onMessagesChanged` fires AFTER the\n // store is updated, so `messages` holds the applied content - and it also\n // covers full messages-snapshot updates, which the activity callbacks miss.\n if (messageId) {\n activitySub =\n getAgent()?.subscribe({\n onMessagesChanged: ({ messages }) =>\n pushFromMessages(messages as readonly ActivityLike[]),\n }) ?? null;\n }\n } catch (err) {\n console.error(\"[MCPAppsRenderer] Setup error:\", err);\n if (!disposed) {\n hooks?.onError?.(err instanceof Error ? err : new Error(String(err)));\n }\n }\n };\n\n void setup();\n\n return {\n sendToolInput(args) {\n pendingToolInput = args;\n flushPending();\n },\n sendToolResult(result) {\n pendingToolResult =\n MCPAppsActivityContentSchema.shape.result.parse(result);\n flushPending();\n },\n syncContent(content) {\n // Store precedence: when this activity lives in the agent's message store,\n // the subscription is authoritative (it reads the applied post-update\n // content), so ignore the prop to avoid pushing a possibly-stale React\n // prop over it. Forward props only for activities absent from the store\n // (rendered from an external messages list).\n if (messageId && activityInStore()) return;\n pushFromContent(content);\n },\n teardown() {\n closeSession();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;AAgCA,SAAS,MAAM,OAAwB;AACrC,KAAI;AACF,SAAO,KAAK,UAAU,MAAM,IAAI;SAC1B;AACN,SAAO;;;;;;;;;;;;AAaX,SAAgB,cAAc,OAAuB;AACnD,KAAI;EACF,MAAM,SAAS,KAAK,MAAM;EAC1B,MAAM,QAAQ,WAAW,KAAK,SAAS,cACrC,UAAU,WAAW,EAAE,CACxB;AACD,SAAO,IAAI,aAAa,CAAC,OAAO,MAAM;SAChC;AACN,QAAM,IAAI,MAAM,wDAAwD;;;;;;;;;;;AAY5E,SAAS,eACP,UACA,aACA,eAAe,OACc;CAC7B,MAAM,QAAQ,UAAU,MAAM,cAAc,UAAU,QAAQ,YAAY;AAC1E,KAAI,MAAO,QAAO;AAClB,QAAO,CAAC,gBAAgB,UAAU,WAAW,IAAI,SAAS,KAAK;;;;;;;;;AAUjE,SAAS,cAAc,SAIZ;AAKT,QAAO,KAAK,UAAU;EACpB,QAAQ,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EACpB,oBAAoB,EAAE,eACpB,iBAAiB,SAAoC,EACxD,CAAC,IAAI;WAEH,KAAK;AACZ,WAAQ,MAAM,kCAAkC,IAAI;AACpD,OAAI,CAAC,SACH,QAAO,UAAU,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,IAAI,CAAC,CAAC;;;AAK3E,CAAK,OAAO;AAEZ,QAAO;EACL,cAAc,MAAM;AAClB,sBAAmB;AACnB,iBAAc;;EAEhB,eAAe,QAAQ;AACrB,uBACE,6BAA6B,MAAM,OAAO,MAAM,OAAO;AACzD,iBAAc;;EAEhB,YAAY,SAAS;AAMnB,OAAI,aAAa,iBAAiB,CAAE;AACpC,mBAAgB,QAAQ;;EAE1B,WAAW;AACT,iBAAc;;EAEjB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@copilotkit/mcp-apps-renderer",
3
- "version": "2.0.0-rc.4",
3
+ "version": "2.0.0-rc.41",
4
4
  "private": false,
5
5
  "description": "Framework-agnostic MCP Apps host for CopilotKit - the app<->host protocol (ext-apps AppBridge), sandbox proxy, and shared renderer consumed by the React, Vue, and Angular frontends",
6
6
  "keywords": [
@@ -14,6 +14,9 @@
14
14
  ],
15
15
  "homepage": "https://github.com/CopilotKit/CopilotKit",
16
16
  "license": "MIT",
17
+ "engines": {
18
+ "node": ">=20"
19
+ },
17
20
  "repository": {
18
21
  "type": "git",
19
22
  "url": "git+https://github.com/CopilotKit/CopilotKit.git",
@@ -25,6 +28,13 @@
25
28
  "type": "module",
26
29
  "module": "./dist/index.mjs",
27
30
  "types": "./dist/index.d.mts",
31
+ "typesVersions": {
32
+ "*": {
33
+ "activity": [
34
+ "./dist/activity.d.cts"
35
+ ]
36
+ }
37
+ },
28
38
  "exports": {
29
39
  ".": {
30
40
  "import": {
@@ -48,22 +58,21 @@
48
58
  "access": "public"
49
59
  },
50
60
  "dependencies": {
51
- "@copilotkit/shared": "2.0.0-rc.4",
61
+ "@copilotkit/shared": "2.0.0-rc.41",
52
62
  "@modelcontextprotocol/ext-apps": "^1.7.5",
53
- "@modelcontextprotocol/sdk": "^1.29.0"
63
+ "@modelcontextprotocol/sdk": "^1.29.0",
64
+ "zod": "^4.2.0"
54
65
  },
55
66
  "peerDependencies": {
56
- "@ag-ui/client": ">=0.0.59",
57
- "zod": ">=3.25"
67
+ "@ag-ui/client": "^1.0.2"
58
68
  },
59
69
  "devDependencies": {
60
- "@ag-ui/client": "1.0.2",
70
+ "@ag-ui/client": "1.0.4",
61
71
  "@modelcontextprotocol/sdk": "^1.29.0",
62
72
  "jsdom": "^26.1.0",
63
73
  "tsdown": "^0.20.3",
64
74
  "typescript": "5.9.2",
65
- "vitest": "^3.2.4",
66
- "zod": "^3.25.76"
75
+ "vitest": "^3.2.4"
67
76
  },
68
77
  "scripts": {
69
78
  "build": "tsdown",