@copilotkit/angular 0.5.2 → 0.6.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.
@@ -1,275 +1,11 @@
1
- import { z } from 'zod/v4';
1
+ import { MCPAppsActivityContentSchema } from '@copilotkit/mcp-apps-renderer/activity';
2
2
  import { isPlatformBrowser } from '@angular/common';
3
3
  import * as i0 from '@angular/core';
4
- import { InjectionToken, inject, PLATFORM_ID, input, computed, viewChild, signal, afterRenderEffect, ChangeDetectionStrategy, Component, makeEnvironmentProviders } from '@angular/core';
4
+ import { InjectionToken, inject, PLATFORM_ID, input, computed, viewChild, signal, afterRenderEffect, untracked, ChangeDetectionStrategy, Component, makeEnvironmentProviders } from '@angular/core';
5
5
  import { CopilotKit, ɵCOPILOTKIT_BUILT_IN_ACTIVITY_RENDERERS as _COPILOTKIT_BUILT_IN_ACTIVITY_RENDERERS } from '@copilotkit/angular';
6
- import { randomUUID } from '@copilotkit/shared';
7
6
 
8
- const annotationsSchema = z.looseObject({
9
- audience: z.array(z.enum(["user", "assistant"])).optional(),
10
- priority: z.number().min(0).max(1).optional(),
11
- lastModified: z.string().optional(),
12
- });
13
- const base64Schema = z
14
- .string()
15
- .refine((value) => value.length % 4 === 0 &&
16
- /^[A-Za-z0-9+/]*={0,2}$/.test(value) &&
17
- !/=/.test(value.slice(0, -2)), "Expected base64-encoded data");
18
- const resourceContentsSchema = z.union([
19
- z.looseObject({
20
- uri: z.string(),
21
- mimeType: z.string().optional(),
22
- text: z.string(),
23
- }),
24
- z.looseObject({
25
- uri: z.string(),
26
- mimeType: z.string().optional(),
27
- blob: base64Schema,
28
- }),
29
- ]);
30
- const contentItemSchema = z.discriminatedUnion("type", [
31
- z.looseObject({
32
- type: z.literal("text"),
33
- text: z.string(),
34
- annotations: annotationsSchema.optional(),
35
- }),
36
- z.looseObject({
37
- type: z.literal("image"),
38
- data: base64Schema,
39
- mimeType: z.string(),
40
- annotations: annotationsSchema.optional(),
41
- }),
42
- z.looseObject({
43
- type: z.literal("audio"),
44
- data: base64Schema,
45
- mimeType: z.string(),
46
- annotations: annotationsSchema.optional(),
47
- }),
48
- z.looseObject({
49
- type: z.literal("resource"),
50
- resource: resourceContentsSchema,
51
- annotations: annotationsSchema.optional(),
52
- }),
53
- z.looseObject({
54
- type: z.literal("resource_link"),
55
- uri: z.string(),
56
- name: z.string(),
57
- description: z.string().optional(),
58
- mimeType: z.string().optional(),
59
- annotations: annotationsSchema.optional(),
60
- }),
61
- ]);
62
- const callToolResultSchema = z.looseObject({
63
- content: z.array(contentItemSchema).default([]),
64
- structuredContent: z.record(z.string(), z.unknown()).optional(),
65
- isError: z.boolean().optional(),
66
- _meta: z.record(z.string(), z.unknown()).optional(),
67
- });
68
- /**
69
- * Content schema for `activityType: "mcp-apps"` activity messages: a snapshot
70
- * of an MCP Apps tool call, carrying the middleware server hash, optional
71
- * stable server id, the ui:// resource to render, and its tool exchange.
72
- *
73
- * Kept local and declared with the `zod/v4` API so the Angular browser bundle
74
- * validates protocol data without taking a direct MCP client SDK dependency.
75
- */
76
- const mcpAppsSnapshotContentSchema = z.looseObject({
77
- serverHash: z.string(),
78
- serverId: z.string().optional(),
79
- resourceUri: z.string(),
80
- result: callToolResultSchema,
81
- toolInput: z.record(z.string(), z.unknown()).optional(),
82
- });
83
-
84
- const DEFAULT_IDLE_TIMEOUT_MS = 30_000;
85
- const DEFAULT_IDLE_POLL_INTERVAL_MS = 500;
86
- /** Raised when a renderer cancels MCP work that it owns. */
87
- class MCPAppsQueueCancelledError extends Error {
88
- constructor() {
89
- super("MCP Apps request cancelled because its renderer was destroyed.");
90
- this.name = "MCPAppsQueueCancelledError";
91
- }
92
- }
93
- /** Raised when an agent does not become idle within the configured limit. */
94
- class MCPAppsQueueTimeoutError extends Error {
95
- constructor(timeoutMs) {
96
- super(`Timed out waiting ${timeoutMs}ms for the agent to become idle.`);
97
- this.name = "MCPAppsQueueTimeoutError";
98
- }
99
- }
100
- /** Raised when a queued follow-up no longer belongs to the active thread. */
101
- class MCPAppsQueueThreadChangedError extends Error {
102
- constructor(originThreadId, currentThreadId) {
103
- super(`Dropped MCP Apps follow-up after thread changed from "${originThreadId}" to "${currentThreadId}".`);
104
- this.name = "MCPAppsQueueThreadChangedError";
105
- }
106
- }
107
- /**
108
- * Serializes MCP requests per agent thread while retaining renderer ownership.
109
- *
110
- * An owner can abort its queued and active waits without affecting requests
111
- * created by another renderer. Follow-ups can additionally opt into a
112
- * thread-identity check immediately before execution.
113
- */
114
- class MCPAppsRequestQueue {
115
- queues = new Map();
116
- processing = new Map();
117
- idleTimeoutMs;
118
- idlePollIntervalMs;
119
- constructor(options = {}) {
120
- this.idleTimeoutMs = positiveDuration(options.idleTimeoutMs, DEFAULT_IDLE_TIMEOUT_MS, "idleTimeoutMs");
121
- this.idlePollIntervalMs = positiveDuration(options.idlePollIntervalMs, DEFAULT_IDLE_POLL_INTERVAL_MS, "idlePollIntervalMs");
122
- }
123
- /** Enqueues one request and resolves it in FIFO order for its thread. */
124
- enqueue(request) {
125
- const capturedThreadId = request.agent.threadId || "default";
126
- return new Promise((resolve, reject) => {
127
- const agentQueues = this.queues.get(request.agent) ?? new Map();
128
- const queue = agentQueues.get(capturedThreadId) ?? [];
129
- const item = {
130
- agent: request.agent,
131
- capturedThreadId,
132
- controller: new AbortController(),
133
- dropAfterThreadSwitch: request.dropAfterThreadSwitch ?? false,
134
- execute: request.execute,
135
- ownerId: request.ownerId,
136
- reject,
137
- resolve: (result) => resolve(result),
138
- };
139
- queue.push(item);
140
- agentQueues.set(capturedThreadId, queue);
141
- this.queues.set(request.agent, agentQueues);
142
- void this.processQueue(request.agent, capturedThreadId);
143
- });
144
- }
145
- /** Cancels only requests associated with the supplied renderer owner. */
146
- cancelOwner(ownerId) {
147
- for (const agentQueues of this.queues.values()) {
148
- for (const queue of agentQueues.values()) {
149
- for (const item of queue) {
150
- if (item.ownerId === ownerId && !item.controller.signal.aborted) {
151
- item.controller.abort();
152
- item.reject(new MCPAppsQueueCancelledError());
153
- }
154
- }
155
- }
156
- }
157
- }
158
- async processQueue(agent, threadId) {
159
- const processingThreads = this.processing.get(agent) ?? new Set();
160
- if (processingThreads.has(threadId))
161
- return;
162
- processingThreads.add(threadId);
163
- this.processing.set(agent, processingThreads);
164
- try {
165
- const queue = this.queues.get(agent)?.get(threadId);
166
- if (!queue)
167
- return;
168
- while (queue.length > 0) {
169
- const item = queue[0];
170
- try {
171
- this.throwIfCancelled(item.controller.signal);
172
- await this.waitForAgentIdle(item.agent, item.controller.signal);
173
- this.throwIfCancelled(item.controller.signal);
174
- const currentThreadId = item.agent.threadId || "default";
175
- if (item.dropAfterThreadSwitch &&
176
- currentThreadId !== item.capturedThreadId) {
177
- throw new MCPAppsQueueThreadChangedError(item.capturedThreadId, currentThreadId);
178
- }
179
- const result = await raceWithAbort(item.execute(item.controller.signal), item.controller.signal);
180
- item.resolve(result);
181
- }
182
- catch (error) {
183
- item.reject(asError$1(error));
184
- }
185
- finally {
186
- queue.shift();
187
- }
188
- }
189
- }
190
- finally {
191
- const agentQueues = this.queues.get(agent);
192
- agentQueues?.delete(threadId);
193
- if (agentQueues?.size === 0)
194
- this.queues.delete(agent);
195
- processingThreads.delete(threadId);
196
- if (processingThreads.size === 0)
197
- this.processing.delete(agent);
198
- }
199
- }
200
- waitForAgentIdle(agent, signal) {
201
- if (!agent.isRunning)
202
- return Promise.resolve();
203
- return new Promise((resolve, reject) => {
204
- let settled = false;
205
- let subscription;
206
- let interval;
207
- const cleanup = () => {
208
- clearTimeout(timeout);
209
- if (interval !== undefined)
210
- clearInterval(interval);
211
- subscription?.unsubscribe();
212
- signal.removeEventListener("abort", cancel);
213
- };
214
- const finish = () => {
215
- if (settled)
216
- return;
217
- settled = true;
218
- cleanup();
219
- resolve();
220
- };
221
- const fail = (error) => {
222
- if (settled)
223
- return;
224
- settled = true;
225
- cleanup();
226
- reject(error);
227
- };
228
- const cancel = () => fail(new MCPAppsQueueCancelledError());
229
- const timeout = setTimeout(() => fail(new MCPAppsQueueTimeoutError(this.idleTimeoutMs)), this.idleTimeoutMs);
230
- signal.addEventListener("abort", cancel, { once: true });
231
- subscription = agent.subscribe({
232
- onRunFinalized: finish,
233
- onRunFailed: finish,
234
- });
235
- interval = setInterval(() => {
236
- if (!agent.isRunning)
237
- finish();
238
- }, this.idlePollIntervalMs);
239
- if (signal.aborted)
240
- cancel();
241
- });
242
- }
243
- throwIfCancelled(signal) {
244
- if (signal.aborted)
245
- throw new MCPAppsQueueCancelledError();
246
- }
247
- }
248
- function positiveDuration(value, fallback, name) {
249
- const resolved = value ?? fallback;
250
- if (!Number.isFinite(resolved) || resolved <= 0) {
251
- throw new RangeError(`${name} must be a positive finite number.`);
252
- }
253
- return resolved;
254
- }
255
- function raceWithAbort(promise, signal) {
256
- if (signal.aborted)
257
- return Promise.reject(new MCPAppsQueueCancelledError());
258
- return new Promise((resolve, reject) => {
259
- const cancel = () => reject(new MCPAppsQueueCancelledError());
260
- signal.addEventListener("abort", cancel, { once: true });
261
- promise.then((value) => {
262
- signal.removeEventListener("abort", cancel);
263
- resolve(value);
264
- }, (error) => {
265
- signal.removeEventListener("abort", cancel);
266
- reject(error);
267
- });
268
- });
269
- }
270
- function asError$1(error) {
271
- return error instanceof Error ? error : new Error(String(error));
272
- }
7
+ /** Preserve the Angular export while sharing the runtime content contract. */
8
+ const mcpAppsSnapshotContentSchema = MCPAppsActivityContentSchema;
273
9
 
274
10
  const DEFAULT_MCP_APPS_CONFIG = {
275
11
  idleTimeoutMs: 30_000,
@@ -284,49 +20,58 @@ const DEFAULT_MCP_APPS_CONFIG = {
284
20
  logging: {},
285
21
  },
286
22
  hostContext: {
287
- theme: "light",
288
23
  platform: "web",
289
24
  },
290
25
  };
291
26
  /** Holds renderer behavior configuration registered via `provideMCPApps`. */
292
27
  const MCP_APPS_CONFIG = new InjectionToken("MCP_APPS_CONFIG", { factory: () => ({ ...DEFAULT_MCP_APPS_CONFIG }) });
293
28
 
294
- const PROTOCOL_VERSION = "2025-06-18";
295
- const queuesByIdleTimeout = new Map();
296
- /**
297
- * Renders one MCP App snapshot through the same agent-mediated protocol used
298
- * by the other CopilotKit frontends. Each instance owns its queued work and
299
- * sandbox listener, while requests remain serialized per agent thread.
300
- */
29
+ /** Angular owns the DOM and reactive state; the shared session owns MCP. */
301
30
  class CopilotMCPAppsWidget {
302
31
  config = inject(MCP_APPS_CONFIG);
303
32
  copilotKit = inject(CopilotKit);
304
33
  platformId = inject(PLATFORM_ID);
305
- ownerId = randomUUID();
306
- queue = queueForTimeout(this.config.idleTimeoutMs);
307
- renderVersion = 0;
34
+ session;
308
35
  data = input.required(/* @ts-ignore */
309
36
  ...(ngDevMode ? [{ debugName: "data" }] : /* istanbul ignore next */ []));
310
37
  agent = input(/* @ts-ignore */
311
38
  ...(ngDevMode ? [undefined, { debugName: "agent" }] : /* istanbul ignore next */ []));
312
- renderSession = computed(() => ({ agent: this.agent(), data: this.data() }), { ...(ngDevMode ? { debugName: "renderSession" } : /* istanbul ignore next */ {}), equal: (previous, current) => previous.agent === current.agent &&
313
- areStructurallyEqual(previous.data, current.data) });
39
+ /** Omitted for direct widget use with external, prop-driven content. */
40
+ messageId = input(/* @ts-ignore */
41
+ ...(ngDevMode ? [undefined, { debugName: "messageId" }] : /* istanbul ignore next */ []));
42
+ identity = computed(() => {
43
+ const { resourceUri, serverHash, serverId } = this.data();
44
+ return { resourceUri, serverHash, serverId };
45
+ }, { ...(ngDevMode ? { debugName: "identity" } : /* istanbul ignore next */ {}), equal: (a, b) => a.resourceUri === b.resourceUri &&
46
+ a.serverHash === b.serverHash &&
47
+ a.serverId === b.serverId });
314
48
  appFrame = viewChild.required("appFrame");
315
49
  loading = signal(true, /* @ts-ignore */
316
50
  ...(ngDevMode ? [{ debugName: "loading" }] : /* istanbul ignore next */ []));
317
51
  error = signal("", /* @ts-ignore */
318
52
  ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
53
+ contentError = signal("", /* @ts-ignore */
54
+ ...(ngDevMode ? [{ debugName: "contentError" }] : /* istanbul ignore next */ []));
319
55
  constructor() {
320
56
  afterRenderEffect((onCleanup) => {
57
+ this.identity();
58
+ const agent = this.agent();
59
+ const messageId = this.messageId();
321
60
  const frame = this.appFrame().nativeElement;
322
- const { data, agent } = this.renderSession();
323
- const version = ++this.renderVersion;
324
- const controller = new AbortController();
325
- this.queue.cancelOwner(this.ownerId);
326
- this.resetFrame(frame);
61
+ let active = true;
62
+ let session;
63
+ this.loading.set(true);
64
+ this.error.set("");
65
+ this.contentError.set("");
66
+ frame.style.removeProperty("height");
67
+ frame.removeAttribute("src");
68
+ frame.removeAttribute("srcdoc");
69
+ frame.removeAttribute("data-mcp-app-initialized");
327
70
  onCleanup(() => {
328
- controller.abort();
329
- this.queue.cancelOwner(this.ownerId);
71
+ active = false;
72
+ session?.teardown();
73
+ if (this.session === session)
74
+ this.session = undefined;
330
75
  frame.removeAttribute("srcdoc");
331
76
  frame.removeAttribute("src");
332
77
  frame.removeAttribute("data-mcp-app-initialized");
@@ -335,258 +80,93 @@ class CopilotMCPAppsWidget {
335
80
  this.loading.set(false);
336
81
  return;
337
82
  }
338
- void this.renderApp(frame, data, agent, controller, version);
339
- });
340
- }
341
- async renderApp(frame, data, agent, controller, version) {
342
- if (!agent) {
343
- this.fail("No agent is available to load this MCP App.", frame, version);
344
- return;
345
- }
346
- try {
347
- const runResult = await this.queue.enqueue({
348
- agent,
349
- ownerId: this.ownerId,
350
- execute: () => agent.runAgent({
351
- forwardedProps: {
352
- __proxiedMCPRequest: {
353
- serverHash: data.serverHash,
354
- serverId: data.serverId,
355
- method: "resources/read",
356
- params: { uri: data.resourceUri },
357
- },
358
- },
359
- }),
360
- });
361
- this.throwIfStale(controller.signal, version);
362
- const resource = findResource(runResult, data.resourceUri);
363
- const html = resource.text
364
- ? resource.text
365
- : resource.blob
366
- ? decodeBase64(resource.blob)
367
- : undefined;
368
- if (!html) {
369
- throw new Error("The MCP App resource has no text or blob content.");
370
- }
371
- frame.removeAttribute("data-mcp-app-initialized");
372
- const sandboxReady = this.connectSandbox(frame, data, agent, controller.signal, version);
373
- frame.setAttribute("sandbox", "allow-scripts allow-same-origin allow-forms");
374
- frame.removeAttribute("src");
375
- frame.srcdoc = buildSandboxHTML(resource._meta?.ui?.csp?.resourceDomains);
376
- await sandboxReady;
377
- this.throwIfStale(controller.signal, version);
378
- this.sendNotification(frame, "ui/notifications/sandbox-resource-ready", {
379
- html,
380
- });
381
- this.loading.set(false);
382
- }
383
- catch (error) {
384
- if (isCancellation(error))
83
+ if (!agent) {
84
+ this.loading.set(false);
85
+ this.error.set("No agent is available to load this MCP App.");
385
86
  return;
386
- this.fail(asError(error).message, frame, version);
387
- }
388
- }
389
- connectSandbox(frame, data, agent, abortSignal, version) {
390
- return new Promise((resolve, reject) => {
391
- let ready = false;
392
- const timeout = setTimeout(() => {
393
- cleanup();
394
- reject(new Error(`Timed out waiting ${this.config.initializationTimeoutMs}ms for the MCP App sandbox.`));
395
- }, this.config.initializationTimeoutMs);
396
- const cancel = () => {
397
- cleanup();
398
- reject(new MCPAppsQueueCancelledError());
399
- };
400
- const onMessage = (event) => {
401
- if (event.source !== frame.contentWindow)
402
- return;
403
- const message = parseJSONRPCMessage(event.data);
404
- if (!message)
405
- return;
406
- if (message.method === "ui/notifications/sandbox-proxy-ready") {
407
- if (!ready) {
408
- ready = true;
409
- clearTimeout(timeout);
410
- resolve();
411
- }
87
+ }
88
+ const fail = (error) => {
89
+ if (!active)
412
90
  return;
413
- }
414
- void this.handleMessage(frame, data, agent, message, abortSignal, version);
415
- };
416
- const cleanup = () => {
417
- clearTimeout(timeout);
418
- window.removeEventListener("message", onMessage);
419
- abortSignal.removeEventListener("abort", cancel);
91
+ this.loading.set(false);
92
+ this.error.set(error.message);
93
+ session?.teardown();
94
+ frame.removeAttribute("srcdoc");
95
+ frame.removeAttribute("data-mcp-app-initialized");
420
96
  };
421
- window.addEventListener("message", onMessage);
422
- abortSignal.addEventListener("abort", cancel, { once: true });
423
- if (abortSignal.aborted)
424
- cancel();
425
- // Keep protocol messages connected after initialization. Cleanup occurs
426
- // when this render session's abort signal fires.
427
- abortSignal.addEventListener("abort", () => window.removeEventListener("message", onMessage), { once: true });
428
- });
429
- }
430
- async handleMessage(frame, data, agent, message, abortSignal, version) {
431
- if (abortSignal.aborted || version !== this.renderVersion)
432
- return;
433
- if (message.id !== undefined) {
434
- switch (message.method) {
435
- case "ui/initialize":
436
- frame.setAttribute("data-mcp-app-initialized", "true");
437
- this.sendResponse(frame, message.id, {
438
- protocolVersion: PROTOCOL_VERSION,
439
- hostInfo: this.config.hostInfo,
440
- hostCapabilities: this.config.hostCapabilities,
441
- hostContext: this.config.hostContext,
442
- });
443
- return;
444
- case "ui/message":
445
- await this.handleUIMessage(frame, agent, message, version);
446
- return;
447
- case "ui/open-link":
448
- this.handleOpenLink(frame, message);
449
- return;
450
- case "tools/call":
451
- await this.handleToolCall(frame, data, agent, message, abortSignal);
97
+ // Cleanup is registered before importing, so an obsolete bind never starts.
98
+ void import('@copilotkit/mcp-apps-renderer')
99
+ .catch((importErr) => {
100
+ // Name the packages and the fix: the raw module-resolution error
101
+ // ("Failed to fetch dynamically imported module...") tells a user
102
+ // nothing about what to install. Same message as React and Vue.
103
+ throw new Error("MCP Apps require '@copilotkit/mcp-apps-renderer' and its " +
104
+ "'@modelcontextprotocol/ext-apps' dependency. Reinstall your " +
105
+ "dependencies if this package is missing.", { cause: importErr });
106
+ })
107
+ .then((mcp) => {
108
+ if (!active)
452
109
  return;
453
- default:
454
- this.sendError(frame, message.id, -32601, `Method not found: ${message.method}`);
455
- return;
456
- }
457
- }
458
- switch (message.method) {
459
- case "ui/notifications/initialized":
460
- if (data.toolInput) {
461
- this.sendNotification(frame, "ui/notifications/tool-input", {
462
- arguments: data.toolInput,
463
- });
464
- }
465
- this.sendNotification(frame, "ui/notifications/tool-result", data.result);
466
- break;
467
- case "ui/notifications/size-changed": {
468
- const height = message.params?.height;
469
- if (typeof height === "number" &&
470
- Number.isFinite(height) &&
471
- height > 0) {
472
- frame.style.height = `${Math.ceil(Math.min(height, 5000))}px`;
473
- }
474
- break;
475
- }
476
- case "notifications/message":
477
- console.info("[CopilotKit MCP App]", message.params ?? {});
478
- break;
479
- }
480
- }
481
- async handleUIMessage(frame, agent, message, version) {
482
- const id = message.id;
483
- const role = message.params?.role === "assistant" ? "assistant" : "user";
484
- const content = Array.isArray(message.params?.content)
485
- ? message.params.content
486
- .filter(isTextContent)
487
- .map((part) => part.text)
488
- .join("\n")
489
- : "";
490
- if (content) {
491
- agent.addMessage({ id: randomUUID(), role, content });
492
- }
493
- this.sendResponse(frame, id, { isError: false });
494
- const shouldFollowUp = typeof message.params?.followUp === "boolean"
495
- ? message.params.followUp
496
- : role === "user";
497
- if (!shouldFollowUp || !content)
498
- return;
499
- try {
500
- await this.queue.enqueue({
501
- agent,
502
- ownerId: this.ownerId,
503
- dropAfterThreadSwitch: true,
504
- execute: () => this.copilotKit.core.runAgent({ agent }),
505
- });
506
- }
507
- catch (error) {
508
- if (isCancellation(error))
509
- return;
510
- this.fail(`MCP App follow-up failed: ${asError(error).message}`, frame, version);
511
- }
512
- }
513
- handleOpenLink(frame, message) {
514
- const id = message.id;
515
- const url = safeExternalURL(message.params?.url);
516
- if (!url) {
517
- this.sendError(frame, id, -32602, "A valid HTTP(S) URL is required.");
518
- return;
519
- }
520
- window.open(url, "_blank", "noopener,noreferrer");
521
- this.sendResponse(frame, id, { isError: false });
522
- }
523
- async handleToolCall(frame, data, agent, message, abortSignal) {
524
- const id = message.id;
525
- try {
526
- const runResult = await this.queue.enqueue({
527
- agent,
528
- ownerId: this.ownerId,
529
- execute: () => agent.runAgent({
530
- forwardedProps: {
531
- __proxiedMCPRequest: {
532
- serverHash: data.serverHash,
533
- serverId: data.serverId,
534
- method: "tools/call",
535
- params: message.params,
110
+ session = mcp.bindMcpApp({
111
+ iframe: frame,
112
+ getContent: () => untracked(this.data),
113
+ getAgent: () => agent,
114
+ messageId,
115
+ host: this.copilotKit.core,
116
+ options: this.config,
117
+ cancelFollowUpsOnTeardown: true,
118
+ requireExactResourceUri: true,
119
+ cancelRunningWaitOnTeardown: true,
120
+ hooks: {
121
+ onSandboxReady: () => {
122
+ if (active)
123
+ this.loading.set(false);
124
+ },
125
+ onInitialized: () => {
126
+ if (!active)
127
+ return;
128
+ this.loading.set(false);
129
+ frame.setAttribute("data-mcp-app-initialized", "true");
130
+ },
131
+ onSizeChanged: ({ height }) => {
132
+ if (active &&
133
+ typeof height === "number" &&
134
+ Number.isFinite(height) &&
135
+ height > 0) {
136
+ frame.style.height = `${Math.ceil(Math.min(height, 5000))}px`;
137
+ }
536
138
  },
139
+ onError: fail,
140
+ onContentError: (err) => {
141
+ if (active)
142
+ this.contentError.set(err?.message ?? "");
143
+ },
144
+ onFollowUpError: fail,
537
145
  },
538
- }),
539
- });
540
- if (!abortSignal.aborted)
541
- this.sendResponse(frame, id, runResult.result ?? {});
542
- }
543
- catch (error) {
544
- if (isCancellation(error))
545
- return;
546
- this.sendError(frame, id, -32603, asError(error).message);
547
- }
548
- }
549
- sendResponse(frame, id, result) {
550
- frame.contentWindow?.postMessage({ jsonrpc: "2.0", id, result }, "*");
551
- }
552
- sendError(frame, id, code, message) {
553
- frame.contentWindow?.postMessage({ jsonrpc: "2.0", id, error: { code, message } }, "*");
554
- }
555
- sendNotification(frame, method, params) {
556
- frame.contentWindow?.postMessage({ jsonrpc: "2.0", method, params }, "*");
557
- }
558
- fail(message, frame, version) {
559
- if (version !== this.renderVersion)
560
- return;
561
- this.loading.set(false);
562
- this.error.set(message);
563
- frame.removeAttribute("srcdoc");
564
- frame.removeAttribute("src");
565
- frame.removeAttribute("data-mcp-app-initialized");
566
- }
567
- resetFrame(frame) {
568
- this.loading.set(true);
569
- this.error.set("");
570
- frame.style.removeProperty("height");
571
- frame.removeAttribute("srcdoc");
572
- frame.removeAttribute("src");
573
- frame.removeAttribute("data-mcp-app-initialized");
574
- }
575
- throwIfStale(abortSignal, version) {
576
- if (abortSignal.aborted || version !== this.renderVersion) {
577
- throw new MCPAppsQueueCancelledError();
578
- }
146
+ });
147
+ this.session = session;
148
+ session.syncContent(untracked(this.data));
149
+ })
150
+ .catch(fail);
151
+ });
152
+ // Content updates feed the existing session and never reload its iframe.
153
+ afterRenderEffect(() => {
154
+ const data = this.data();
155
+ untracked(() => this.session?.syncContent(data));
156
+ });
579
157
  }
580
158
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.0", ngImport: i0, type: CopilotMCPAppsWidget, deps: [], target: i0.ɵɵFactoryTarget.Component });
581
- static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "22.0.0", type: CopilotMCPAppsWidget, isStandalone: true, selector: "copilot-mcp-apps-widget", inputs: { data: { classPropertyName: "data", publicName: "data", isSignal: true, isRequired: true, transformFunction: null }, agent: { classPropertyName: "agent", publicName: "agent", isSignal: true, isRequired: false, transformFunction: null } }, viewQueries: [{ propertyName: "appFrame", first: true, predicate: ["appFrame"], descendants: true, isSignal: true }], ngImport: i0, template: `
159
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "22.0.0", type: CopilotMCPAppsWidget, isStandalone: true, selector: "copilot-mcp-apps-widget", inputs: { data: { classPropertyName: "data", publicName: "data", isSignal: true, isRequired: true, transformFunction: null }, agent: { classPropertyName: "agent", publicName: "agent", isSignal: true, isRequired: false, transformFunction: null }, messageId: { classPropertyName: "messageId", publicName: "messageId", isSignal: true, isRequired: false, transformFunction: null } }, viewQueries: [{ propertyName: "appFrame", first: true, predicate: ["appFrame"], descendants: true, isSignal: true }], ngImport: i0, template: `
582
160
  <div class="copilot-mcp-apps-container">
583
161
  @if (loading()) {
584
162
  <p class="copilot-mcp-apps-status" role="status" aria-live="polite">
585
163
  Loading MCP App…
586
164
  </p>
587
165
  }
588
- @if (error()) {
589
- <p class="copilot-mcp-apps-error" role="alert">{{ error() }}</p>
166
+ @if (error() || contentError()) {
167
+ <p class="copilot-mcp-apps-error" role="alert">
168
+ {{ error() || contentError() }}
169
+ </p>
590
170
  }
591
171
  <iframe
592
172
  #appFrame
@@ -606,8 +186,10 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.0", ngImpor
606
186
  Loading MCP App…
607
187
  </p>
608
188
  }
609
- @if (error()) {
610
- <p class="copilot-mcp-apps-error" role="alert">{{ error() }}</p>
189
+ @if (error() || contentError()) {
190
+ <p class="copilot-mcp-apps-error" role="alert">
191
+ {{ error() || contentError() }}
192
+ </p>
611
193
  }
612
194
  <iframe
613
195
  #appFrame
@@ -617,130 +199,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.0", ngImpor
617
199
  ></iframe>
618
200
  </div>
619
201
  `, styles: [".copilot-mcp-apps-container{position:relative;width:100%;min-height:100px;overflow:hidden}.copilot-mcp-apps-frame{display:block;width:100%;min-height:100px;border:0;background:transparent}.copilot-mcp-apps-status,.copilot-mcp-apps-error{margin:0;padding:16px}.copilot-mcp-apps-status{color:#525252}.copilot-mcp-apps-error{color:#991b1b}\n"] }]
620
- }], ctorParameters: () => [], propDecorators: { data: [{ type: i0.Input, args: [{ isSignal: true, alias: "data", required: true }] }], agent: [{ type: i0.Input, args: [{ isSignal: true, alias: "agent", required: false }] }], appFrame: [{ type: i0.ViewChild, args: ["appFrame", { isSignal: true }] }] } });
621
- function queueForTimeout(idleTimeoutMs) {
622
- let queue = queuesByIdleTimeout.get(idleTimeoutMs);
623
- if (!queue) {
624
- queue = new MCPAppsRequestQueue({ idleTimeoutMs });
625
- queuesByIdleTimeout.set(idleTimeoutMs, queue);
626
- }
627
- return queue;
628
- }
629
- function findResource(runResult, resourceUri) {
630
- const result = runResult.result;
631
- const resource = result?.contents?.find((candidate) => candidate.uri === resourceUri);
632
- if (!resource) {
633
- throw new Error(`No matching MCP App resource was returned for "${resourceUri}".`);
634
- }
635
- return resource;
636
- }
637
- function parseJSONRPCMessage(value) {
638
- if (!isRecord(value) ||
639
- value.jsonrpc !== "2.0" ||
640
- typeof value.method !== "string") {
641
- return undefined;
642
- }
643
- if (value.id !== undefined &&
644
- typeof value.id !== "string" &&
645
- typeof value.id !== "number") {
646
- return undefined;
647
- }
648
- if (value.params !== undefined && !isRecord(value.params))
649
- return undefined;
650
- return value;
651
- }
652
- function isRecord(value) {
653
- return Boolean(value && typeof value === "object" && !Array.isArray(value));
654
- }
655
- function isTextContent(value) {
656
- return (isRecord(value) && value.type === "text" && typeof value.text === "string");
657
- }
658
- function safeExternalURL(value) {
659
- if (typeof value !== "string")
660
- return undefined;
661
- try {
662
- const url = new URL(value, window.location.href);
663
- if (url.protocol !== "http:" && url.protocol !== "https:")
664
- return undefined;
665
- if (url.username || url.password)
666
- return undefined;
667
- return url.href;
668
- }
669
- catch {
670
- return undefined;
671
- }
672
- }
673
- function decodeBase64(value) {
674
- try {
675
- const binary = atob(value);
676
- const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
677
- return new TextDecoder().decode(bytes);
678
- }
679
- catch {
680
- throw new Error("The MCP App resource contains invalid base64 content.");
681
- }
682
- }
683
- function isCancellation(error) {
684
- return (error instanceof MCPAppsQueueCancelledError ||
685
- error instanceof MCPAppsQueueThreadChangedError);
686
- }
687
- function asError(error) {
688
- return error instanceof Error ? error : new Error(String(error));
689
- }
690
- /** Compares JSON-compatible activity snapshots without relying on object identity. */
691
- function areStructurallyEqual(left, right) {
692
- if (Object.is(left, right))
693
- return true;
694
- if (Array.isArray(left) || Array.isArray(right)) {
695
- return (Array.isArray(left) &&
696
- Array.isArray(right) &&
697
- left.length === right.length &&
698
- left.every((value, index) => areStructurallyEqual(value, right[index])));
699
- }
700
- if (!isRecord(left) || !isRecord(right))
701
- return false;
702
- const leftKeys = Object.keys(left);
703
- const rightKeys = Object.keys(right);
704
- return (leftKeys.length === rightKeys.length &&
705
- leftKeys.every((key) => Object.prototype.hasOwnProperty.call(right, key) &&
706
- areStructurallyEqual(left[key], right[key])));
707
- }
708
- function buildSandboxHTML(extraCspDomains) {
709
- const baseScriptSrc = "'self' 'wasm-unsafe-eval' 'unsafe-inline' 'unsafe-eval' blob: data: http://localhost:* https://localhost:*";
710
- const baseFrameSrc = "* blob: data: http://localhost:* https://localhost:*";
711
- const extra = extraCspDomains?.length ? ` ${extraCspDomains.join(" ")}` : "";
712
- const scriptSrc = baseScriptSrc + extra;
713
- const frameSrc = baseFrameSrc + extra;
714
- return `<!doctype html>
715
- <html>
716
- <head>
717
- <meta charset="utf-8" />
718
- <meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src * data: blob: 'unsafe-inline'; media-src * blob: data:; font-src * blob: data:; script-src ${scriptSrc}; style-src * blob: data: 'unsafe-inline'; connect-src *; frame-src ${frameSrc}; base-uri 'self';" />
719
- <style>html,body{margin:0;padding:0;height:100%;width:100%;overflow:hidden}*{box-sizing:border-box}iframe{background-color:transparent;border:none;padding:0;overflow:hidden;width:100%;height:100%}</style>
720
- </head>
721
- <body>
722
- <script>
723
- if(window.self===window.top){throw new Error("This file must be used in an iframe.")}
724
- const inner=document.createElement("iframe");
725
- inner.style="width:100%;height:100%;border:none;";
726
- inner.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms");
727
- document.body.appendChild(inner);
728
- window.addEventListener("message",async(event)=>{
729
- if(event.source===window.parent){
730
- if(event.data&&event.data.method==="ui/notifications/sandbox-resource-ready"){
731
- const{html,sandbox}=event.data.params;
732
- if(typeof sandbox==="string")inner.setAttribute("sandbox",sandbox);
733
- if(typeof html==="string")inner.srcdoc=html;
734
- }else if(inner&&inner.contentWindow){
735
- inner.contentWindow.postMessage(event.data,"*");
736
- }
737
- }else if(event.source===inner.contentWindow){window.parent.postMessage(event.data,"*")}
738
- });
739
- window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-ready",params:{}},"*");
740
- </script>
741
- </body>
742
- </html>`;
743
- }
202
+ }], ctorParameters: () => [], propDecorators: { data: [{ type: i0.Input, args: [{ isSignal: true, alias: "data", required: true }] }], agent: [{ type: i0.Input, args: [{ isSignal: true, alias: "agent", required: false }] }], messageId: [{ type: i0.Input, args: [{ isSignal: true, alias: "messageId", required: false }] }], appFrame: [{ type: i0.ViewChild, args: ["appFrame", { isSignal: true }] }] } });
744
203
 
745
204
  /**
746
205
  * Activity renderer for `mcp-apps` snapshots. Renders the referenced MCP App
@@ -758,8 +217,12 @@ class CopilotMCPAppsActivityRenderer {
758
217
  ...(ngDevMode ? [undefined, { debugName: "agent" }] : /* istanbul ignore next */ []));
759
218
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.0", ngImport: i0, type: CopilotMCPAppsActivityRenderer, deps: [], target: i0.ɵɵFactoryTarget.Component });
760
219
  static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.1.0", version: "22.0.0", type: CopilotMCPAppsActivityRenderer, isStandalone: true, selector: "copilot-mcp-apps-activity-renderer", inputs: { activityType: { classPropertyName: "activityType", publicName: "activityType", isSignal: true, isRequired: true, transformFunction: null }, content: { classPropertyName: "content", publicName: "content", isSignal: true, isRequired: true, transformFunction: null }, message: { classPropertyName: "message", publicName: "message", isSignal: true, isRequired: true, transformFunction: null }, agent: { classPropertyName: "agent", publicName: "agent", isSignal: true, isRequired: false, transformFunction: null } }, ngImport: i0, template: `
761
- <copilot-mcp-apps-widget [data]="content()" [agent]="agent()" />
762
- `, isInline: true, dependencies: [{ kind: "component", type: CopilotMCPAppsWidget, selector: "copilot-mcp-apps-widget", inputs: ["data", "agent"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
220
+ <copilot-mcp-apps-widget
221
+ [data]="content()"
222
+ [agent]="agent()"
223
+ [messageId]="message().id"
224
+ />
225
+ `, isInline: true, dependencies: [{ kind: "component", type: CopilotMCPAppsWidget, selector: "copilot-mcp-apps-widget", inputs: ["data", "agent", "messageId"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
763
226
  }
764
227
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.0", ngImport: i0, type: CopilotMCPAppsActivityRenderer, decorators: [{
765
228
  type: Component,
@@ -768,7 +231,11 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.0", ngImpor
768
231
  changeDetection: ChangeDetectionStrategy.OnPush,
769
232
  imports: [CopilotMCPAppsWidget],
770
233
  template: `
771
- <copilot-mcp-apps-widget [data]="content()" [agent]="agent()" />
234
+ <copilot-mcp-apps-widget
235
+ [data]="content()"
236
+ [agent]="agent()"
237
+ [messageId]="message().id"
238
+ />
772
239
  `,
773
240
  }]
774
241
  }], propDecorators: { activityType: [{ type: i0.Input, args: [{ isSignal: true, alias: "activityType", required: true }] }], content: [{ type: i0.Input, args: [{ isSignal: true, alias: "content", required: true }] }], message: [{ type: i0.Input, args: [{ isSignal: true, alias: "message", required: true }] }], agent: [{ type: i0.Input, args: [{ isSignal: true, alias: "agent", required: false }] }] } });
@@ -790,6 +257,10 @@ const mcpAppsActivityRendererConfig = {
790
257
  * Application renderers retain precedence over this built-in registration.
791
258
  */
792
259
  function provideMCPApps(config = {}) {
260
+ const idleTimeoutMs = config.idleTimeoutMs ?? DEFAULT_MCP_APPS_CONFIG.idleTimeoutMs;
261
+ if (!Number.isFinite(idleTimeoutMs) || idleTimeoutMs <= 0) {
262
+ throw new RangeError("idleTimeoutMs must be a positive finite number.");
263
+ }
793
264
  return makeEnvironmentProviders([
794
265
  {
795
266
  provide: MCP_APPS_CONFIG,