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