@copilotkit/mcp-apps-renderer 2.0.0-rc.4 → 2.0.0-rc.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_virtual/_rolldown/runtime.cjs +29 -0
- package/dist/activity.cjs +6 -0
- package/dist/activity.d.cts +2 -1
- package/dist/activity.d.mts +2 -1
- package/dist/activity.mjs +2 -1
- package/dist/activity.umd.js +369 -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/host.cjs +246 -0
- package/dist/host.cjs.map +1 -0
- package/dist/host.d.cts +99 -0
- package/dist/host.d.cts.map +1 -0
- package/dist/host.d.mts +99 -0
- package/dist/host.d.mts.map +1 -0
- package/dist/host.mjs +241 -0
- package/dist/host.mjs.map +1 -0
- package/dist/request-queue.mjs.map +1 -1
- package/dist/session.d.cts +172 -0
- package/dist/session.d.cts.map +1 -0
- package/dist/session.d.mts +1 -58
- package/dist/session.d.mts.map +1 -1
- package/dist/session.mjs +2 -2
- package/dist/session.mjs.map +1 -1
- package/package.json +17 -8
package/dist/host.mjs
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
//#region src/host.ts
|
|
2
|
+
/** Message shown when the bridge package cannot be loaded. */
|
|
3
|
+
const MCP_APPS_RENDERER_MISSING_MESSAGE = "MCP Apps require '@copilotkit/mcp-apps-renderer' and its '@modelcontextprotocol/ext-apps' dependency. Reinstall your dependencies if this package is missing.";
|
|
4
|
+
/** Error text when an MCP App renders without an agent to fetch it through. */
|
|
5
|
+
const MCP_APPS_NO_AGENT_MESSAGE = "No agent available to fetch resource";
|
|
6
|
+
/** Tallest an MCP App iframe may grow, in pixels. */
|
|
7
|
+
const MCP_APP_MAX_HEIGHT = 5e3;
|
|
8
|
+
/** The height the iframe starts at before the widget reports its size. */
|
|
9
|
+
const INITIAL_HEIGHT_PX = 100;
|
|
10
|
+
/**
|
|
11
|
+
* Loads the bridge (`bindMcpApp`) lazily. The bridge pulls the MCP SDK and
|
|
12
|
+
* its zod schemas (~40-50 kB gzipped), so an app only pays for it when an MCP
|
|
13
|
+
* App renders. The `import()` itself stays in the frontend, where its bundler
|
|
14
|
+
* can split it out. A failed load rethrows with what to install, since a raw
|
|
15
|
+
* module-resolution error does not say.
|
|
16
|
+
*
|
|
17
|
+
* @param importRenderer - `() => import("@copilotkit/mcp-apps-renderer")`.
|
|
18
|
+
*/
|
|
19
|
+
function loadMcpAppsRenderer(importRenderer) {
|
|
20
|
+
return importRenderer().catch((importErr) => {
|
|
21
|
+
throw new Error(MCP_APPS_RENDERER_MISSING_MESSAGE, { cause: importErr });
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
function identityOf(content) {
|
|
25
|
+
if (!content) return "";
|
|
26
|
+
return JSON.stringify([
|
|
27
|
+
content.resourceUri,
|
|
28
|
+
content.serverHash,
|
|
29
|
+
content.serverId
|
|
30
|
+
]);
|
|
31
|
+
}
|
|
32
|
+
const INITIAL_STATE = {
|
|
33
|
+
loading: true,
|
|
34
|
+
error: null,
|
|
35
|
+
contentError: null,
|
|
36
|
+
size: {},
|
|
37
|
+
prefersBorder: false
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* Hosts one MCP App: creates the sandbox iframe in a container, binds the
|
|
41
|
+
* MCP session to it, sizes it as the widget reports, and keeps the state a
|
|
42
|
+
* frontend renders. It binds again (new iframe, new session) only when the
|
|
43
|
+
* container, agent, message id or widget identity (resource URI, server)
|
|
44
|
+
* changes; new tool input or results feed the existing session.
|
|
45
|
+
*
|
|
46
|
+
* @example
|
|
47
|
+
* ```ts
|
|
48
|
+
* const app = new ɵMcpAppHost({ host: core });
|
|
49
|
+
* app.subscribe(() => render(app.getState()));
|
|
50
|
+
* app.setContent(content);
|
|
51
|
+
* app.setAgent(agent);
|
|
52
|
+
* app.setMessageId(message.id);
|
|
53
|
+
* app.setContainer(element); // on mount
|
|
54
|
+
* app.destroy(); // on unmount
|
|
55
|
+
* ```
|
|
56
|
+
*/
|
|
57
|
+
var McpAppHost = class {
|
|
58
|
+
#options;
|
|
59
|
+
#listeners = /* @__PURE__ */ new Set();
|
|
60
|
+
#container = null;
|
|
61
|
+
#content;
|
|
62
|
+
#agent;
|
|
63
|
+
#messageId;
|
|
64
|
+
#bindKey = "";
|
|
65
|
+
#iframe = null;
|
|
66
|
+
#session = null;
|
|
67
|
+
/** Bumped on every bind and on destroy; stale async work checks it. */
|
|
68
|
+
#generation = 0;
|
|
69
|
+
#state = INITIAL_STATE;
|
|
70
|
+
constructor(options) {
|
|
71
|
+
this.getState = () => this.#state;
|
|
72
|
+
this.subscribe = (listener) => {
|
|
73
|
+
this.#listeners.add(listener);
|
|
74
|
+
return () => {
|
|
75
|
+
this.#listeners.delete(listener);
|
|
76
|
+
};
|
|
77
|
+
};
|
|
78
|
+
this.#options = options;
|
|
79
|
+
}
|
|
80
|
+
/** Sets the element the iframe goes into. `null` removes it. */
|
|
81
|
+
setContainer(container) {
|
|
82
|
+
this.#container = container;
|
|
83
|
+
this.#rebindIfNeeded();
|
|
84
|
+
}
|
|
85
|
+
/** Sets the latest activity content. */
|
|
86
|
+
setContent(content) {
|
|
87
|
+
this.#content = content;
|
|
88
|
+
if (!this.#rebindIfNeeded()) this.#session?.syncContent(content);
|
|
89
|
+
}
|
|
90
|
+
/** Sets the agent the widget's requests go through. */
|
|
91
|
+
setAgent(agent) {
|
|
92
|
+
this.#agent = agent;
|
|
93
|
+
this.#rebindIfNeeded();
|
|
94
|
+
}
|
|
95
|
+
/** Sets the id of the activity message, so the session follows the store. */
|
|
96
|
+
setMessageId(messageId) {
|
|
97
|
+
this.#messageId = messageId;
|
|
98
|
+
this.#rebindIfNeeded();
|
|
99
|
+
}
|
|
100
|
+
/** Tears the session down and removes the iframe. A later setter binds again. */
|
|
101
|
+
destroy() {
|
|
102
|
+
this.#unbind();
|
|
103
|
+
this.#bindKey = "";
|
|
104
|
+
}
|
|
105
|
+
#rebindIfNeeded() {
|
|
106
|
+
const key = JSON.stringify([
|
|
107
|
+
identityOf(this.#content),
|
|
108
|
+
this.#messageId ?? null,
|
|
109
|
+
this.#container !== null,
|
|
110
|
+
this.#agent !== void 0
|
|
111
|
+
]);
|
|
112
|
+
const agentChanged = this.#session !== null && this.#boundAgent !== this.#agent;
|
|
113
|
+
const containerChanged = this.#boundContainer !== this.#container;
|
|
114
|
+
if (key === this.#bindKey && !agentChanged && !containerChanged) return false;
|
|
115
|
+
this.#bindKey = key;
|
|
116
|
+
this.#bind();
|
|
117
|
+
return true;
|
|
118
|
+
}
|
|
119
|
+
#boundAgent;
|
|
120
|
+
#boundContainer = null;
|
|
121
|
+
#bind() {
|
|
122
|
+
this.#unbind();
|
|
123
|
+
const container = this.#container;
|
|
124
|
+
const content = this.#content;
|
|
125
|
+
const agent = this.#agent;
|
|
126
|
+
this.#boundAgent = agent;
|
|
127
|
+
this.#boundContainer = container;
|
|
128
|
+
if (!content || !container) return;
|
|
129
|
+
if (!agent) {
|
|
130
|
+
this.#setState({
|
|
131
|
+
...INITIAL_STATE,
|
|
132
|
+
loading: false,
|
|
133
|
+
error: MCP_APPS_NO_AGENT_MESSAGE
|
|
134
|
+
});
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
const generation = this.#generation;
|
|
138
|
+
const isCurrent = () => generation === this.#generation;
|
|
139
|
+
this.#setState(INITIAL_STATE);
|
|
140
|
+
const iframe = document.createElement("iframe");
|
|
141
|
+
for (const [name, value] of Object.entries(this.#options.iframeAttributes ?? {})) iframe.setAttribute(name, value);
|
|
142
|
+
iframe.style.width = "100%";
|
|
143
|
+
iframe.style.height = `${String(INITIAL_HEIGHT_PX)}px`;
|
|
144
|
+
iframe.style.border = "none";
|
|
145
|
+
iframe.style.backgroundColor = "transparent";
|
|
146
|
+
iframe.style.display = "block";
|
|
147
|
+
container.appendChild(iframe);
|
|
148
|
+
this.#iframe = iframe;
|
|
149
|
+
const scoped = this.#options.scopeToWidget === true;
|
|
150
|
+
const fail = (err) => {
|
|
151
|
+
if (!isCurrent()) return;
|
|
152
|
+
this.#setState({
|
|
153
|
+
...this.#state,
|
|
154
|
+
loading: false,
|
|
155
|
+
error: err.message
|
|
156
|
+
});
|
|
157
|
+
if (scoped) {
|
|
158
|
+
this.#session?.teardown();
|
|
159
|
+
this.#session = null;
|
|
160
|
+
iframe.removeAttribute("srcdoc");
|
|
161
|
+
iframe.removeAttribute("data-mcp-app-initialized");
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
loadMcpAppsRenderer(this.#options.importRenderer).then((mod) => {
|
|
165
|
+
if (!isCurrent()) return;
|
|
166
|
+
const session = mod.bindMcpApp({
|
|
167
|
+
iframe,
|
|
168
|
+
getContent: () => this.#content ?? content,
|
|
169
|
+
getAgent: () => this.#agent,
|
|
170
|
+
host: this.#options.host,
|
|
171
|
+
messageId: this.#messageId,
|
|
172
|
+
options: this.#options.sessionOptions,
|
|
173
|
+
cancelFollowUpsOnTeardown: scoped,
|
|
174
|
+
requireExactResourceUri: scoped,
|
|
175
|
+
cancelRunningWaitOnTeardown: scoped,
|
|
176
|
+
hooks: {
|
|
177
|
+
onResource: (resource) => {
|
|
178
|
+
if (!isCurrent()) return;
|
|
179
|
+
this.#setState({
|
|
180
|
+
...this.#state,
|
|
181
|
+
loading: false,
|
|
182
|
+
prefersBorder: resource._meta?.ui?.prefersBorder === true
|
|
183
|
+
});
|
|
184
|
+
},
|
|
185
|
+
onInitialized: () => {
|
|
186
|
+
if (isCurrent()) iframe.setAttribute("data-mcp-app-initialized", "true");
|
|
187
|
+
},
|
|
188
|
+
onSizeChanged: (size) => {
|
|
189
|
+
if (isCurrent()) this.#applySize(iframe, size);
|
|
190
|
+
},
|
|
191
|
+
onContentError: (err) => {
|
|
192
|
+
if (!isCurrent()) return;
|
|
193
|
+
this.#setState({
|
|
194
|
+
...this.#state,
|
|
195
|
+
contentError: err?.message ?? null
|
|
196
|
+
});
|
|
197
|
+
},
|
|
198
|
+
onError: fail,
|
|
199
|
+
...scoped ? { onFollowUpError: fail } : {}
|
|
200
|
+
}
|
|
201
|
+
});
|
|
202
|
+
this.#session = session;
|
|
203
|
+
session.syncContent(this.#content ?? content);
|
|
204
|
+
}).catch((err) => {
|
|
205
|
+
console.error("[MCPAppsRenderer] Setup error:", err);
|
|
206
|
+
fail(err instanceof Error ? err : new Error(String(err)));
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
#applySize(iframe, size) {
|
|
210
|
+
const next = {};
|
|
211
|
+
if (typeof size.width === "number" && Number.isFinite(size.width)) {
|
|
212
|
+
next.width = size.width;
|
|
213
|
+
iframe.style.minWidth = `min(${String(size.width)}px, 100%)`;
|
|
214
|
+
iframe.style.width = "100%";
|
|
215
|
+
}
|
|
216
|
+
const height = size.height;
|
|
217
|
+
if (typeof height === "number" && Number.isFinite(height) && height > 0) {
|
|
218
|
+
next.height = Math.ceil(Math.min(height, MCP_APP_MAX_HEIGHT));
|
|
219
|
+
iframe.style.height = `${String(next.height)}px`;
|
|
220
|
+
}
|
|
221
|
+
this.#setState({
|
|
222
|
+
...this.#state,
|
|
223
|
+
size: next
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
#unbind() {
|
|
227
|
+
this.#generation += 1;
|
|
228
|
+
this.#session?.teardown();
|
|
229
|
+
this.#session = null;
|
|
230
|
+
this.#iframe?.remove();
|
|
231
|
+
this.#iframe = null;
|
|
232
|
+
}
|
|
233
|
+
#setState(state) {
|
|
234
|
+
this.#state = state;
|
|
235
|
+
for (const listener of this.#listeners) listener();
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
//#endregion
|
|
240
|
+
export { MCP_APPS_NO_AGENT_MESSAGE, MCP_APPS_RENDERER_MISSING_MESSAGE, MCP_APP_MAX_HEIGHT, McpAppHost, loadMcpAppsRenderer };
|
|
241
|
+
//# sourceMappingURL=host.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"host.mjs","names":["#options","#listeners","#state","#container","#rebindIfNeeded","#content","#session","#agent","#messageId","#unbind","#bindKey","#boundAgent","#boundContainer","#bind","#setState","#generation","#iframe","#applySize"],"sources":["../src/host.ts"],"sourcesContent":["// The framework-neutral host shell around `bindMcpApp`: the iframe, its size,\n// and the loading / error / content-error state every frontend renders. It is\n// bridge-free (the bridge loads lazily through `loadMcpAppsRenderer`), so\n// frontends can import it statically from the `/activity` entry.\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport type { MCPAppsActivityContent } from \"./content-schema\";\nimport type { ɵMcpFollowUpHost } from \"./follow-up\";\nimport type {\n BindMcpAppOptions,\n FetchedResource,\n McpAppSession,\n McpAppSessionOptions,\n} from \"./session\";\n\n/** The part of the bridge module the host uses, loaded on demand. */\nexport interface McpAppsRendererModule {\n bindMcpApp(options: BindMcpAppOptions): McpAppSession;\n}\n\n/** Message shown when the bridge package cannot be loaded. */\nexport const MCP_APPS_RENDERER_MISSING_MESSAGE =\n \"MCP Apps require '@copilotkit/mcp-apps-renderer' and its \" +\n \"'@modelcontextprotocol/ext-apps' dependency. Reinstall your \" +\n \"dependencies if this package is missing.\";\n\n/** Error text when an MCP App renders without an agent to fetch it through. */\nexport const MCP_APPS_NO_AGENT_MESSAGE = \"No agent available to fetch resource\";\n\n/** Tallest an MCP App iframe may grow, in pixels. */\nexport const MCP_APP_MAX_HEIGHT = 5000;\n\n/** The height the iframe starts at before the widget reports its size. */\nconst INITIAL_HEIGHT_PX = 100;\n\n/** Imports the bridge module; frontends pass `() => import(\"@copilotkit/mcp-apps-renderer\")`. */\nexport type McpAppsRendererImporter = () => Promise<McpAppsRendererModule>;\n\n/**\n * Loads the bridge (`bindMcpApp`) lazily. The bridge pulls the MCP SDK and\n * its zod schemas (~40-50 kB gzipped), so an app only pays for it when an MCP\n * App renders. The `import()` itself stays in the frontend, where its bundler\n * can split it out. A failed load rethrows with what to install, since a raw\n * module-resolution error does not say.\n *\n * @param importRenderer - `() => import(\"@copilotkit/mcp-apps-renderer\")`.\n */\nexport function loadMcpAppsRenderer(importRenderer: McpAppsRendererImporter) {\n return importRenderer().catch((importErr: unknown) => {\n throw new Error(MCP_APPS_RENDERER_MISSING_MESSAGE, { cause: importErr });\n });\n}\n\n/** What a frontend renders around the MCP App iframe. */\nexport interface McpAppHostState {\n loading: boolean;\n /** Fatal setup failure; shown until the host binds again. */\n error: string | null;\n /** Recoverable: the latest content was rejected and not forwarded. */\n contentError: string | null;\n /** The size the widget reported. */\n size: { width?: number; height?: number };\n /** The resource asked the host for a border and background. */\n prefersBorder: boolean;\n}\n\nexport interface McpAppHostOptions {\n /** The CopilotKit core, for `ui/message` follow-up runs. */\n host: ɵMcpFollowUpHost;\n /** Session options (host info, timeouts, `allowSameOriginFallback`). */\n sessionOptions?: McpAppSessionOptions;\n /**\n * Scope the session to the widget (Angular's contract): teardown cancels\n * its queued follow-up and releases running waits, the fetched resource URI\n * must match exactly, and a failed follow-up or setup error tears the\n * session down, blanks the iframe and shows the error.\n */\n scopeToWidget?: boolean;\n /** Attributes set on the iframe, such as a `data-testid` or `title`. */\n iframeAttributes?: Record<string, string>;\n /** `() => import(\"@copilotkit/mcp-apps-renderer\")`; see {@link loadMcpAppsRenderer}. */\n importRenderer: McpAppsRendererImporter;\n}\n\nfunction identityOf(content: MCPAppsActivityContent | undefined) {\n if (!content) return \"\";\n return JSON.stringify([\n content.resourceUri,\n content.serverHash,\n content.serverId,\n ]);\n}\n\nconst INITIAL_STATE: McpAppHostState = {\n loading: true,\n error: null,\n contentError: null,\n size: {},\n prefersBorder: false,\n};\n\n/**\n * Hosts one MCP App: creates the sandbox iframe in a container, binds the\n * MCP session to it, sizes it as the widget reports, and keeps the state a\n * frontend renders. It binds again (new iframe, new session) only when the\n * container, agent, message id or widget identity (resource URI, server)\n * changes; new tool input or results feed the existing session.\n *\n * @example\n * ```ts\n * const app = new ɵMcpAppHost({ host: core });\n * app.subscribe(() => render(app.getState()));\n * app.setContent(content);\n * app.setAgent(agent);\n * app.setMessageId(message.id);\n * app.setContainer(element); // on mount\n * app.destroy(); // on unmount\n * ```\n */\nexport class McpAppHost {\n readonly #options: McpAppHostOptions;\n readonly #listeners = new Set<() => void>();\n #container: HTMLElement | null = null;\n #content: MCPAppsActivityContent | undefined;\n #agent: AbstractAgent | undefined;\n #messageId: string | undefined;\n #bindKey = \"\";\n #iframe: HTMLIFrameElement | null = null;\n #session: McpAppSession | null = null;\n /** Bumped on every bind and on destroy; stale async work checks it. */\n #generation = 0;\n #state: McpAppHostState = INITIAL_STATE;\n\n constructor(options: McpAppHostOptions) {\n this.#options = options;\n }\n\n /** The current state. The same object until something changes. */\n getState = () => this.#state;\n\n /** Calls `listener` when the state changes. Returns the unsubscribe function. */\n subscribe = (listener: () => void) => {\n this.#listeners.add(listener);\n return () => {\n this.#listeners.delete(listener);\n };\n };\n\n /** Sets the element the iframe goes into. `null` removes it. */\n setContainer(container: HTMLElement | null) {\n this.#container = container;\n this.#rebindIfNeeded();\n }\n\n /** Sets the latest activity content. */\n setContent(content: MCPAppsActivityContent) {\n this.#content = content;\n if (!this.#rebindIfNeeded()) this.#session?.syncContent(content);\n }\n\n /** Sets the agent the widget's requests go through. */\n setAgent(agent: AbstractAgent | undefined) {\n this.#agent = agent;\n this.#rebindIfNeeded();\n }\n\n /** Sets the id of the activity message, so the session follows the store. */\n setMessageId(messageId: string | undefined) {\n this.#messageId = messageId;\n this.#rebindIfNeeded();\n }\n\n /** Tears the session down and removes the iframe. A later setter binds again. */\n destroy() {\n this.#unbind();\n this.#bindKey = \"\";\n }\n\n #rebindIfNeeded() {\n const key = JSON.stringify([\n identityOf(this.#content),\n this.#messageId ?? null,\n this.#container !== null,\n this.#agent !== undefined,\n ]);\n const agentChanged =\n this.#session !== null && this.#boundAgent !== this.#agent;\n const containerChanged = this.#boundContainer !== this.#container;\n if (key === this.#bindKey && !agentChanged && !containerChanged) {\n return false;\n }\n this.#bindKey = key;\n this.#bind();\n return true;\n }\n\n #boundAgent: AbstractAgent | undefined;\n #boundContainer: HTMLElement | null = null;\n\n #bind() {\n this.#unbind();\n const container = this.#container;\n const content = this.#content;\n const agent = this.#agent;\n this.#boundAgent = agent;\n this.#boundContainer = container;\n if (!content || !container) return;\n if (!agent) {\n this.#setState({\n ...INITIAL_STATE,\n loading: false,\n error: MCP_APPS_NO_AGENT_MESSAGE,\n });\n return;\n }\n\n const generation = this.#generation;\n const isCurrent = () => generation === this.#generation;\n this.#setState(INITIAL_STATE);\n\n const iframe = document.createElement(\"iframe\");\n for (const [name, value] of Object.entries(\n this.#options.iframeAttributes ?? {},\n )) {\n iframe.setAttribute(name, value);\n }\n iframe.style.width = \"100%\";\n iframe.style.height = `${String(INITIAL_HEIGHT_PX)}px`;\n iframe.style.border = \"none\";\n iframe.style.backgroundColor = \"transparent\";\n iframe.style.display = \"block\";\n container.appendChild(iframe);\n this.#iframe = iframe;\n\n const scoped = this.#options.scopeToWidget === true;\n const fail = (err: Error) => {\n if (!isCurrent()) return;\n this.#setState({ ...this.#state, loading: false, error: err.message });\n if (scoped) {\n // Blank the widget, so a failed app does not stay interactive.\n this.#session?.teardown();\n this.#session = null;\n iframe.removeAttribute(\"srcdoc\");\n iframe.removeAttribute(\"data-mcp-app-initialized\");\n }\n };\n loadMcpAppsRenderer(this.#options.importRenderer)\n .then((mod) => {\n if (!isCurrent()) return;\n const session = mod.bindMcpApp({\n iframe,\n getContent: () => this.#content ?? content,\n getAgent: () => this.#agent,\n host: this.#options.host,\n messageId: this.#messageId,\n options: this.#options.sessionOptions,\n cancelFollowUpsOnTeardown: scoped,\n requireExactResourceUri: scoped,\n cancelRunningWaitOnTeardown: scoped,\n hooks: {\n onResource: (resource: FetchedResource) => {\n if (!isCurrent()) return;\n this.#setState({\n ...this.#state,\n loading: false,\n prefersBorder: resource._meta?.ui?.prefersBorder === true,\n });\n },\n onInitialized: () => {\n if (isCurrent()) {\n iframe.setAttribute(\"data-mcp-app-initialized\", \"true\");\n }\n },\n onSizeChanged: (size) => {\n if (isCurrent()) this.#applySize(iframe, size);\n },\n onContentError: (err) => {\n if (!isCurrent()) return;\n this.#setState({\n ...this.#state,\n contentError: err?.message ?? null,\n });\n },\n onError: fail,\n ...(scoped ? { onFollowUpError: fail } : {}),\n },\n });\n this.#session = session;\n // Seed the content: an activity rendered from an external message\n // list is not in the agent's store, so nothing else would send it.\n session.syncContent(this.#content ?? content);\n })\n .catch((err: unknown) => {\n console.error(\"[MCPAppsRenderer] Setup error:\", err);\n fail(err instanceof Error ? err : new Error(String(err)));\n });\n }\n\n #applySize(\n iframe: HTMLIFrameElement,\n size: { width?: number; height?: number },\n ) {\n const next: McpAppHostState[\"size\"] = {};\n if (typeof size.width === \"number\" && Number.isFinite(size.width)) {\n next.width = size.width;\n // Allow expansion but cap at the container width.\n iframe.style.minWidth = `min(${String(size.width)}px, 100%)`;\n iframe.style.width = \"100%\";\n }\n const height = size.height;\n if (typeof height === \"number\" && Number.isFinite(height) && height > 0) {\n next.height = Math.ceil(Math.min(height, MCP_APP_MAX_HEIGHT));\n iframe.style.height = `${String(next.height)}px`;\n }\n this.#setState({ ...this.#state, size: next });\n }\n\n #unbind() {\n this.#generation += 1;\n this.#session?.teardown();\n this.#session = null;\n this.#iframe?.remove();\n this.#iframe = null;\n }\n\n #setState(state: McpAppHostState) {\n this.#state = state;\n for (const listener of this.#listeners) listener();\n }\n}\n"],"mappings":";;AAoBA,MAAa,oCACX;;AAKF,MAAa,4BAA4B;;AAGzC,MAAa,qBAAqB;;AAGlC,MAAM,oBAAoB;;;;;;;;;;AAc1B,SAAgB,oBAAoB,gBAAyC;AAC3E,QAAO,gBAAgB,CAAC,OAAO,cAAuB;AACpD,QAAM,IAAI,MAAM,mCAAmC,EAAE,OAAO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O,MAAM,SAAS,GAAG,OAAO,KAAK,OAAO,CAAC;;AAE/C,QAAKS,SAAU;GAAE,GAAG,MAAKZ;GAAQ,MAAM;GAAM,CAAC;;CAGhD,UAAU;AACR,QAAKa,cAAe;AACpB,QAAKT,SAAU,UAAU;AACzB,QAAKA,UAAW;AAChB,QAAKU,QAAS,QAAQ;AACtB,QAAKA,SAAU;;CAGjB,UAAU,OAAwB;AAChC,QAAKd,QAAS;AACd,OAAK,MAAM,YAAY,MAAKD,UAAY,WAAU"}
|
|
@@ -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,KAAsB;;;;;;CAM/C,MAAM,QACJ,OACA,SACA,SACyB;EAGzB,MAAM,MAAM,OAAO,MAAM;AAEzB,S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G5D,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,MAAM,MAAM,OAAO,MAAM;AAEzB,SAAO,IAAI,SAAS,SAAS,WAAW;GACtC,IAAI,QAAQ,KAAK,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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"}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { MCPAppsActivityContent } from "./content-schema.cjs";
|
|
2
|
+
import { ɵMcpFollowUpHost } from "./follow-up.cjs";
|
|
3
|
+
import { AbstractAgent } from "@ag-ui/client";
|
|
4
|
+
import { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
|
|
5
|
+
|
|
6
|
+
//#region src/session.d.ts
|
|
7
|
+
/** A resource fetched from the MCP server via the agent proxy. */
|
|
8
|
+
interface FetchedResource {
|
|
9
|
+
uri: string;
|
|
10
|
+
mimeType?: string;
|
|
11
|
+
text?: string;
|
|
12
|
+
blob?: string;
|
|
13
|
+
_meta?: {
|
|
14
|
+
ui?: {
|
|
15
|
+
prefersBorder?: boolean;
|
|
16
|
+
csp?: {
|
|
17
|
+
connectDomains?: string[];
|
|
18
|
+
resourceDomains?: string[];
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
/** Reactive callbacks the framework adapter wires to its own state. */
|
|
24
|
+
interface McpAppSessionHooks {
|
|
25
|
+
/** The widget reported a new content size (ui/notifications/size-changed). */
|
|
26
|
+
onSizeChanged?(size: {
|
|
27
|
+
width?: number;
|
|
28
|
+
height?: number;
|
|
29
|
+
}): void;
|
|
30
|
+
/** The widget finished initializing (safe to push tool input/result). */
|
|
31
|
+
onInitialized?(): void;
|
|
32
|
+
/** The sandbox proxy is ready and its resource has been sent. */
|
|
33
|
+
onSandboxReady?(): void;
|
|
34
|
+
/** The fetched resource metadata (e.g. prefersBorder) is available. */
|
|
35
|
+
onResource?(resource: FetchedResource): void;
|
|
36
|
+
/**
|
|
37
|
+
* FATAL setup failure (resource fetch, bridge connect, sandbox timeout).
|
|
38
|
+
* The session cannot serve this widget; the host keeps showing the error
|
|
39
|
+
* until it re-binds.
|
|
40
|
+
*/
|
|
41
|
+
onError?(err: Error): void;
|
|
42
|
+
/** A queued ui/message follow-up failed. */
|
|
43
|
+
onFollowUpError?(err: Error): void;
|
|
44
|
+
/**
|
|
45
|
+
* RECOVERABLE content problem: an activity update was rejected by the content
|
|
46
|
+
* schema and therefore not forwarded to the widget. Reported the same way
|
|
47
|
+
* whether the content came from the agent's store or from an adapter prop.
|
|
48
|
+
*
|
|
49
|
+
* Called with the `Error` when content is rejected, and with `null` as soon as
|
|
50
|
+
* valid content arrives again - the widget resumes, so the host must clear the
|
|
51
|
+
* message rather than leave a stale error on screen.
|
|
52
|
+
*/
|
|
53
|
+
onContentError?(err: Error | null): void;
|
|
54
|
+
}
|
|
55
|
+
interface BindMcpAppOptions {
|
|
56
|
+
/**
|
|
57
|
+
* The sandbox iframe. The adapter creates and OWNS this element (mounts it in
|
|
58
|
+
* its render model, sizes it, removes it on unmount). The session only
|
|
59
|
+
* configures the sandbox contract (sandbox attr, testid, srcdoc) and talks to
|
|
60
|
+
* it through the bridge - it never creates, moves, or removes the iframe.
|
|
61
|
+
*/
|
|
62
|
+
iframe: HTMLIFrameElement;
|
|
63
|
+
/** Returns the current activity content (resourceUri, serverHash, tool input/result). */
|
|
64
|
+
getContent: () => MCPAppsActivityContent;
|
|
65
|
+
/** Returns the current agent (may change across renders). */
|
|
66
|
+
getAgent: () => AbstractAgent | undefined;
|
|
67
|
+
/** CopilotKit host, for ui/message follow-up runs (issue #5819). */
|
|
68
|
+
host: ɵMcpFollowUpHost;
|
|
69
|
+
/**
|
|
70
|
+
* The id of the activity message this session renders. When provided, the
|
|
71
|
+
* session subscribes to the agent's message store, finds this activity, and
|
|
72
|
+
* pushes its tool input/result to the widget itself (self-driving), so the
|
|
73
|
+
* adapter does not re-implement the agent-driven forwarding loop.
|
|
74
|
+
*
|
|
75
|
+
* The store is authoritative only for activities that live in it. When a host
|
|
76
|
+
* renders an activity from an EXTERNAL message list (e.g. CopilotChatView's
|
|
77
|
+
* `messages` prop), that activity is not in `agent.messages`; the adapter must
|
|
78
|
+
* then call `syncContent` on content change so the widget still receives its
|
|
79
|
+
* tool input/result. Both paths share one dedup, so they never double-send.
|
|
80
|
+
*/
|
|
81
|
+
messageId?: string;
|
|
82
|
+
hooks?: McpAppSessionHooks;
|
|
83
|
+
/**
|
|
84
|
+
* Host identity, capabilities and UI context announced during the MCP Apps
|
|
85
|
+
* initialization handshake, plus the two timeouts. Every field is optional and
|
|
86
|
+
* merged over {@link MCP_APPS_SESSION_DEFAULTS}, so a frontend only overrides
|
|
87
|
+
* what it exposes to its users.
|
|
88
|
+
*/
|
|
89
|
+
options?: McpAppSessionOptions;
|
|
90
|
+
/**
|
|
91
|
+
* Decides whether `ui/open-link` may open a URL, and with what final value.
|
|
92
|
+
*
|
|
93
|
+
* Defaults to {@link denyDangerousSchemes}, the single policy every CopilotKit
|
|
94
|
+
* frontend uses - no adapter overrides it, so a widget behaves the same in
|
|
95
|
+
* React, Vue and Angular. This hook exists for a host with a genuinely
|
|
96
|
+
* different security contract; prefer changing the shared policy over setting
|
|
97
|
+
* it, otherwise widget behaviour becomes framework-dependent again.
|
|
98
|
+
*/
|
|
99
|
+
openLinkPolicy?: McpAppOpenLinkPolicy;
|
|
100
|
+
/**
|
|
101
|
+
* Whether `teardown` also cancels a queued `ui/message` follow-up run.
|
|
102
|
+
*
|
|
103
|
+
* Defaults to `false`: the follow-up carries the user's message onwards, so it
|
|
104
|
+
* outlives the widget that sent it. Hosts that scope follow-ups to the widget
|
|
105
|
+
* (the Angular contract) can opt in.
|
|
106
|
+
*/
|
|
107
|
+
cancelFollowUpsOnTeardown?: boolean;
|
|
108
|
+
/** Require the fetched resource URI to match exactly (Angular compatibility). */
|
|
109
|
+
requireExactResourceUri?: boolean;
|
|
110
|
+
/** Release already-started proxy/follow-up waits on teardown, without aborting the underlying run. */
|
|
111
|
+
cancelRunningWaitOnTeardown?: boolean;
|
|
112
|
+
}
|
|
113
|
+
/** Host identity announced during the initialization handshake. */
|
|
114
|
+
interface McpAppHostInfo {
|
|
115
|
+
name: string;
|
|
116
|
+
version: string;
|
|
117
|
+
}
|
|
118
|
+
interface McpAppSessionOptions {
|
|
119
|
+
/** Maximum time a queued request waits for a busy agent. Default 30s. */
|
|
120
|
+
idleTimeoutMs?: number;
|
|
121
|
+
/**
|
|
122
|
+
* Maximum time to wait for the sandbox proxy handshake
|
|
123
|
+
* (`ui/notifications/sandbox-proxy-ready`). Default 30s.
|
|
124
|
+
*
|
|
125
|
+
* This measures the SANDBOX step, not `ui/notifications/initialized`: a widget
|
|
126
|
+
* that loads its proxy but never reports initialized is a different failure.
|
|
127
|
+
*/
|
|
128
|
+
initializationTimeoutMs?: number;
|
|
129
|
+
/** Host identity announced during the initialization handshake. */
|
|
130
|
+
hostInfo?: McpAppHostInfo;
|
|
131
|
+
/** Protocol capabilities announced to embedded MCP Apps. */
|
|
132
|
+
hostCapabilities?: Record<string, unknown>;
|
|
133
|
+
/** Non-secret UI context announced to embedded MCP Apps. */
|
|
134
|
+
hostContext?: Record<string, unknown>;
|
|
135
|
+
/**
|
|
136
|
+
* Restore `allow-same-origin` on the sandbox frames. Default `false`.
|
|
137
|
+
*
|
|
138
|
+
* **Unsafe.** The sandbox proxy is loaded via `srcdoc`, so with this flag the
|
|
139
|
+
* widget runs with the host page's origin: it can read the host's cookies,
|
|
140
|
+
* storage and DOM, and call the host's APIs as the signed-in user. Only set
|
|
141
|
+
* it for widgets you wrote and trust that genuinely need `localStorage`,
|
|
142
|
+
* `IndexedDB` or cookies. By default widgets get an opaque origin.
|
|
143
|
+
*/
|
|
144
|
+
allowSameOriginFallback?: boolean;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Returns the URL to open, or `undefined` to refuse. Receiving the raw string
|
|
148
|
+
* (not a parsed URL) lets a policy resolve relative links itself.
|
|
149
|
+
*/
|
|
150
|
+
type McpAppOpenLinkPolicy = (url: string) => string | undefined;
|
|
151
|
+
interface McpAppSession {
|
|
152
|
+
/** Forward the tool call input to the widget (host -> app). Buffered until ready. */
|
|
153
|
+
sendToolInput(args: Record<string, unknown>): void;
|
|
154
|
+
/** Forward the tool result to the widget (host -> app). Buffered until ready. */
|
|
155
|
+
sendToolResult(result: CallToolResult): void;
|
|
156
|
+
/**
|
|
157
|
+
* Forward the tool input/result carried by `content` to the widget, deduped so
|
|
158
|
+
* an unchanged value is not re-sent. The prop-driven counterpart to the agent
|
|
159
|
+
* subscription: the adapter calls this on content change so activities rendered
|
|
160
|
+
* from an external message list (absent from `agent.messages`) still reach the
|
|
161
|
+
* widget. No-op for values already sent (shared dedup with the subscription).
|
|
162
|
+
*
|
|
163
|
+
* Content is validated here exactly as it is on the store path: a rejected
|
|
164
|
+
* value is not forwarded and surfaces through `onContentError`.
|
|
165
|
+
*/
|
|
166
|
+
syncContent(content: MCPAppsActivityContent): void;
|
|
167
|
+
/** Disconnect the bridge and release listeners. Does NOT remove the iframe. */
|
|
168
|
+
teardown(): void;
|
|
169
|
+
}
|
|
170
|
+
//#endregion
|
|
171
|
+
export { BindMcpAppOptions, McpAppSession, McpAppSessionOptions };
|
|
172
|
+
//# sourceMappingURL=session.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session.d.cts","names":[],"sources":["../src/session.ts"],"mappings":";;;;;;;UAwIiB,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;EAcD;EAZd,aAAA,EAAe,IAAA;IAAQ,KAAA;IAAgB,MAAA;EAAA;EAwBvC;EAtBA,aAAA;EAsBgB;EApBhB,cAAA;EAoBiC;EAlBjC,UAAA,EAAY,QAAA,EAAU,eAAA;EAqBU;;;;;EAfhC,OAAA,EAAS,GAAA,EAAK,KAAA;EA0CN;EAxCR,eAAA,EAAiB,GAAA,EAAK,KAAA;EAyDL;;;;;;;;;EA/CjB,cAAA,EAAgB,GAAA,EAAK,KAAA;AAAA;AAAA,UAGN,iBAAA;EA2Bf;;;;;;EApBA,MAAA,EAAQ,iBAAA;EA+CR;EA7CA,UAAA,QAAkB,sBAAA;EA+CS;EA7C3B,QAAA,QAAgB,aAAA;EAiDD;EA/Cf,IAAA,EAAM,gBAAA;;;;AAoDR;;;;;;;;;EAvCE,SAAA;EACA,KAAA,GAAQ,kBAAA;EAkDG;;;;;;EA3CX,OAAA,GAAU,oBAAA;EAyDa;AAmBzB;;;;;AA8DA;;;EAhIE,cAAA,GAAiB,oBAAA;EAoIM;;;;;;;EA5HvB,yBAAA;EA4HuB;EA1HvB,uBAAA;EAqIA;EAnIA,2BAAA;AAAA;;UAIe,cAAA;EACf,IAAA;EACA,OAAA;AAAA;AAAA,UAGe,oBAAA;;EAEf,aAAA;;;;;;;;EAQA,uBAAA;;EAEA,QAAA,GAAW,cAAA;;EAEX,gBAAA,GAAmB,MAAA;;EAEnB,WAAA,GAAc,MAAA;;;;;;;;;;EAUd,uBAAA;AAAA;;;;;KAmBU,oBAAA,IAAwB,GAAA;AAAA,UA8DnB,aAAA;;EAEf,aAAA,CAAc,IAAA,EAAM,MAAA;;EAEpB,cAAA,CAAe,MAAA,EAAQ,cAAA;;;;;;;;;;;EAWvB,WAAA,CAAY,OAAA,EAAS,sBAAA;;EAErB,QAAA;AAAA"}
|
package/dist/session.d.mts
CHANGED
|
@@ -4,25 +4,6 @@ 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;
|
|
17
|
-
/**
|
|
18
|
-
* The MCP Apps protocol version this host negotiates. Sourced directly from the
|
|
19
|
-
* ext-apps bridge (single source of truth, no hand-maintained literal). It lives
|
|
20
|
-
* here (a bridge-side module) rather than in the bridge-free `./constants` /
|
|
21
|
-
* `./activity` entry so the lightweight activity-registration surface stays free
|
|
22
|
-
* of the ext-apps bundle; consumers that need the version import it from the
|
|
23
|
-
* package root, which already loads the bridge.
|
|
24
|
-
*/
|
|
25
|
-
declare const MCP_APPS_PROTOCOL_VERSION = "2026-01-26";
|
|
26
7
|
/** A resource fetched from the MCP server via the agent proxy. */
|
|
27
8
|
interface FetchedResource {
|
|
28
9
|
uri: string;
|
|
@@ -162,40 +143,11 @@ interface McpAppSessionOptions {
|
|
|
162
143
|
*/
|
|
163
144
|
allowSameOriginFallback?: boolean;
|
|
164
145
|
}
|
|
165
|
-
/** Defaults every frontend inherits unless it overrides them. */
|
|
166
|
-
declare const MCP_APPS_SESSION_DEFAULTS: Readonly<Required<McpAppSessionOptions>>;
|
|
167
146
|
/**
|
|
168
147
|
* Returns the URL to open, or `undefined` to refuse. Receiving the raw string
|
|
169
148
|
* (not a parsed URL) lets a policy resolve relative links itself.
|
|
170
149
|
*/
|
|
171
150
|
type McpAppOpenLinkPolicy = (url: string) => string | undefined;
|
|
172
|
-
/**
|
|
173
|
-
* The MCP Apps link policy, shared by every frontend.
|
|
174
|
-
*
|
|
175
|
-
* Three independent rules, deliberately kept as ONE policy so a widget behaves
|
|
176
|
-
* the same whichever framework hosts it:
|
|
177
|
-
*
|
|
178
|
-
* 1. **Scheme denylist**, not an allowlist. Only the schemes that execute script
|
|
179
|
-
* or render attacker-controlled HTML are refused (`javascript:`, `data:`,
|
|
180
|
-
* `vbscript:`, `blob:`, `file:`). Everything else is allowed, including
|
|
181
|
-
* app-defined deep links (`myapp:`, `whatsapp:`), which hand off to an OS
|
|
182
|
-
* handler rather than executing in the page. An allowlist could never
|
|
183
|
-
* enumerate those, and restricting to http/https would break them.
|
|
184
|
-
* 2. **Embedded credentials refused** (`https://user:pw@host`): a widget must not
|
|
185
|
-
* hand the browser a URL carrying someone's credentials.
|
|
186
|
-
* 3. **Path-relative links resolved** against the host document, so `/docs`,
|
|
187
|
-
* `./x` and `../x` open instead of failing URL parsing. Only those three
|
|
188
|
-
* forms: every string is technically a valid relative reference, so anything
|
|
189
|
-
* else stays refused rather than becoming a navigation on the host origin.
|
|
190
|
-
* This does mean a widget can reach a path of the HOST application - the same
|
|
191
|
-
* reach a normal anchor in the page would have.
|
|
192
|
-
*
|
|
193
|
-
* Rules 2 and 3 come from the Angular host, which enforced them before it moved
|
|
194
|
-
* onto this session; rule 1 is the CopilotKit product decision (it matches the
|
|
195
|
-
* Anthropic Software Directory policy: https origins plus owned custom URI
|
|
196
|
-
* schemes). Merging them means no frontend overrides anything.
|
|
197
|
-
*/
|
|
198
|
-
declare const denyDangerousSchemes: McpAppOpenLinkPolicy;
|
|
199
151
|
interface McpAppSession {
|
|
200
152
|
/** Forward the tool call input to the widget (host -> app). Buffered until ready. */
|
|
201
153
|
sendToolInput(args: Record<string, unknown>): void;
|
|
@@ -215,15 +167,6 @@ interface McpAppSession {
|
|
|
215
167
|
/** Disconnect the bridge and release listeners. Does NOT remove the iframe. */
|
|
216
168
|
teardown(): void;
|
|
217
169
|
}
|
|
218
|
-
/**
|
|
219
|
-
* Bind an MCP App to a host-provided sandbox iframe: fetch the widget resource
|
|
220
|
-
* through the agent, connect the ext-apps `AppBridge` over a PostMessage
|
|
221
|
-
* transport, and wire the app<->host protocol (ui/message, ui/open-link,
|
|
222
|
-
* tools/call + resources/read proxy, size, host context). Framework-agnostic:
|
|
223
|
-
* the React/Vue/Angular renderers create the iframe and wire reactive state via
|
|
224
|
-
* `hooks`, but all protocol logic lives here.
|
|
225
|
-
*/
|
|
226
|
-
declare function bindMcpApp(opts: BindMcpAppOptions): McpAppSession;
|
|
227
170
|
//#endregion
|
|
228
|
-
export { BindMcpAppOptions,
|
|
171
|
+
export { BindMcpAppOptions, McpAppSession, McpAppSessionOptions };
|
|
229
172
|
//# sourceMappingURL=session.d.mts.map
|
package/dist/session.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.d.mts","names":[],"sources":["../src/session.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"session.d.mts","names":[],"sources":["../src/session.ts"],"mappings":";;;;;;;UAwIiB,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;EAcD;EAZd,aAAA,EAAe,IAAA;IAAQ,KAAA;IAAgB,MAAA;EAAA;EAwBvC;EAtBA,aAAA;EAsBgB;EApBhB,cAAA;EAoBiC;EAlBjC,UAAA,EAAY,QAAA,EAAU,eAAA;EAqBU;;;;;EAfhC,OAAA,EAAS,GAAA,EAAK,KAAA;EA0CN;EAxCR,eAAA,EAAiB,GAAA,EAAK,KAAA;EAyDL;;;;;;;;;EA/CjB,cAAA,EAAgB,GAAA,EAAK,KAAA;AAAA;AAAA,UAGN,iBAAA;EA2Bf;;;;;;EApBA,MAAA,EAAQ,iBAAA;EA+CR;EA7CA,UAAA,QAAkB,sBAAA;EA+CS;EA7C3B,QAAA,QAAgB,aAAA;EAiDD;EA/Cf,IAAA,EAAM,gBAAA;;;;AAoDR;;;;;;;;;EAvCE,SAAA;EACA,KAAA,GAAQ,kBAAA;EAkDG;;;;;;EA3CX,OAAA,GAAU,oBAAA;EAyDa;AAmBzB;;;;;AA8DA;;;EAhIE,cAAA,GAAiB,oBAAA;EAoIM;;;;;;;EA5HvB,yBAAA;EA4HuB;EA1HvB,uBAAA;EAqIA;EAnIA,2BAAA;AAAA;;UAIe,cAAA;EACf,IAAA;EACA,OAAA;AAAA;AAAA,UAGe,oBAAA;;EAEf,aAAA;;;;;;;;EAQA,uBAAA;;EAEA,QAAA,GAAW,cAAA;;EAEX,gBAAA,GAAmB,MAAA;;EAEnB,WAAA,GAAc,MAAA;;;;;;;;;;EAUd,uBAAA;AAAA;;;;;KAmBU,oBAAA,IAAwB,GAAA;AAAA,UA8DnB,aAAA;;EAEf,aAAA,CAAc,IAAA,EAAM,MAAA;;EAEpB,cAAA,CAAe,MAAA,EAAQ,cAAA;;;;;;;;;;;EAWvB,WAAA,CAAY,OAAA,EAAS,sBAAA;;EAErB,QAAA;AAAA"}
|
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 = {
|