@copilotkit/mcp-apps-renderer 1.76.0 → 1.77.0

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.
@@ -4,6 +4,16 @@ import { AbstractAgent } from "@ag-ui/client";
4
4
  import { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
5
5
 
6
6
  //#region src/session.d.ts
7
+ /**
8
+ * Decode a base64 resource body as UTF-8.
9
+ *
10
+ * @internal exported for testing.
11
+ *
12
+ * `atob` alone yields a latin1 string, which mangles non-ASCII widget HTML
13
+ * (`<p>Été ☀️</p>` decoded to `<p>Été ☀ï¸</p>`). Decode to bytes first, then
14
+ * run them through a UTF-8 TextDecoder.
15
+ */
16
+ declare function ɵdecodeBase64(value: string): string;
7
17
  /**
8
18
  * The MCP Apps protocol version this host negotiates. Sourced directly from the
9
19
  * ext-apps bridge (single source of truth, no hand-maintained literal). It lives
@@ -38,10 +48,28 @@ interface McpAppSessionHooks {
38
48
  }): void;
39
49
  /** The widget finished initializing (safe to push tool input/result). */
40
50
  onInitialized?(): void;
51
+ /** The sandbox proxy is ready and its resource has been sent. */
52
+ onSandboxReady?(): void;
41
53
  /** The fetched resource metadata (e.g. prefersBorder) is available. */
42
54
  onResource?(resource: FetchedResource): void;
43
- /** Setup failed (resource fetch, connect, ...). */
55
+ /**
56
+ * FATAL setup failure (resource fetch, bridge connect, sandbox timeout).
57
+ * The session cannot serve this widget; the host keeps showing the error
58
+ * until it re-binds.
59
+ */
44
60
  onError?(err: Error): void;
61
+ /** A queued ui/message follow-up failed. */
62
+ onFollowUpError?(err: Error): void;
63
+ /**
64
+ * RECOVERABLE content problem: an activity update was rejected by the content
65
+ * schema and therefore not forwarded to the widget. Reported the same way
66
+ * whether the content came from the agent's store or from an adapter prop.
67
+ *
68
+ * Called with the `Error` when content is rejected, and with `null` as soon as
69
+ * valid content arrives again - the widget resumes, so the host must clear the
70
+ * message rather than leave a stale error on screen.
71
+ */
72
+ onContentError?(err: Error | null): void;
45
73
  }
46
74
  interface BindMcpAppOptions {
47
75
  /**
@@ -57,13 +85,123 @@ interface BindMcpAppOptions {
57
85
  getAgent: () => AbstractAgent | undefined;
58
86
  /** CopilotKit host, for ui/message follow-up runs (issue #5819). */
59
87
  host: ɵMcpFollowUpHost;
88
+ /**
89
+ * The id of the activity message this session renders. When provided, the
90
+ * session subscribes to the agent's message store, finds this activity, and
91
+ * pushes its tool input/result to the widget itself (self-driving), so the
92
+ * adapter does not re-implement the agent-driven forwarding loop.
93
+ *
94
+ * The store is authoritative only for activities that live in it. When a host
95
+ * renders an activity from an EXTERNAL message list (e.g. CopilotChatView's
96
+ * `messages` prop), that activity is not in `agent.messages`; the adapter must
97
+ * then call `syncContent` on content change so the widget still receives its
98
+ * tool input/result. Both paths share one dedup, so they never double-send.
99
+ */
100
+ messageId?: string;
60
101
  hooks?: McpAppSessionHooks;
102
+ /**
103
+ * Host identity, capabilities and UI context announced during the MCP Apps
104
+ * initialization handshake, plus the two timeouts. Every field is optional and
105
+ * merged over {@link MCP_APPS_SESSION_DEFAULTS}, so a frontend only overrides
106
+ * what it exposes to its users.
107
+ */
108
+ options?: McpAppSessionOptions;
109
+ /**
110
+ * Decides whether `ui/open-link` may open a URL, and with what final value.
111
+ *
112
+ * Defaults to {@link denyDangerousSchemes}, the single policy every CopilotKit
113
+ * frontend uses - no adapter overrides it, so a widget behaves the same in
114
+ * React, Vue and Angular. This hook exists for a host with a genuinely
115
+ * different security contract; prefer changing the shared policy over setting
116
+ * it, otherwise widget behaviour becomes framework-dependent again.
117
+ */
118
+ openLinkPolicy?: McpAppOpenLinkPolicy;
119
+ /**
120
+ * Whether `teardown` also cancels a queued `ui/message` follow-up run.
121
+ *
122
+ * Defaults to `false`: the follow-up carries the user's message onwards, so it
123
+ * outlives the widget that sent it. Hosts that scope follow-ups to the widget
124
+ * (the Angular contract) can opt in.
125
+ */
126
+ cancelFollowUpsOnTeardown?: boolean;
127
+ /** Require the fetched resource URI to match exactly (Angular compatibility). */
128
+ requireExactResourceUri?: boolean;
129
+ /** Release already-started proxy/follow-up waits on teardown, without aborting the underlying run. */
130
+ cancelRunningWaitOnTeardown?: boolean;
131
+ }
132
+ /** Host identity announced during the initialization handshake. */
133
+ interface McpAppHostInfo {
134
+ name: string;
135
+ version: string;
136
+ }
137
+ interface McpAppSessionOptions {
138
+ /** Maximum time a queued request waits for a busy agent. Default 30s. */
139
+ idleTimeoutMs?: number;
140
+ /**
141
+ * Maximum time to wait for the sandbox proxy handshake
142
+ * (`ui/notifications/sandbox-proxy-ready`). Default 30s.
143
+ *
144
+ * This measures the SANDBOX step, not `ui/notifications/initialized`: a widget
145
+ * that loads its proxy but never reports initialized is a different failure.
146
+ */
147
+ initializationTimeoutMs?: number;
148
+ /** Host identity announced during the initialization handshake. */
149
+ hostInfo?: McpAppHostInfo;
150
+ /** Protocol capabilities announced to embedded MCP Apps. */
151
+ hostCapabilities?: Record<string, unknown>;
152
+ /** Non-secret UI context announced to embedded MCP Apps. */
153
+ hostContext?: Record<string, unknown>;
61
154
  }
155
+ /** Defaults every frontend inherits unless it overrides them. */
156
+ declare const MCP_APPS_SESSION_DEFAULTS: Readonly<Required<McpAppSessionOptions>>;
157
+ /**
158
+ * Returns the URL to open, or `undefined` to refuse. Receiving the raw string
159
+ * (not a parsed URL) lets a policy resolve relative links itself.
160
+ */
161
+ type McpAppOpenLinkPolicy = (url: string) => string | undefined;
162
+ /**
163
+ * The MCP Apps link policy, shared by every frontend.
164
+ *
165
+ * Three independent rules, deliberately kept as ONE policy so a widget behaves
166
+ * the same whichever framework hosts it:
167
+ *
168
+ * 1. **Scheme denylist**, not an allowlist. Only the schemes that execute script
169
+ * or render attacker-controlled HTML are refused (`javascript:`, `data:`,
170
+ * `vbscript:`, `blob:`, `file:`). Everything else is allowed, including
171
+ * app-defined deep links (`myapp:`, `whatsapp:`), which hand off to an OS
172
+ * handler rather than executing in the page. An allowlist could never
173
+ * enumerate those, and restricting to http/https would break them.
174
+ * 2. **Embedded credentials refused** (`https://user:pw@host`): a widget must not
175
+ * hand the browser a URL carrying someone's credentials.
176
+ * 3. **Path-relative links resolved** against the host document, so `/docs`,
177
+ * `./x` and `../x` open instead of failing URL parsing. Only those three
178
+ * forms: every string is technically a valid relative reference, so anything
179
+ * else stays refused rather than becoming a navigation on the host origin.
180
+ * This does mean a widget can reach a path of the HOST application - the same
181
+ * reach a normal anchor in the page would have.
182
+ *
183
+ * Rules 2 and 3 come from the Angular host, which enforced them before it moved
184
+ * onto this session; rule 1 is the CopilotKit product decision (it matches the
185
+ * Anthropic Software Directory policy: https origins plus owned custom URI
186
+ * schemes). Merging them means no frontend overrides anything.
187
+ */
188
+ declare const denyDangerousSchemes: McpAppOpenLinkPolicy;
62
189
  interface McpAppSession {
63
190
  /** Forward the tool call input to the widget (host -> app). Buffered until ready. */
64
191
  sendToolInput(args: Record<string, unknown>): void;
65
192
  /** Forward the tool result to the widget (host -> app). Buffered until ready. */
66
193
  sendToolResult(result: CallToolResult): void;
194
+ /**
195
+ * Forward the tool input/result carried by `content` to the widget, deduped so
196
+ * an unchanged value is not re-sent. The prop-driven counterpart to the agent
197
+ * subscription: the adapter calls this on content change so activities rendered
198
+ * from an external message list (absent from `agent.messages`) still reach the
199
+ * widget. No-op for values already sent (shared dedup with the subscription).
200
+ *
201
+ * Content is validated here exactly as it is on the store path: a rejected
202
+ * value is not forwarded and surfaces through `onContentError`.
203
+ */
204
+ syncContent(content: MCPAppsActivityContent): void;
67
205
  /** Disconnect the bridge and release listeners. Does NOT remove the iframe. */
68
206
  teardown(): void;
69
207
  }
@@ -77,5 +215,5 @@ interface McpAppSession {
77
215
  */
78
216
  declare function bindMcpApp(opts: BindMcpAppOptions): McpAppSession;
79
217
  //#endregion
80
- export { BindMcpAppOptions, FetchedResource, MCP_APPS_PROTOCOL_VERSION, McpAppSession, McpAppSessionHooks, bindMcpApp };
218
+ export { BindMcpAppOptions, FetchedResource, MCP_APPS_PROTOCOL_VERSION, MCP_APPS_SESSION_DEFAULTS, McpAppHostInfo, McpAppOpenLinkPolicy, McpAppSession, McpAppSessionHooks, McpAppSessionOptions, bindMcpApp, denyDangerousSchemes, ɵdecodeBase64 };
81
219
  //# sourceMappingURL=session.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"session.d.mts","names":[],"sources":["../src/session.ts"],"mappings":";;;;;;;;AAwBA;;;;;AA0BA;cA1Ba,yBAAA;;UA0BI,eAAA;EACf,GAAA;EACA,QAAA;EACA,IAAA;EACA,IAAA;EACA,KAAA;IACE,EAAA;MACE,aAAA;MACA,GAAA;QACE,cAAA;QACA,eAAA;MAAA;IAAA;EAAA;AAAA;;UAOS,kBAAA;EAEf;EAAA,aAAA,EAAe,IAAA;IAAQ,KAAA;IAAgB,MAAA;EAAA;EAIvC;EAFA,aAAA;EAEY;EAAZ,UAAA,EAAY,QAAA,EAAU,eAAA;EAER;EAAd,OAAA,EAAS,GAAA,EAAK,KAAA;AAAA;AAAA,UAGC,iBAAA;EAAA;;;;;;EAOf,MAAA,EAAQ,iBAAA;EAOA;EALR,UAAA,QAAkB,sBAAA;EAKQ;EAH1B,QAAA,QAAgB,aAAA;EAJR;EAMR,IAAA,EAAM,gBAAA;EACN,KAAA,GAAQ,kBAAA;AAAA;AAAA,UAGO,aAAA;EAJf;EAMA,aAAA,CAAc,IAAA,EAAM,MAAA;EALpB;EAOA,cAAA,CAAe,MAAA,EAAQ,cAAA;EAPG;EAS1B,QAAA;AAAA;;;;;;;;;iBAWc,UAAA,CAAW,IAAA,EAAM,iBAAA,GAAoB,aAAA"}
1
+ {"version":3,"file":"session.d.mts","names":[],"sources":["../src/session.ts"],"mappings":";;;;;;;;AAiDA;;;;;AA6DA;;iBA7DgB,aAAA,CAAc,KAAA;;;AAuF9B;;;;;;cA1Ba,yBAAA;;UA0BI,eAAA;EACf,GAAA;EACA,QAAA;EACA,IAAA;EACA,IAAA;EACA,KAAA;IACE,EAAA;MACE,aAAA;MACA,GAAA;QACE,cAAA;QACA,eAAA;MAAA;IAAA;EAAA;AAAA;;UAOS,kBAAA;EAEf;EAAA,aAAA,EAAe,IAAA;IAAQ,KAAA;IAAgB,MAAA;EAAA;EAIvC;EAFA,aAAA;EAIsB;EAFtB,cAAA;EAQA;EANA,UAAA,EAAY,QAAA,EAAU,eAAA;EAMb;;;;;EAAT,OAAA,EAAS,GAAA,EAAK,KAAA;EAYE;EAVhB,eAAA,EAAiB,GAAA,EAAK,KAAA;EAUW;AAGnC;;;;;;;;EAHE,cAAA,EAAgB,GAAA,EAAK,KAAA;AAAA;AAAA,UAGN,iBAAA;EA4CsB;;;;;;EArCrC,MAAA,EAAQ,iBAAA;EAMR;EAJA,UAAA,QAAkB,sBAAA;EAiBlB;EAfA,QAAA,QAAgB,aAAA;EAgBR;EAdR,IAAA,EAAM,gBAAA;EAqBI;;;;;;;;AA0BZ;;;;EAlCE,SAAA;EACA,KAAA,GAAQ,kBAAA;EAsC2B;;;;;;EA/BnC,OAAA,GAAU,oBAAA;EAiCV;;;;;;;;;EAvBA,cAAA,GAAiB,oBAAA;EAyCN;;;;;;;EAjCX,yBAAA;EAiCsC;EA/BtC,uBAAA;EAgCS;EA9BT,2BAAA;AAAA;AA2CF;AAAA,UAvCiB,cAAA;EACf,IAAA;EACA,OAAA;AAAA;AAAA,UAGe,oBAAA;EAsFhB;EApFC,aAAA;EA4DiC;;AA0BnC;;;;;EA9EE,uBAAA;EA6F2C;EA3F3C,QAAA,GAAW,cAAA;EA8EX;EA5EA,gBAAA,GAAmB,MAAA;EA4EL;EA1Ed,WAAA,GAAc,MAAA;AAAA;;cAIH,yBAAA,EAA2B,QAAA,CACtC,QAAA,CAAS,oBAAA;;;;;KAaC,oBAAA,IAAwB,GAAA;AAkFpC;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,cAtDa,oBAAA,EAAsB,oBAAA;AAAA,UA0BlB,aAAA;;EAEf,aAAA,CAAc,IAAA,EAAM,MAAA;;EAEpB,cAAA,CAAe,MAAA,EAAQ,cAAA;;;;;;;;;;;EAWvB,WAAA,CAAY,OAAA,EAAS,sBAAA;;EAErB,QAAA;AAAA;;;;;;;;;iBAWc,UAAA,CAAW,IAAA,EAAM,iBAAA,GAAoB,aAAA"}
package/dist/session.mjs CHANGED
@@ -1,12 +1,66 @@
1
- import { MCP_OPEN_LINK_BLOCKED_SCHEMES } from "./constants.mjs";
1
+ import { MCPAppsActivityType, MCP_OPEN_LINK_BLOCKED_SCHEMES } from "./constants.mjs";
2
+ import { MCPAppsActivityContentSchema } from "./content-schema.mjs";
2
3
  import { buildSandboxHTML } from "./sandbox.mjs";
3
- import { mcpAppsRequestQueue } from "./request-queue.mjs";
4
+ import { MCPAppsQueueThreadChangedError, MCP_APPS_QUEUE_IDLE_TIMEOUT_MS, mcpAppsRequestQueue } from "./request-queue.mjs";
4
5
  import { ɵrunMcpFollowUp } from "./follow-up.mjs";
5
6
  import { z } from "zod";
6
7
  import { AppBridge, LATEST_PROTOCOL_VERSION, PostMessageTransport } from "@modelcontextprotocol/ext-apps/app-bridge";
7
8
  import { randomUUID } from "@copilotkit/shared";
8
9
 
9
10
  //#region src/session.ts
11
+ /** JSON key for dedup; falls back to empty string on a cyclic/unserializable value. */
12
+ function keyOf(value) {
13
+ try {
14
+ return JSON.stringify(value) ?? "";
15
+ } catch {
16
+ return "";
17
+ }
18
+ }
19
+ /**
20
+ * Decode a base64 resource body as UTF-8.
21
+ *
22
+ * @internal exported for testing.
23
+ *
24
+ * `atob` alone yields a latin1 string, which mangles non-ASCII widget HTML
25
+ * (`<p>Été ☀️</p>` decoded to `<p>Été ☀ï¸</p>`). Decode to bytes first, then
26
+ * run them through a UTF-8 TextDecoder.
27
+ */
28
+ function ɵdecodeBase64(value) {
29
+ try {
30
+ const binary = atob(value);
31
+ const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
32
+ return new TextDecoder().decode(bytes);
33
+ } catch {
34
+ throw new Error("The MCP App resource contains invalid base64 content.");
35
+ }
36
+ }
37
+ /**
38
+ * Pick the resource this session asked for.
39
+ *
40
+ * A `resources/read` response may carry several contents; taking the first one
41
+ * can hand the widget a different resource than the one it is bound to. Match on
42
+ * the requested URI, and fall back to a lone content only when the server
43
+ * returned exactly one (some servers normalize the URI they echo back).
44
+ */
45
+ function selectResource(contents, resourceUri, requireExact = false) {
46
+ const match = contents?.find((candidate) => candidate.uri === resourceUri);
47
+ if (match) return match;
48
+ return !requireExact && contents?.length === 1 ? contents[0] : void 0;
49
+ }
50
+ /**
51
+ * Stable key for the widget resource a session is bound to. A session fetches
52
+ * and renders exactly ONE resource. If the store activity for this messageId is
53
+ * later replaced by a different resource (resourceUri/serverHash/serverId), the
54
+ * store subscription must NOT push the new widget's tool input/result into this
55
+ * (old) iframe - the adapter re-binds a fresh session for the new identity.
56
+ */
57
+ function identityKeyOf(content) {
58
+ return JSON.stringify([
59
+ content.resourceUri ?? null,
60
+ content.serverHash ?? null,
61
+ content.serverId ?? null
62
+ ]);
63
+ }
10
64
  /**
11
65
  * The MCP Apps protocol version this host negotiates. Sourced directly from the
12
66
  * ext-apps bridge (single source of truth, no hand-maintained literal). It lives
@@ -36,6 +90,65 @@ const CopilotKitUiMessageSchema = z.object({
36
90
  _meta: z.record(z.string(), z.any()).optional()
37
91
  }).passthrough()
38
92
  });
93
+ /** Defaults every frontend inherits unless it overrides them. */
94
+ const MCP_APPS_SESSION_DEFAULTS = {
95
+ idleTimeoutMs: MCP_APPS_QUEUE_IDLE_TIMEOUT_MS,
96
+ initializationTimeoutMs: 3e4,
97
+ hostInfo: {
98
+ name: "CopilotKit MCP Apps Host",
99
+ version: "1.0.0"
100
+ },
101
+ hostCapabilities: {
102
+ openLinks: {},
103
+ logging: {},
104
+ message: { text: {} }
105
+ },
106
+ hostContext: { platform: "web" }
107
+ };
108
+ /**
109
+ * The MCP Apps link policy, shared by every frontend.
110
+ *
111
+ * Three independent rules, deliberately kept as ONE policy so a widget behaves
112
+ * the same whichever framework hosts it:
113
+ *
114
+ * 1. **Scheme denylist**, not an allowlist. Only the schemes that execute script
115
+ * or render attacker-controlled HTML are refused (`javascript:`, `data:`,
116
+ * `vbscript:`, `blob:`, `file:`). Everything else is allowed, including
117
+ * app-defined deep links (`myapp:`, `whatsapp:`), which hand off to an OS
118
+ * handler rather than executing in the page. An allowlist could never
119
+ * enumerate those, and restricting to http/https would break them.
120
+ * 2. **Embedded credentials refused** (`https://user:pw@host`): a widget must not
121
+ * hand the browser a URL carrying someone's credentials.
122
+ * 3. **Path-relative links resolved** against the host document, so `/docs`,
123
+ * `./x` and `../x` open instead of failing URL parsing. Only those three
124
+ * forms: every string is technically a valid relative reference, so anything
125
+ * else stays refused rather than becoming a navigation on the host origin.
126
+ * This does mean a widget can reach a path of the HOST application - the same
127
+ * reach a normal anchor in the page would have.
128
+ *
129
+ * Rules 2 and 3 come from the Angular host, which enforced them before it moved
130
+ * onto this session; rule 1 is the CopilotKit product decision (it matches the
131
+ * Anthropic Software Directory policy: https origins plus owned custom URI
132
+ * schemes). Merging them means no frontend overrides anything.
133
+ */
134
+ const denyDangerousSchemes = (url) => {
135
+ let parsed;
136
+ let absolute = true;
137
+ try {
138
+ parsed = new URL(url);
139
+ } catch {
140
+ if (!/^(\/|\.\/|\.\.\/)/.test(url)) return void 0;
141
+ absolute = false;
142
+ try {
143
+ parsed = new URL(url, window.location.href);
144
+ } catch {
145
+ return;
146
+ }
147
+ }
148
+ if (MCP_OPEN_LINK_BLOCKED_SCHEMES.has(parsed.protocol)) return void 0;
149
+ if (parsed.username || parsed.password) return void 0;
150
+ return absolute ? url : parsed.href;
151
+ };
39
152
  /**
40
153
  * Bind an MCP App to a host-provided sandbox iframe: fetch the widget resource
41
154
  * through the agent, connect the ext-apps `AppBridge` over a PostMessage
@@ -45,12 +158,25 @@ const CopilotKitUiMessageSchema = z.object({
45
158
  * `hooks`, but all protocol logic lives here.
46
159
  */
47
160
  function bindMcpApp(opts) {
48
- const { iframe, getContent, getAgent, host, hooks } = opts;
161
+ const { iframe, getContent, getAgent, host, messageId, hooks, options, openLinkPolicy = denyDangerousSchemes, cancelFollowUpsOnTeardown = false } = opts;
162
+ const settings = {
163
+ ...MCP_APPS_SESSION_DEFAULTS,
164
+ ...options
165
+ };
166
+ const boundIdentity = identityKeyOf(getContent());
167
+ const queueOwner = {};
49
168
  let disposed = false;
50
169
  let ready = false;
51
170
  let bridge = null;
52
171
  let pendingToolInput;
53
172
  let pendingToolResult;
173
+ let lastToolInputKey;
174
+ let lastToolResultKey;
175
+ let lastInvalidContentKey;
176
+ let activitySub = null;
177
+ let sandboxTimer;
178
+ let sandboxReady = false;
179
+ let sandboxTimedOut = false;
54
180
  /** Flush any buffered tool input/result to the widget once it is initialized. */
55
181
  const flushPending = () => {
56
182
  if (!ready || !bridge) return;
@@ -63,21 +189,128 @@ function bindMcpApp(opts) {
63
189
  pendingToolResult = void 0;
64
190
  }
65
191
  };
192
+ /**
193
+ * Report content the schema rejected. RECOVERABLE: the session keeps running
194
+ * and resumes as soon as valid content arrives, so this never goes through the
195
+ * fatal `onError` channel. Deduped on the offending value, since store updates
196
+ * fire for every message change, not just this activity's.
197
+ */
198
+ const reportContentRejected = (value, error) => {
199
+ const key = keyOf(value);
200
+ if (key === lastInvalidContentKey) return;
201
+ lastInvalidContentKey = key;
202
+ hooks?.onContentError?.(/* @__PURE__ */ new Error(`[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}`));
203
+ };
204
+ /** Valid content resumed: clear the message the host shows for a rejection. */
205
+ const clearContentRejection = () => {
206
+ if (lastInvalidContentKey === void 0) return;
207
+ lastInvalidContentKey = void 0;
208
+ hooks?.onContentError?.(null);
209
+ };
210
+ /**
211
+ * Push tool input/result from an activity content to the widget, deduped so an
212
+ * unchanged value (e.g. a re-emitted snapshot) is not re-sent. Buffered by the
213
+ * imperative sender until the widget is initialized.
214
+ *
215
+ * The single forwarding path for BOTH sources - the store subscription
216
+ * (`pushFromMessages`) and the adapter props (`syncContent`) - so validation,
217
+ * the identity guard and recoverable-error reporting behave identically
218
+ * whichever one produced the content.
219
+ */
220
+ const pushFromContent = (content) => {
221
+ const parsedContent = MCPAppsActivityContentSchema.safeParse(content);
222
+ if (!parsedContent.success) {
223
+ reportContentRejected(content, parsedContent.error);
224
+ return;
225
+ }
226
+ const validated = parsedContent.data;
227
+ if (identityKeyOf(validated) !== boundIdentity) return;
228
+ const { toolInput } = validated;
229
+ const validResult = validated.result;
230
+ clearContentRejection();
231
+ if (toolInput !== void 0) {
232
+ const key = keyOf(toolInput);
233
+ if (key !== lastToolInputKey) {
234
+ lastToolInputKey = key;
235
+ pendingToolInput = toolInput;
236
+ flushPending();
237
+ }
238
+ }
239
+ if (validResult !== void 0) {
240
+ const key = keyOf(validResult);
241
+ if (key !== lastToolResultKey) {
242
+ lastToolResultKey = key;
243
+ pendingToolResult = validResult;
244
+ flushPending();
245
+ }
246
+ }
247
+ };
248
+ /**
249
+ * Push the CURRENT content of this activity (read from the agent's message
250
+ * store, the authoritative post-apply source) to the widget. Used both at
251
+ * initialize and on every `onMessagesChanged`, so the widget always reflects
252
+ * the applied state - never a stale React prop or a pre-apply activity message.
253
+ * Store path only (requires `messageId`); the props path goes through
254
+ * `syncContent`. `messages` overrides the store lookup when provided.
255
+ */
256
+ const pushFromMessages = (messages) => {
257
+ if (disposed || !messageId) return;
258
+ const msg = (messages ?? getAgent()?.messages)?.find((m) => m?.id === messageId);
259
+ if (!msg || msg.activityType !== MCPAppsActivityType) return;
260
+ const parsed = MCPAppsActivityContentSchema.safeParse(msg.content);
261
+ if (!parsed.success) {
262
+ reportContentRejected(msg.content, parsed.error);
263
+ return;
264
+ }
265
+ pushFromContent(parsed.data);
266
+ };
267
+ /** True when this activity currently lives in the agent's message store. */
268
+ const activityInStore = () => !!(getAgent()?.messages)?.some((m) => m?.id === messageId && m?.activityType === MCPAppsActivityType);
66
269
  /** Fetch the widget resource (`resources/read`) through the agent proxy queue. */
67
270
  const fetchResource = async () => {
68
271
  const agent = getAgent();
69
272
  if (!agent) throw new Error("No agent available to fetch resource");
70
273
  const { resourceUri, serverHash, serverId } = getContent();
71
- const resource = (await mcpAppsRequestQueue.enqueue(agent, () => agent.runAgent({ forwardedProps: { __proxiedMCPRequest: {
274
+ const resultData = (await mcpAppsRequestQueue.enqueue(agent, () => agent.runAgent({ forwardedProps: { __proxiedMCPRequest: {
72
275
  serverHash,
73
276
  serverId,
74
277
  method: "resources/read",
75
278
  params: { uri: resourceUri }
76
- } } }))).result?.contents?.[0];
279
+ } } }), {
280
+ owner: queueOwner,
281
+ timeoutMs: settings.idleTimeoutMs,
282
+ cancelRunningWait: opts.cancelRunningWaitOnTeardown,
283
+ dropAfterThreadSwitch: true
284
+ })).result;
285
+ const resource = selectResource(resultData?.contents, resourceUri, opts.requireExactResourceUri);
77
286
  if (!resource) throw new Error("No resource content in response");
78
287
  return resource;
79
288
  };
80
289
  /**
290
+ * Terminal shutdown, owned by the session itself.
291
+ *
292
+ * Used by `teardown()` AND by the sandbox watchdog: once the handshake window
293
+ * closes, the session must stop serving this widget rather than leave the
294
+ * bridge and its handlers live until the adapter happens to unmount. It does
295
+ * NOT remove the iframe - the adapter owns that element.
296
+ *
297
+ * Idempotent.
298
+ */
299
+ const closeSession = () => {
300
+ if (disposed) return;
301
+ disposed = true;
302
+ if (sandboxTimer !== void 0) {
303
+ clearTimeout(sandboxTimer);
304
+ sandboxTimer = void 0;
305
+ }
306
+ mcpAppsRequestQueue.cancelOwner(queueOwner);
307
+ activitySub?.unsubscribe();
308
+ activitySub = null;
309
+ const b = bridge;
310
+ bridge = null;
311
+ b?.close();
312
+ };
313
+ /**
81
314
  * Fetch the resource, configure + load the sandbox iframe, construct the
82
315
  * AppBridge, wire the app->host handlers, and connect the transport.
83
316
  */
@@ -95,21 +328,31 @@ function bindMcpApp(opts) {
95
328
  if (!win) throw new Error("Sandbox iframe has no contentWindow");
96
329
  let html;
97
330
  if (resource.text) html = resource.text;
98
- else if (resource.blob) html = atob(resource.blob);
331
+ else if (resource.blob) html = ɵdecodeBase64(resource.blob);
99
332
  else throw new Error("Resource has no text or blob content");
100
- bridge = new AppBridge(null, {
101
- name: "CopilotKit MCP Apps Host",
102
- version: "1.0.0"
103
- }, {
104
- openLinks: {},
105
- logging: {},
106
- message: { text: {} }
107
- }, { hostContext: {
333
+ bridge = new AppBridge(null, settings.hostInfo, settings.hostCapabilities, { hostContext: {
108
334
  theme: iframe.closest(".dark") ? "dark" : "light",
109
- platform: "web"
335
+ ...settings.hostContext
110
336
  } });
337
+ sandboxTimer = setTimeout(() => {
338
+ if (disposed || sandboxReady) return;
339
+ sandboxTimedOut = true;
340
+ hooks?.onError?.(/* @__PURE__ */ new Error(`[MCPAppsRenderer] Timed out after ${settings.initializationTimeoutMs}ms waiting for the MCP App sandbox to initialize.`));
341
+ closeSession();
342
+ }, settings.initializationTimeoutMs);
111
343
  bridge.onsandboxready = () => {
112
- bridge?.sendSandboxResourceReady({ html });
344
+ if (sandboxTimedOut) {
345
+ console.warn("[MCPAppsRenderer] Ignoring a sandbox handshake that arrived after the initialization timeout.");
346
+ return;
347
+ }
348
+ sandboxReady = true;
349
+ if (sandboxTimer !== void 0) {
350
+ clearTimeout(sandboxTimer);
351
+ sandboxTimer = void 0;
352
+ }
353
+ bridge?.sendSandboxResourceReady({ html }).then(() => {
354
+ if (!disposed) hooks?.onSandboxReady?.();
355
+ });
113
356
  };
114
357
  bridge.setRequestHandler(CopilotKitUiMessageSchema, async (req) => {
115
358
  const currentAgent = getAgent();
@@ -133,7 +376,15 @@ function bindMcpApp(opts) {
133
376
  host,
134
377
  agent: currentAgent,
135
378
  capturedThreadId
136
- })).catch((err) => console.error("[MCPAppsRenderer] ui/message agent run failed:", err));
379
+ }), {
380
+ timeoutMs: settings.idleTimeoutMs,
381
+ owner: cancelFollowUpsOnTeardown ? queueOwner : void 0,
382
+ cancelRunningWait: opts.cancelRunningWaitOnTeardown
383
+ }).catch((err) => {
384
+ if (disposed && cancelFollowUpsOnTeardown) return;
385
+ console.error("[MCPAppsRenderer] ui/message agent run failed:", err);
386
+ hooks?.onFollowUpError?.(err instanceof Error ? err : new Error(String(err)));
387
+ });
137
388
  }
138
389
  return { isError: false };
139
390
  } catch (err) {
@@ -142,18 +393,12 @@ function bindMcpApp(opts) {
142
393
  }
143
394
  });
144
395
  bridge.onopenlink = async ({ url }) => {
145
- let parsed;
146
- try {
147
- parsed = new URL(url);
148
- } catch {
149
- console.warn("[MCPAppsRenderer] ui/open-link rejected: unparseable url");
150
- return { isError: true };
151
- }
152
- if (MCP_OPEN_LINK_BLOCKED_SCHEMES.has(parsed.protocol)) {
153
- console.warn("[MCPAppsRenderer] ui/open-link rejected: blocked scheme", parsed.protocol);
396
+ const allowed = openLinkPolicy(url);
397
+ if (!allowed) {
398
+ console.warn("[MCPAppsRenderer] ui/open-link rejected by policy:", url);
154
399
  return { isError: true };
155
400
  }
156
- window.open(url, "_blank", "noopener,noreferrer");
401
+ window.open(allowed, "_blank", "noopener,noreferrer");
157
402
  return { isError: false };
158
403
  };
159
404
  bridge.oncalltool = async (params) => {
@@ -161,12 +406,24 @@ function bindMcpApp(opts) {
161
406
  const currentAgent = getAgent();
162
407
  if (!serverHash) throw new Error("No server hash available for proxying");
163
408
  if (!currentAgent) throw new Error("No agent available for proxying");
164
- return (await mcpAppsRequestQueue.enqueue(currentAgent, () => currentAgent.runAgent({ forwardedProps: { __proxiedMCPRequest: {
165
- serverHash,
166
- serverId,
167
- method: "tools/call",
168
- params
169
- } } }))).result || { content: [] };
409
+ let runResult;
410
+ try {
411
+ runResult = await mcpAppsRequestQueue.enqueue(currentAgent, () => currentAgent.runAgent({ forwardedProps: { __proxiedMCPRequest: {
412
+ serverHash,
413
+ serverId,
414
+ method: "tools/call",
415
+ params
416
+ } } }), {
417
+ owner: queueOwner,
418
+ timeoutMs: settings.idleTimeoutMs,
419
+ cancelRunningWait: opts.cancelRunningWaitOnTeardown,
420
+ dropAfterThreadSwitch: true
421
+ });
422
+ } catch (err) {
423
+ if (err instanceof MCPAppsQueueThreadChangedError) throw new Error(`tools/call was not executed: ${err.message} Retry from the current thread.`, { cause: err });
424
+ throw err;
425
+ }
426
+ return MCPAppsActivityContentSchema.shape.result.parse(runResult.result ?? {});
170
427
  };
171
428
  bridge.onsizechange = (p) => {
172
429
  if (disposed) return;
@@ -180,6 +437,13 @@ function bindMcpApp(opts) {
180
437
  if (disposed) return;
181
438
  ready = true;
182
439
  hooks?.onInitialized?.();
440
+ if (messageId && activityInStore()) {
441
+ pendingToolInput = void 0;
442
+ pendingToolResult = void 0;
443
+ lastToolInputKey = void 0;
444
+ lastToolResultKey = void 0;
445
+ pushFromMessages();
446
+ }
183
447
  flushPending();
184
448
  };
185
449
  bridge.onloggingmessage = (p) => {
@@ -192,6 +456,7 @@ function bindMcpApp(opts) {
192
456
  bridge = null;
193
457
  return;
194
458
  }
459
+ if (messageId) activitySub = getAgent()?.subscribe({ onMessagesChanged: ({ messages }) => pushFromMessages(messages) }) ?? null;
195
460
  } catch (err) {
196
461
  console.error("[MCPAppsRenderer] Setup error:", err);
197
462
  if (!disposed) hooks?.onError?.(err instanceof Error ? err : new Error(String(err)));
@@ -204,18 +469,19 @@ function bindMcpApp(opts) {
204
469
  flushPending();
205
470
  },
206
471
  sendToolResult(result) {
207
- pendingToolResult = result;
472
+ pendingToolResult = MCPAppsActivityContentSchema.shape.result.parse(result);
208
473
  flushPending();
209
474
  },
475
+ syncContent(content) {
476
+ if (messageId && activityInStore()) return;
477
+ pushFromContent(content);
478
+ },
210
479
  teardown() {
211
- disposed = true;
212
- const b = bridge;
213
- bridge = null;
214
- b?.close();
480
+ closeSession();
215
481
  }
216
482
  };
217
483
  }
218
484
 
219
485
  //#endregion
220
- export { MCP_APPS_PROTOCOL_VERSION, bindMcpApp };
486
+ export { MCP_APPS_PROTOCOL_VERSION, MCP_APPS_SESSION_DEFAULTS, bindMcpApp, denyDangerousSchemes, ɵdecodeBase64 };
221
487
  //# sourceMappingURL=session.mjs.map