@copilotkit/mcp-apps-renderer 2.0.0-rc.2 → 2.0.0-rc.20
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.
- package/dist/_virtual/_rolldown/runtime.cjs +29 -0
- package/dist/activity.umd.js +63 -35
- package/dist/activity.umd.js.map +1 -1
- package/dist/content-schema.cjs +37 -35
- package/dist/content-schema.cjs.map +1 -1
- package/dist/content-schema.d.cts +40 -3309
- package/dist/content-schema.d.cts.map +1 -1
- package/dist/content-schema.d.mts +40 -3309
- package/dist/content-schema.d.mts.map +1 -1
- package/dist/content-schema.mjs +2 -2
- package/dist/content-schema.mjs.map +1 -1
- package/dist/request-queue.mjs.map +1 -1
- package/dist/session.mjs +2 -2
- package/dist/session.mjs.map +1 -1
- package/package.json +9 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"content-schema.d.mts","names":[],"sources":["../src/content-schema.ts"],"mappings":";;;;cA8Fa,4BAAA,EAA4B,CAAA,CAAA,SAAA
|
|
1
|
+
{"version":3,"file":"content-schema.d.mts","names":[],"sources":["../src/content-schema.ts"],"mappings":";;;;cA8Fa,4BAAA,EAA4B,CAAA,CAAA,SAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAU7B,sBAAA,GAAyB,CAAA,CAAE,KAAA,QAC9B,4BAAA"}
|
package/dist/content-schema.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import
|
|
1
|
+
import * as z from "zod";
|
|
2
2
|
|
|
3
3
|
//#region src/content-schema.ts
|
|
4
|
-
const looseObject = (shape) => z.object(shape).
|
|
4
|
+
const looseObject = (shape) => z.object(shape).loose();
|
|
5
5
|
const metaSchema = z.record(z.string(), z.unknown());
|
|
6
6
|
const annotationsSchema = looseObject({
|
|
7
7
|
audience: z.array(z.enum(["user", "assistant"])).optional(),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"content-schema.mjs","names":[],"sources":["../src/content-schema.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"file":"content-schema.mjs","names":[],"sources":["../src/content-schema.ts"],"sourcesContent":["import * as z from \"zod\";\n\n// Keep /activity bridge-free: the MCP SDK is only used as a test oracle.\n// This is the Angular host's content contract, expressed using our zod API.\nconst looseObject = <T extends z.ZodRawShape>(shape: T) =>\n z.object(shape).loose();\n\n// `_meta` is an extension channel, so its CONTENTS stay unconstrained - but the\n// SDK still requires it to be an object, and a string or array there is a bug\n// worth catching rather than forwarding.\nconst metaSchema = z.record(z.string(), z.unknown());\n\nconst annotationsSchema = looseObject({\n audience: z.array(z.enum([\"user\", \"assistant\"])).optional(),\n priority: z.number().min(0).max(1).optional(),\n lastModified: z.string().optional(),\n});\n\n// Validated by decoding, mirroring the MCP SDK's own base64 check, rather than\n// by pattern. The pattern this replaces additionally required canonical padding,\n// which the SDK does not: it accepts an unpadded payload that we rejected. Since\n// one bad block fails the whole content array, that cost the entire widget.\nconst base64Schema = z.string().refine((value) => {\n try {\n atob(value);\n return true;\n } catch {\n return false;\n }\n}, \"Expected base64-encoded data\");\n\nconst resourceContentsSchema = z.union([\n looseObject({\n uri: z.string(),\n mimeType: z.string().optional(),\n text: z.string(),\n _meta: metaSchema.optional(),\n }),\n looseObject({\n uri: z.string(),\n mimeType: z.string().optional(),\n blob: base64Schema,\n _meta: metaSchema.optional(),\n }),\n]);\n\nconst contentItemSchema = z.discriminatedUnion(\"type\", [\n looseObject({\n type: z.literal(\"text\"),\n text: z.string(),\n annotations: annotationsSchema.optional(),\n _meta: metaSchema.optional(),\n }),\n looseObject({\n type: z.literal(\"image\"),\n data: base64Schema,\n mimeType: z.string(),\n annotations: annotationsSchema.optional(),\n _meta: metaSchema.optional(),\n }),\n looseObject({\n type: z.literal(\"audio\"),\n data: base64Schema,\n mimeType: z.string(),\n annotations: annotationsSchema.optional(),\n _meta: metaSchema.optional(),\n }),\n looseObject({\n type: z.literal(\"resource\"),\n resource: resourceContentsSchema,\n annotations: annotationsSchema.optional(),\n _meta: metaSchema.optional(),\n }),\n looseObject({\n type: z.literal(\"resource_link\"),\n uri: z.string(),\n name: z.string(),\n title: z.string().optional(),\n description: z.string().optional(),\n mimeType: z.string().optional(),\n size: z.number().optional(),\n annotations: annotationsSchema.optional(),\n _meta: metaSchema.optional(),\n }),\n]);\n\nconst callToolResultSchema = looseObject({\n content: z.array(contentItemSchema).default([]),\n structuredContent: z.record(z.string(), z.unknown()).optional(),\n isError: z.boolean().optional(),\n _meta: z.record(z.string(), z.unknown()).optional(),\n});\n\n/** Activity input accepts an omitted result.content; validation defaults it to []. */\nexport const MCPAppsActivityContentSchema = looseObject({\n result: callToolResultSchema,\n resourceUri: z.string(),\n serverHash: z.string(),\n serverId: z.string().optional(),\n toolInput: z.record(z.string(), z.unknown()).optional(),\n});\n\n// Keep the public input contract compatible with structured-only results.\n// Parsed output is normalized before it crosses the bridge.\nexport type MCPAppsActivityContent = z.input<\n typeof MCPAppsActivityContentSchema\n>;\n"],"mappings":";;;AAIA,MAAM,eAAwC,UAC5C,EAAE,OAAO,MAAM,CAAC,OAAO;AAKzB,MAAM,aAAa,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,SAAS,CAAC;AAEpD,MAAM,oBAAoB,YAAY;CACpC,UAAU,EAAE,MAAM,EAAE,KAAK,CAAC,QAAQ,YAAY,CAAC,CAAC,CAAC,UAAU;CAC3D,UAAU,EAAE,QAAQ,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,UAAU;CAC7C,cAAc,EAAE,QAAQ,CAAC,UAAU;CACpC,CAAC;AAMF,MAAM,eAAe,EAAE,QAAQ,CAAC,QAAQ,UAAU;AAChD,KAAI;AACF,OAAK,MAAM;AACX,SAAO;SACD;AACN,SAAO;;GAER,+BAA+B;AAElC,MAAM,yBAAyB,EAAE,MAAM,CACrC,YAAY;CACV,KAAK,EA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mB,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,SAAS,CAAC,CAAC,UAAU;CAC/D,SAAS,EAAE,SAAS,CAAC,UAAU;CAC/B,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,SAAS,CAAC,CAAC,UAAU;CACpD,CAAC;;AAGF,MAAa,+BAA+B,YAAY;CACtD,QAAQ;CACR,aAAa,EAAE,QAAQ;CACvB,YAAY,EAAE,QAAQ;CACtB,UAAU,EAAE,QAAQ,CAAC,UAAU;CAC/B,WAAW,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,SAAS,CAAC,CAAC,UAAU;CACxD,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request-queue.mjs","names":[],"sources":["../src/request-queue.ts"],"sourcesContent":["import type { AbstractAgent, RunAgentResult } from \"@ag-ui/client\";\n\n/**\n * How long a queued request waits for a busy agent before it is rejected.\n * A stuck run would otherwise hold the whole queue (and the widget's loading\n * state) forever. The Vue host enforced this before the shared extraction; it\n * now applies to every frontend.\n */\nexport const MCP_APPS_QUEUE_IDLE_TIMEOUT_MS = 30_000;\n\n/**\n * Raised when queued work is dropped because the agent moved to another thread\n * between enqueue and execution. Distinguishable so callers can answer the\n * requester explicitly instead of leaving it waiting.\n */\nexport class MCPAppsQueueThreadChangedError extends Error {\n constructor(\n readonly originThreadId: string,\n readonly currentThreadId: string,\n ) {\n super(\n `[CopilotKit] MCP app request dropped: the agent moved from thread \"${originThreadId}\" to \"${currentThreadId}\" while it was queued.`,\n );\n this.name = \"MCPAppsQueueThreadChangedError\";\n }\n}\n\n/** Options accepted by {@link MCPAppsRequestQueue.enqueue}. */\nexport interface MCPAppsEnqueueOptions {\n /**\n * Identifies the caller that owns this request, so `cancelOwner` can drop the\n * work of a single widget without touching requests queued by other widgets\n * (the pre-extraction `cancel(threadId)` was too broad: it rejected everything\n * sharing a thread).\n */\n owner?: object;\n /** Override the busy-agent wait timeout. Defaults to 30s. */\n timeoutMs?: number;\n /** Also release an executing request's wait on owner cancellation (does not stop its run). */\n cancelRunningWait?: boolean;\n /**\n * Drop the request instead of running it when the agent has switched threads\n * since it was enqueued.\n *\n * The queue is keyed by agent AND thread, but that only decides which FIFO the\n * work joins: a single shared agent object can have its `threadId` mutated in\n * place while the work waits, so executing later would run a thread-1 request\n * against thread-2 - and stream into it (issue #5819's failure mode, applied\n * to the proxy paths).\n */\n dropAfterThreadSwitch?: boolean;\n}\n\ninterface QueueItem {\n execute: (signal: AbortSignal) => Promise<RunAgentResult>;\n cancelRunningWait?: boolean;\n resolve: (result: RunAgentResult) => void;\n reject: (error: Error) => void;\n owner?: object;\n timeoutMs: number;\n /** Aborted by `cancelOwner`, so an active idle wait stops immediately. */\n controller: AbortController;\n /** Thread the agent was on when this work was enqueued. */\n originThreadId: string;\n dropAfterThreadSwitch?: boolean;\n /**\n * Set once `execute()` has actually been invoked. The run itself can no longer\n * be cancelled (runAgent exposes no abort), but the caller's WAIT still can:\n * with `cancelRunningWait`, `cancelOwner` aborts the signal and settles the\n * requester instead of leaving it pending.\n */\n executing?: boolean;\n /** Set by `cancelOwner` for work that must not run. */\n cancelled?: boolean;\n}\n\n/** Stable per-agent id, so two agents sharing a threadId keep separate queues. */\nconst agentKeys = new WeakMap<AbstractAgent, string>();\nlet nextAgentKey = 0;\nfunction keyFor(agent: AbstractAgent): string {\n let key = agentKeys.get(agent);\n if (!key) {\n key = `agent-${nextAgentKey++}`;\n agentKeys.set(agent, key);\n }\n return `${key}::${agent.threadId || \"default\"}`;\n}\n\n/**\n * Queue for serializing MCP app requests to an agent.\n * Ensures requests wait for the agent to stop running and are processed one at a time.\n */\nexport class MCPAppsRequestQueue {\n private queues = new Map<string, QueueItem[]>();\n private processing = new Map<string, boolean>();\n\n /**\n * Add a request to the queue for a specific agent thread.\n * Returns a promise that resolves when the request completes.\n */\n async enqueue(\n agent: AbstractAgent,\n request: (signal: AbortSignal) => Promise<RunAgentResult>,\n options?: MCPAppsEnqueueOptions,\n ): Promise<RunAgentResult> {\n // Keyed by agent AND thread: a shared thread id must not serialize (or\n // cancel) work belonging to a different agent.\n const key = keyFor(agent);\n\n return new Promise((resolve, reject) => {\n let queue = this.queues.get(key);\n if (!queue) {\n queue = [];\n this.queues.set(key, queue);\n }\n\n queue.push({\n execute: request,\n cancelRunningWait: options?.cancelRunningWait,\n resolve,\n reject,\n owner: options?.owner,\n timeoutMs: options?.timeoutMs ?? MCP_APPS_QUEUE_IDLE_TIMEOUT_MS,\n controller: new AbortController(),\n originThreadId: agent.threadId || \"default\",\n dropAfterThreadSwitch: options?.dropAfterThreadSwitch,\n });\n\n // Start processing if not already running\n this.processQueue(key, agent);\n });\n }\n\n /**\n * Drop every request queued by `owner` that has not started executing yet,\n * rejecting its promise. Used by a widget teardown so work that only exists to\n * feed a now-unmounted iframe does not run against the agent later.\n *\n * By default this cancels waiting work only. `cancelRunningWait` also\n * releases an executing caller's wait and signals its callback; it does not\n * itself stop a runAgent call. The next item still waits for agent idle.\n */\n cancelOwner(owner: object): void {\n for (const queue of this.queues.values()) {\n for (const item of queue) {\n if (\n item.owner !== owner ||\n (item.executing && !item.cancelRunningWait) ||\n item.cancelled\n )\n continue;\n item.cancelled = true;\n // Abort first: an item already waiting on a busy agent must release its\n // timer and agent subscription now, not when the agent finally frees up.\n item.controller.abort();\n item.reject(\n new Error(\"[CopilotKit] MCP app request cancelled on teardown\"),\n );\n }\n }\n }\n\n /**\n * Drain a queue one request at a time, waiting for the agent to go idle before\n * each. Re-entrant-safe (a single processor per key) and drops the entries once\n * fully drained to keep the shared queue bounded.\n */\n private async processQueue(key: string, agent: AbstractAgent): Promise<void> {\n // If already processing this queue, return\n if (this.processing.get(key)) {\n return;\n }\n\n this.processing.set(key, true);\n\n try {\n const queue = this.queues.get(key);\n if (!queue) return;\n\n while (queue.length > 0) {\n const item = queue[0]!;\n\n // Cancelled before it got its turn: its promise is already rejected.\n if (item.cancelled) {\n queue.shift();\n continue;\n }\n\n try {\n // Wait for any active run to complete before processing\n await this.waitForAgentIdle(\n agent,\n item.timeoutMs,\n item.controller.signal,\n );\n\n // The owner may have torn down while we waited for the agent.\n if (item.cancelled) {\n queue.shift();\n continue;\n }\n\n // Thread guard: the agent object is shared and its `threadId` can be\n // mutated in place while work waits, so re-check right before running.\n // The queue key only decided which FIFO this joined, it does not pin\n // the agent's current thread.\n const currentThreadId = agent.threadId || \"default\";\n if (\n item.dropAfterThreadSwitch &&\n currentThreadId !== item.originThreadId\n ) {\n item.reject(\n new MCPAppsQueueThreadChangedError(\n item.originThreadId,\n currentThreadId,\n ),\n );\n queue.shift();\n continue;\n }\n\n // Execution itself is not aborted; callers may opt into releasing\n // their wait on teardown (the legacy Angular contract).\n item.executing = true;\n const execution = item.execute(item.controller.signal);\n const result = item.cancelRunningWait\n ? await waitWithAbort(execution, item.controller.signal)\n : await execution;\n item.resolve(result);\n } catch (error) {\n item.reject(\n error instanceof Error ? error : new Error(String(error)),\n );\n }\n\n // Remove processed item\n queue.shift();\n }\n } finally {\n // Drop the drained entries from both maps. `mcpAppsRequestQueue` is shared\n // for the page lifetime, so retaining an entry per agent/thread would grow\n // unbounded as threads come and go.\n const queue = this.queues.get(key);\n if (!queue || queue.length === 0) {\n this.queues.delete(key);\n this.processing.delete(key);\n } else {\n this.processing.set(key, false);\n }\n }\n }\n\n /**\n * Resolve once the agent is not running. Subscribes to run-finalized/failed and\n * also polls as a fallback for reconnect scenarios where events do not fire.\n * Rejects after `timeoutMs` so a stuck run cannot block the queue forever.\n */\n private waitForAgentIdle(\n agent: AbstractAgent,\n timeoutMs: number,\n signal?: AbortSignal,\n ): Promise<void> {\n return new Promise((resolve, reject) => {\n if (!agent.isRunning) {\n resolve();\n return;\n }\n if (signal?.aborted) {\n reject(new Error(\"[CopilotKit] MCP app request cancelled on teardown\"));\n return;\n }\n\n let done = false;\n const settle = (fn: () => void) => {\n if (done) return;\n done = true;\n clearTimeout(timer);\n clearInterval(checkInterval);\n sub.unsubscribe();\n signal?.removeEventListener(\"abort\", onAbort);\n fn();\n };\n const onAbort = () =>\n settle(() =>\n reject(\n new Error(\"[CopilotKit] MCP app request cancelled on teardown\"),\n ),\n );\n signal?.addEventListener(\"abort\", onAbort);\n const finish = () => settle(resolve);\n\n const sub = agent.subscribe({\n onRunFinalized: finish,\n onRunFailed: finish,\n });\n\n // Fallback for reconnect scenarios where events don't fire\n const checkInterval = setInterval(() => {\n if (!agent.isRunning) finish();\n }, 500);\n\n const timer = setTimeout(() => {\n settle(() =>\n reject(\n new Error(\n \"[CopilotKit] Timed out waiting for agent to become idle\",\n ),\n ),\n );\n }, timeoutMs);\n });\n }\n}\n\n// Shared per-thread queue instance for all MCP app requests.\nexport const mcpAppsRequestQueue = new MCPAppsRequestQueue();\n\n/** Release only the caller's wait; the underlying run may still be active. */\nfunction waitWithAbort<T>(\n promise: Promise<T>,\n signal: AbortSignal,\n): Promise<T> {\n return new Promise((resolve, reject) => {\n const cancel = () =>\n reject(new Error(\"[CopilotKit] MCP app request cancelled on teardown\"));\n signal.addEventListener(\"abort\", cancel, { once: true });\n promise\n .then(resolve, reject)\n .finally(() => signal.removeEventListener(\"abort\", cancel));\n if (signal.aborted) cancel();\n });\n}\n"],"mappings":";;;;;;;AAQA,MAAa,iCAAiC;;;;;;AAO9C,IAAa,iCAAb,cAAoD,MAAM;CACxD,YACE,AAAS,gBACT,AAAS,iBACT;AACA,QACE,sEAAsE,eAAe,QAAQ,gBAAgB,wBAC9G;EALQ;EACA;AAKT,OAAK,OAAO;;;;AAsDhB,MAAM,4BAAY,IAAI,SAAgC;AACtD,IAAI,eAAe;AACnB,SAAS,OAAO,OAA8B;CAC5C,IAAI,MAAM,UAAU,IAAI,MAAM;AAC9B,KAAI,CAAC,KAAK;AACR,QAAM,SAAS;AACf,YAAU,IAAI,OAAO,IAAI;;AAE3B,QAAO,GAAG,IAAI,IAAI,MAAM,YAAY;;;;;;AAOtC,IAAa,sBAAb,MAAiC;;gCACd,IAAI,KAA0B;oCAC1B,IAAI,KA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E,IAAI,MACF,0DACD,CACF,CACF;MACA,UAAU;IACb;;;AAKN,MAAa,sBAAsB,IAAI,qBAAqB;;AAG5D,SAAS,cACP,SACA,QACY;AACZ,QAAO,IAAI,SAAS,SAAS,WAAW;EACtC,MAAM,eACJ,uBAAO,IAAI,MAAM,qDAAqD,CAAC;AACzE,SAAO,iBAAiB,SAAS,QAAQ,EAAE,MAAM,MAAM,CAAC;AACxD,UACG,KAAK,SAAS,OAAO,CACrB,cAAc,OAAO,oBAAoB,SAAS,OAAO,CAAC;AAC7D,MAAI,OAAO,QAAS,SAAQ;GAC5B"}
|
|
1
|
+
{"version":3,"file":"request-queue.mjs","names":[],"sources":["../src/request-queue.ts"],"sourcesContent":["import type { AbstractAgent, RunAgentResult } from \"@ag-ui/client\";\n\n/**\n * How long a queued request waits for a busy agent before it is rejected.\n * A stuck run would otherwise hold the whole queue (and the widget's loading\n * state) forever. The Vue host enforced this before the shared extraction; it\n * now applies to every frontend.\n */\nexport const MCP_APPS_QUEUE_IDLE_TIMEOUT_MS = 30_000;\n\n/**\n * Raised when queued work is dropped because the agent moved to another thread\n * between enqueue and execution. Distinguishable so callers can answer the\n * requester explicitly instead of leaving it waiting.\n */\nexport class MCPAppsQueueThreadChangedError extends Error {\n constructor(\n readonly originThreadId: string,\n readonly currentThreadId: string,\n ) {\n super(\n `[CopilotKit] MCP app request dropped: the agent moved from thread \"${originThreadId}\" to \"${currentThreadId}\" while it was queued.`,\n );\n this.name = \"MCPAppsQueueThreadChangedError\";\n }\n}\n\n/** Options accepted by {@link MCPAppsRequestQueue.enqueue}. */\nexport interface MCPAppsEnqueueOptions {\n /**\n * Identifies the caller that owns this request, so `cancelOwner` can drop the\n * work of a single widget without touching requests queued by other widgets\n * (the pre-extraction `cancel(threadId)` was too broad: it rejected everything\n * sharing a thread).\n */\n owner?: object;\n /** Override the busy-agent wait timeout. Defaults to 30s. */\n timeoutMs?: number;\n /** Also release an executing request's wait on owner cancellation (does not stop its run). */\n cancelRunningWait?: boolean;\n /**\n * Drop the request instead of running it when the agent has switched threads\n * since it was enqueued.\n *\n * The queue is keyed by agent AND thread, but that only decides which FIFO the\n * work joins: a single shared agent object can have its `threadId` mutated in\n * place while the work waits, so executing later would run a thread-1 request\n * against thread-2 - and stream into it (issue #5819's failure mode, applied\n * to the proxy paths).\n */\n dropAfterThreadSwitch?: boolean;\n}\n\ninterface QueueItem {\n execute: (signal: AbortSignal) => Promise<RunAgentResult>;\n cancelRunningWait?: boolean;\n resolve: (result: RunAgentResult) => void;\n reject: (error: Error) => void;\n owner?: object;\n timeoutMs: number;\n /** Aborted by `cancelOwner`, so an active idle wait stops immediately. */\n controller: AbortController;\n /** Thread the agent was on when this work was enqueued. */\n originThreadId: string;\n dropAfterThreadSwitch?: boolean;\n /**\n * Set once `execute()` has actually been invoked. The run itself can no longer\n * be cancelled (runAgent exposes no abort), but the caller's WAIT still can:\n * with `cancelRunningWait`, `cancelOwner` aborts the signal and settles the\n * requester instead of leaving it pending.\n */\n executing?: boolean;\n /** Set by `cancelOwner` for work that must not run. */\n cancelled?: boolean;\n}\n\n/** Stable per-agent id, so two agents sharing a threadId keep separate queues. */\nconst agentKeys = new WeakMap<AbstractAgent, string>();\nlet nextAgentKey = 0;\nfunction keyFor(agent: AbstractAgent): string {\n let key = agentKeys.get(agent);\n if (!key) {\n key = `agent-${nextAgentKey++}`;\n agentKeys.set(agent, key);\n }\n return `${key}::${agent.threadId || \"default\"}`;\n}\n\n/**\n * Queue for serializing MCP app requests to an agent.\n * Ensures requests wait for the agent to stop running and are processed one at a time.\n */\nexport class MCPAppsRequestQueue {\n private queues = new Map<string, QueueItem[]>();\n private processing = new Map<string, boolean>();\n\n /**\n * Add a request to the queue for a specific agent thread.\n * Returns a promise that resolves when the request completes.\n */\n async enqueue(\n agent: AbstractAgent,\n request: (signal: AbortSignal) => Promise<RunAgentResult>,\n options?: MCPAppsEnqueueOptions,\n ): Promise<RunAgentResult> {\n // Keyed by agent AND thread: a shared thread id must not serialize (or\n // cancel) work belonging to a different agent.\n const key = keyFor(agent);\n\n return new Promise((resolve, reject) => {\n let queue = this.queues.get(key);\n if (!queue) {\n queue = [];\n this.queues.set(key, queue);\n }\n\n queue.push({\n execute: request,\n cancelRunningWait: options?.cancelRunningWait,\n resolve,\n reject,\n owner: options?.owner,\n timeoutMs: options?.timeoutMs ?? MCP_APPS_QUEUE_IDLE_TIMEOUT_MS,\n controller: new AbortController(),\n originThreadId: agent.threadId || \"default\",\n dropAfterThreadSwitch: options?.dropAfterThreadSwitch,\n });\n\n // Start processing if not already running\n void this.processQueue(key, agent);\n });\n }\n\n /**\n * Drop every request queued by `owner` that has not started executing yet,\n * rejecting its promise. Used by a widget teardown so work that only exists to\n * feed a now-unmounted iframe does not run against the agent later.\n *\n * By default this cancels waiting work only. `cancelRunningWait` also\n * releases an executing caller's wait and signals its callback; it does not\n * itself stop a runAgent call. The next item still waits for agent idle.\n */\n cancelOwner(owner: object): void {\n for (const queue of this.queues.values()) {\n for (const item of queue) {\n if (\n item.owner !== owner ||\n (item.executing && !item.cancelRunningWait) ||\n item.cancelled\n )\n continue;\n item.cancelled = true;\n // Abort first: an item already waiting on a busy agent must release its\n // timer and agent subscription now, not when the agent finally frees up.\n item.controller.abort();\n item.reject(\n new Error(\"[CopilotKit] MCP app request cancelled on teardown\"),\n );\n }\n }\n }\n\n /**\n * Drain a queue one request at a time, waiting for the agent to go idle before\n * each. Re-entrant-safe (a single processor per key) and drops the entries once\n * fully drained to keep the shared queue bounded.\n */\n private async processQueue(key: string, agent: AbstractAgent): Promise<void> {\n // If already processing this queue, return\n if (this.processing.get(key)) {\n return;\n }\n\n this.processing.set(key, true);\n\n try {\n const queue = this.queues.get(key);\n if (!queue) return;\n\n while (queue.length > 0) {\n const item = queue[0]!;\n\n // Cancelled before it got its turn: its promise is already rejected.\n if (item.cancelled) {\n queue.shift();\n continue;\n }\n\n try {\n // Wait for any active run to complete before processing\n await this.waitForAgentIdle(\n agent,\n item.timeoutMs,\n item.controller.signal,\n );\n\n // The owner may have torn down while we waited for the agent.\n if (item.cancelled) {\n queue.shift();\n continue;\n }\n\n // Thread guard: the agent object is shared and its `threadId` can be\n // mutated in place while work waits, so re-check right before running.\n // The queue key only decided which FIFO this joined, it does not pin\n // the agent's current thread.\n const currentThreadId = agent.threadId || \"default\";\n if (\n item.dropAfterThreadSwitch &&\n currentThreadId !== item.originThreadId\n ) {\n item.reject(\n new MCPAppsQueueThreadChangedError(\n item.originThreadId,\n currentThreadId,\n ),\n );\n queue.shift();\n continue;\n }\n\n // Execution itself is not aborted; callers may opt into releasing\n // their wait on teardown (the legacy Angular contract).\n item.executing = true;\n const execution = item.execute(item.controller.signal);\n const result = item.cancelRunningWait\n ? await waitWithAbort(execution, item.controller.signal)\n : await execution;\n item.resolve(result);\n } catch (error) {\n item.reject(\n error instanceof Error ? error : new Error(String(error)),\n );\n }\n\n // Remove processed item\n queue.shift();\n }\n } finally {\n // Drop the drained entries from both maps. `mcpAppsRequestQueue` is shared\n // for the page lifetime, so retaining an entry per agent/thread would grow\n // unbounded as threads come and go.\n const queue = this.queues.get(key);\n if (!queue || queue.length === 0) {\n this.queues.delete(key);\n this.processing.delete(key);\n } else {\n this.processing.set(key, false);\n }\n }\n }\n\n /**\n * Resolve once the agent is not running. Subscribes to run-finalized/failed and\n * also polls as a fallback for reconnect scenarios where events do not fire.\n * Rejects after `timeoutMs` so a stuck run cannot block the queue forever.\n */\n private waitForAgentIdle(\n agent: AbstractAgent,\n timeoutMs: number,\n signal?: AbortSignal,\n ): Promise<void> {\n return new Promise((resolve, reject) => {\n if (!agent.isRunning) {\n resolve();\n return;\n }\n if (signal?.aborted) {\n reject(new Error(\"[CopilotKit] MCP app request cancelled on teardown\"));\n return;\n }\n\n let done = false;\n const settle = (fn: () => void) => {\n if (done) return;\n done = true;\n clearTimeout(timer);\n clearInterval(checkInterval);\n sub.unsubscribe();\n signal?.removeEventListener(\"abort\", onAbort);\n fn();\n };\n const onAbort = () =>\n settle(() =>\n reject(\n new Error(\"[CopilotKit] MCP app request cancelled on teardown\"),\n ),\n );\n signal?.addEventListener(\"abort\", onAbort);\n const finish = () => settle(resolve);\n\n const sub = agent.subscribe({\n onRunFinalized: finish,\n onRunFailed: finish,\n });\n\n // Fallback for reconnect scenarios where events don't fire\n const checkInterval = setInterval(() => {\n if (!agent.isRunning) finish();\n }, 500);\n\n const timer = setTimeout(() => {\n settle(() =>\n reject(\n new Error(\n \"[CopilotKit] Timed out waiting for agent to become idle\",\n ),\n ),\n );\n }, timeoutMs);\n });\n }\n}\n\n// Shared per-thread queue instance for all MCP app requests.\nexport const mcpAppsRequestQueue = new MCPAppsRequestQueue();\n\n/** Release only the caller's wait; the underlying run may still be active. */\nfunction waitWithAbort<T>(\n promise: Promise<T>,\n signal: AbortSignal,\n): Promise<T> {\n return new Promise((resolve, reject) => {\n const cancel = () =>\n reject(new Error(\"[CopilotKit] MCP app request cancelled on teardown\"));\n signal.addEventListener(\"abort\", cancel, { once: true });\n promise\n .then(resolve, reject)\n .finally(() => signal.removeEventListener(\"abort\", cancel));\n if (signal.aborted) cancel();\n });\n}\n"],"mappings":";;;;;;;AAQA,MAAa,iCAAiC;;;;;;AAO9C,IAAa,iCAAb,cAAoD,MAAM;CACxD,YACE,AAAS,gBACT,AAAS,iBACT;AACA,QACE,sEAAsE,eAAe,QAAQ,gBAAgB,wBAC9G;EALQ;EACA;AAKT,OAAK,OAAO;;;;AAsDhB,MAAM,4BAAY,IAAI,SAAgC;AACtD,IAAI,eAAe;AACnB,SAAS,OAAO,OAA8B;CAC5C,IAAI,MAAM,UAAU,IAAI,MAAM;AAC9B,KAAI,CAAC,KAAK;AACR,QAAM,SAAS;AACf,YAAU,IAAI,OAAO,IAAI;;AAE3B,QAAO,GAAG,IAAI,IAAI,MAAM,YAAY;;;;;;AAOtC,IAAa,sBAAb,MAAiC;;gCACd,IAAI,KAA0B;oCAC1B,IAAI,KAAsB;;;;;;CAM/C,MAAM,QACJ,OACA,SACA,SACyB;EAGzB,M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KN,MAAa,sBAAsB,IAAI,qBAAqB;;AAG5D,SAAS,cACP,SACA,QACY;AACZ,QAAO,IAAI,SAAS,SAAS,WAAW;EACtC,MAAM,eACJ,uBAAO,IAAI,MAAM,qDAAqD,CAAC;AACzE,SAAO,iBAAiB,SAAS,QAAQ,EAAE,MAAM,MAAM,CAAC;AACxD,UACG,KAAK,SAAS,OAAO,CACrB,cAAc,OAAO,oBAAoB,SAAS,OAAO,CAAC;AAC7D,MAAI,OAAO,QAAS,SAAQ;GAC5B"}
|
package/dist/session.mjs
CHANGED
|
@@ -3,7 +3,7 @@ import { MCPAppsActivityContentSchema } from "./content-schema.mjs";
|
|
|
3
3
|
import { buildSandboxHTML, ɵmcpAppSandboxFlags } from "./sandbox.mjs";
|
|
4
4
|
import { MCPAppsQueueThreadChangedError, MCP_APPS_QUEUE_IDLE_TIMEOUT_MS, mcpAppsRequestQueue } from "./request-queue.mjs";
|
|
5
5
|
import { ɵrunMcpFollowUp } from "./follow-up.mjs";
|
|
6
|
-
import
|
|
6
|
+
import * as z from "zod";
|
|
7
7
|
import { AppBridge, LATEST_PROTOCOL_VERSION, PostMessageTransport } from "@modelcontextprotocol/ext-apps/app-bridge";
|
|
8
8
|
import { randomUUID } from "@copilotkit/shared";
|
|
9
9
|
|
|
@@ -88,7 +88,7 @@ const CopilotKitUiMessageSchema = z.object({
|
|
|
88
88
|
content: z.array(z.any()).optional(),
|
|
89
89
|
followUp: z.boolean().optional(),
|
|
90
90
|
_meta: z.record(z.string(), z.any()).optional()
|
|
91
|
-
}).
|
|
91
|
+
}).loose()
|
|
92
92
|
});
|
|
93
93
|
/** Defaults every frontend inherits unless it overrides them. */
|
|
94
94
|
const MCP_APPS_SESSION_DEFAULTS = {
|
package/dist/session.mjs.map
CHANGED
|
@@ -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,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,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,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,eAAe;EACvB,QAAQ,cAAc;EACtB,QAAQ,YAAY;EACrB,CAAC;;;;;;;;;;AAWJ,MAAa,4BAA4B;;;;;;;;;;;;AAazC,MAAM,4BAA4B,EAAE,OAAO;CACzC,QAAQ,EAAE,QAAQ,aAAa;CAC/B,QAAQ,EACL,OAAO;EACN,MAAM,EAAE,QAAQ,CAAC,UAAU;EAC3B,SAAS,EAAE,M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AClB,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.
|
|
3
|
+
"version": "2.0.0-rc.20",
|
|
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",
|
|
@@ -48,13 +51,13 @@
|
|
|
48
51
|
"access": "public"
|
|
49
52
|
},
|
|
50
53
|
"dependencies": {
|
|
51
|
-
"@copilotkit/shared": "2.0.0-rc.
|
|
54
|
+
"@copilotkit/shared": "2.0.0-rc.20",
|
|
52
55
|
"@modelcontextprotocol/ext-apps": "^1.7.5",
|
|
53
|
-
"@modelcontextprotocol/sdk": "^1.29.0"
|
|
56
|
+
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
57
|
+
"zod": "^4.2.0"
|
|
54
58
|
},
|
|
55
59
|
"peerDependencies": {
|
|
56
|
-
"@ag-ui/client": "
|
|
57
|
-
"zod": ">=3.25"
|
|
60
|
+
"@ag-ui/client": "^1.0.2"
|
|
58
61
|
},
|
|
59
62
|
"devDependencies": {
|
|
60
63
|
"@ag-ui/client": "1.0.2",
|
|
@@ -62,8 +65,7 @@
|
|
|
62
65
|
"jsdom": "^26.1.0",
|
|
63
66
|
"tsdown": "^0.20.3",
|
|
64
67
|
"typescript": "5.9.2",
|
|
65
|
-
"vitest": "^3.2.4"
|
|
66
|
-
"zod": "^3.25.76"
|
|
68
|
+
"vitest": "^3.2.4"
|
|
67
69
|
},
|
|
68
70
|
"scripts": {
|
|
69
71
|
"build": "tsdown",
|