@copilotkit/mcp-apps-renderer 1.75.0 → 1.75.2
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/session.mjs +1 -1
- package/dist/session.mjs.map +1 -1
- package/package.json +2 -2
package/dist/session.mjs
CHANGED
package/dist/session.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.mjs","names":[],"sources":["../src/session.ts"],"sourcesContent":["import {\n AppBridge,\n LATEST_PROTOCOL_VERSION,\n PostMessageTransport,\n} from \"@modelcontextprotocol/ext-apps/app-bridge\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport type { CallToolResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport { z } from \"zod\";\nimport { randomUUID } from \"@copilotkit/shared\";\nimport { buildSandboxHTML } from \"./sandbox\";\nimport { mcpAppsRequestQueue } from \"./request-queue\";\nimport { ɵrunMcpFollowUp } from \"./follow-up\";\nimport type { ɵMcpFollowUpHost } from \"./follow-up\";\nimport { MCP_OPEN_LINK_BLOCKED_SCHEMES } from \"./constants\";\nimport type { MCPAppsActivityContent } from \"./content-schema\";\n\n/**\n * The MCP Apps protocol version this host negotiates. Sourced directly from the\n * ext-apps bridge (single source of truth, no hand-maintained literal). It lives\n * here (a bridge-side module) rather than in the bridge-free `./constants` /\n * `./activity` entry so the lightweight activity-registration surface stays free\n * of the ext-apps bundle; consumers that need the version import it from the\n * package root, which already loads the bridge.\n */\nexport const MCP_APPS_PROTOCOL_VERSION = LATEST_PROTOCOL_VERSION;\n\n/**\n * Permissive `ui/message` schema. ext-apps restricts the request to\n * `role: \"user\"` with no `followUp`, but CopilotKit intentionally extends\n * `ui/message` with `role` (\"user\" | \"assistant\") and `followUp` (documented\n * behavior with dedicated tests). We register our own handler (instead of the\n * bridge's strict `onmessage`) so those extensions survive.\n *\n * Going forward, widgets SHOULD pass the extensions under\n * `params._meta.copilotkit`; the top-level `role`/`followUp` fields are the\n * legacy channel, kept for backward compatibility and slated for deprecation.\n */\nconst CopilotKitUiMessageSchema = z.object({\n method: z.literal(\"ui/message\"),\n params: z\n .object({\n role: z.string().optional(),\n content: z.array(z.any()).optional(),\n followUp: z.boolean().optional(),\n _meta: z.record(z.string(), z.any()).optional(),\n })\n .passthrough(),\n});\n\n/** A resource fetched from the MCP server via the agent proxy. */\nexport interface FetchedResource {\n uri: string;\n mimeType?: string;\n text?: string;\n blob?: string;\n _meta?: {\n ui?: {\n prefersBorder?: boolean;\n csp?: {\n connectDomains?: string[];\n resourceDomains?: string[];\n };\n };\n };\n}\n\n/** Reactive callbacks the framework adapter wires to its own state. */\nexport interface McpAppSessionHooks {\n /** The widget reported a new content size (ui/notifications/size-changed). */\n onSizeChanged?(size: { width?: number; height?: number }): void;\n /** The widget finished initializing (safe to push tool input/result). */\n onInitialized?(): void;\n /** The fetched resource metadata (e.g. prefersBorder) is available. */\n onResource?(resource: FetchedResource): void;\n /** Setup failed (resource fetch, connect, ...). */\n onError?(err: Error): void;\n}\n\nexport interface BindMcpAppOptions {\n /**\n * The sandbox iframe. The adapter creates and OWNS this element (mounts it in\n * its render model, sizes it, removes it on unmount). The session only\n * configures the sandbox contract (sandbox attr, testid, srcdoc) and talks to\n * it through the bridge - it never creates, moves, or removes the iframe.\n */\n iframe: HTMLIFrameElement;\n /** Returns the current activity content (resourceUri, serverHash, tool input/result). */\n getContent: () => MCPAppsActivityContent;\n /** Returns the current agent (may change across renders). */\n getAgent: () => AbstractAgent | undefined;\n /** CopilotKit host, for ui/message follow-up runs (issue #5819). */\n host: ɵMcpFollowUpHost;\n hooks?: McpAppSessionHooks;\n}\n\nexport interface McpAppSession {\n /** Forward the tool call input to the widget (host -> app). Buffered until ready. */\n sendToolInput(args: Record<string, unknown>): void;\n /** Forward the tool result to the widget (host -> app). Buffered until ready. */\n sendToolResult(result: CallToolResult): void;\n /** Disconnect the bridge and release listeners. Does NOT remove the iframe. */\n teardown(): void;\n}\n\n/**\n * Bind an MCP App to a host-provided sandbox iframe: fetch the widget resource\n * through the agent, connect the ext-apps `AppBridge` over a PostMessage\n * transport, and wire the app<->host protocol (ui/message, ui/open-link,\n * tools/call + resources/read proxy, size, host context). Framework-agnostic:\n * the React/Vue/Angular renderers create the iframe and wire reactive state via\n * `hooks`, but all protocol logic lives here.\n */\nexport function bindMcpApp(opts: BindMcpAppOptions): McpAppSession {\n const { iframe, getContent, getAgent, host, hooks } = opts;\n\n let disposed = false;\n let ready = false;\n let bridge: AppBridge | null = null;\n let pendingToolInput: Record<string, unknown> | undefined;\n let pendingToolResult: CallToolResult | undefined;\n\n /** Flush any buffered tool input/result to the widget once it is initialized. */\n const flushPending = () => {\n if (!ready || !bridge) return;\n if (pendingToolInput !== undefined) {\n void bridge.sendToolInput({ arguments: pendingToolInput });\n pendingToolInput = undefined;\n }\n if (pendingToolResult !== undefined) {\n void bridge.sendToolResult(pendingToolResult);\n pendingToolResult = undefined;\n }\n };\n\n /** Fetch the widget resource (`resources/read`) through the agent proxy queue. */\n const fetchResource = async (): Promise<FetchedResource> => {\n const agent = getAgent();\n if (!agent) {\n throw new Error(\"No agent available to fetch resource\");\n }\n const { resourceUri, serverHash, serverId } = getContent();\n const runResult = await mcpAppsRequestQueue.enqueue(agent, () =>\n agent.runAgent({\n forwardedProps: {\n __proxiedMCPRequest: {\n serverHash,\n serverId,\n method: \"resources/read\",\n params: { uri: resourceUri },\n },\n },\n }),\n );\n const resultData = runResult.result as\n | { contents?: FetchedResource[] }\n | undefined;\n const resource = resultData?.contents?.[0];\n if (!resource) {\n throw new Error(\"No resource content in response\");\n }\n return resource;\n };\n\n /**\n * Fetch the resource, configure + load the sandbox iframe, construct the\n * AppBridge, wire the app->host handlers, and connect the transport.\n */\n const setup = async () => {\n try {\n const resource = await fetchResource();\n if (disposed) return;\n hooks?.onResource?.(resource);\n\n // Configure the sandbox iframe (contract shared across frontends).\n iframe.setAttribute(\n \"sandbox\",\n \"allow-scripts allow-same-origin allow-forms\",\n );\n // Cross-frontend MCP-apps surface contract: every frontend must expose the\n // sandbox iframe under the SAME testid so one shared probe (harness\n // `d5-mcp-apps`) and one shared e2e spec can assert the surface mounted\n // without per-frontend selectors.\n iframe.setAttribute(\"data-testid\", \"mcp-app-iframe\");\n iframe.setAttribute(\"title\", \"Interactive MCP application\");\n\n const cspDomains = resource._meta?.ui?.csp?.resourceDomains;\n iframe.srcdoc = buildSandboxHTML(cspDomains);\n\n const win = iframe.contentWindow;\n if (!win) {\n throw new Error(\"Sandbox iframe has no contentWindow\");\n }\n\n let html: string;\n if (resource.text) {\n html = resource.text;\n } else if (resource.blob) {\n html = atob(resource.blob);\n } else {\n throw new Error(\"Resource has no text or blob content\");\n }\n\n bridge = new AppBridge(\n null,\n { name: \"CopilotKit MCP Apps Host\", version: \"1.0.0\" },\n { openLinks: {}, logging: {}, message: { text: {} } },\n // Seed the host context at construction so it is already in place when\n // the widget's ui/initialize is handled (deterministic, not a race).\n { hostContext: { theme: \"light\", platform: \"web\" } },\n );\n\n // Sandbox handshake: on proxy ready, load the widget HTML into the inner\n // sandboxed iframe.\n bridge.onsandboxready = () => {\n void bridge?.sendSandboxResourceReady({ html });\n };\n\n // --- App -> host requests ---\n // ui/message: custom handler preserving CopilotKit role/followUp extensions\n // (via _meta.copilotkit first, then legacy top-level fields).\n bridge.setRequestHandler(CopilotKitUiMessageSchema, async (req) => {\n const currentAgent = getAgent();\n if (!currentAgent) {\n console.warn(\"[MCPAppsRenderer] ui/message: No agent available\");\n return { isError: false };\n }\n try {\n const params = req.params;\n const ck = (params._meta?.copilotkit ?? {}) as {\n role?: string;\n followUp?: boolean;\n };\n const role =\n (ck.role as \"user\" | \"assistant\") ||\n (params.role as \"user\" | \"assistant\") ||\n \"user\";\n const textContent =\n (\n params.content as\n | Array<{ type: string; text?: string }>\n | undefined\n )\n ?.filter((c) => c.type === \"text\" && c.text)\n .map((c) => c.text)\n .join(\"\\n\") || \"\";\n if (textContent) {\n currentAgent.addMessage({\n id: randomUUID(),\n role,\n content: textContent,\n });\n }\n const followUp = ck.followUp ?? params.followUp;\n const shouldFollowUp = followUp ?? role === \"user\";\n if (shouldFollowUp && textContent) {\n const capturedThreadId = currentAgent.threadId || \"default\";\n mcpAppsRequestQueue\n .enqueue(currentAgent, () =>\n ɵrunMcpFollowUp({\n host,\n agent: currentAgent,\n capturedThreadId,\n }),\n )\n .catch((err) =>\n console.error(\n \"[MCPAppsRenderer] ui/message agent run failed:\",\n err,\n ),\n );\n }\n return { isError: false };\n } catch (err) {\n console.error(\"[MCPAppsRenderer] ui/message error:\", err);\n return { isError: true };\n }\n });\n\n bridge.onopenlink = async ({ url }) => {\n // The bridge validates `url` as a string but not the scheme. Block only\n // the script-executing / attacker-HTML schemes; everything else\n // (https universal links, custom-scheme deep links) is allowed.\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n console.warn(\n \"[MCPAppsRenderer] ui/open-link rejected: unparseable url\",\n );\n return { isError: true };\n }\n if (MCP_OPEN_LINK_BLOCKED_SCHEMES.has(parsed.protocol)) {\n console.warn(\n \"[MCPAppsRenderer] ui/open-link rejected: blocked scheme\",\n parsed.protocol,\n );\n return { isError: true };\n }\n window.open(url, \"_blank\", \"noopener,noreferrer\");\n return { isError: false };\n };\n\n bridge.oncalltool = async (params) => {\n const { serverHash, serverId } = getContent();\n const currentAgent = getAgent();\n if (!serverHash) {\n throw new Error(\"No server hash available for proxying\");\n }\n if (!currentAgent) {\n throw new Error(\"No agent available for proxying\");\n }\n const runResult = await mcpAppsRequestQueue.enqueue(currentAgent, () =>\n currentAgent.runAgent({\n forwardedProps: {\n __proxiedMCPRequest: {\n serverHash,\n serverId,\n method: \"tools/call\",\n params,\n },\n },\n }),\n );\n return (runResult.result as CallToolResult) || { content: [] };\n };\n\n // --- App -> host notifications ---\n bridge.onsizechange = (p) => {\n if (disposed) return;\n const { width, height } = (p || {}) as {\n width?: number;\n height?: number;\n };\n hooks?.onSizeChanged?.({\n width: typeof width === \"number\" ? width : undefined,\n height: typeof height === \"number\" ? height : undefined,\n });\n };\n bridge.oninitialized = () => {\n if (disposed) return;\n ready = true;\n hooks?.onInitialized?.();\n flushPending();\n };\n bridge.onloggingmessage = (p) => {\n console.log(\"[MCPAppsRenderer] App log:\", p);\n };\n\n const transport = new PostMessageTransport(win, win);\n await bridge.connect(transport);\n if (disposed) {\n await bridge.close();\n bridge = null;\n return;\n }\n } catch (err) {\n console.error(\"[MCPAppsRenderer] Setup error:\", err);\n if (!disposed) {\n hooks?.onError?.(err instanceof Error ? err : new Error(String(err)));\n }\n }\n };\n\n void setup();\n\n return {\n sendToolInput(args) {\n pendingToolInput = args;\n flushPending();\n },\n sendToolResult(result) {\n pendingToolResult = result;\n flushPending();\n },\n teardown() {\n disposed = true;\n const b = bridge;\n bridge = null;\n void b?.close();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwBA,MAAa,4BAA4B;;;;;;;;;;;;AAazC,MAAM,4BAA4B,EAAE,OAAO;CACzC,QAAQ,EAAE,QAAQ,aAAa;CAC/B,QAAQ,EACL,OAAO;EACN,MAAM,EAAE,QAAQ,CAAC,UAAU;EAC3B,SAAS,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC,UAAU;EACpC,UAAU,EAAE,SAAS,CAAC,UAAU;EAChC,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,KAAK,CAAC,CAAC,UAAU;EAChD,CAAC,CACD,aAAa;CACjB,CAAC;;;;;;;;;AAiEF,SAAgB,WAAW,MAAwC;CACjE,MAAM,EAAE,QAAQ,YAAY,UAAU,MAAM,UAAU;CAEtD,IAAI,WAAW;CACf,IAAI,QAAQ;CACZ,IAAI,SAA2B;CAC/B,IAAI;CACJ,IAAI;;CAGJ,MAAM,qBAAqB;AACzB,MAAI,CAAC,SAAS,CAAC,OAAQ;AACvB,MAAI,qBAAqB,QAAW;AAClC,GAAK,OAAO,cAAc,EAAE,WAAW,kBAAkB,CAAC;AAC1D,sBAAmB;;AAErB,MAAI,s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MAAM,wCAAwC;AAE1D,QAAI,CAAC,aACH,OAAM,IAAI,MAAM,kCAAkC;AAcpD,YAZkB,MAAM,oBAAoB,QAAQ,oBAClD,aAAa,SAAS,EACpB,gBAAgB,EACd,qBAAqB;KACnB;KACA;KACA,QAAQ;KACR;KACD,EACF,EACF,CAAC,CACH,EACiB,UAA6B,EAAE,SAAS,EAAE,EAAE;;AAIhE,UAAO,gBAAgB,MAAM;AAC3B,QAAI,SAAU;IACd,MAAM,EAAE,OAAO,WAAY,KAAK,EAAE;AAIlC,WAAO,gBAAgB;KACrB,OAAO,OAAO,UAAU,WAAW,QAAQ;KAC3C,QAAQ,OAAO,WAAW,WAAW,SAAS;KAC/C,CAAC;;AAEJ,UAAO,sBAAsB;AAC3B,QAAI,SAAU;AACd,YAAQ;AACR,WAAO,iBAAiB;AACxB,kBAAc;;AAEhB,UAAO,oBAAoB,MAAM;AAC/B,YAAQ,IAAI,8BAA8B,EAAE;;GAG9C,MAAM,YAAY,IAAI,qBAAqB,KAAK,IAAI;AACpD,SAAM,OAAO,QAAQ,UAAU;AAC/B,OAAI,UAAU;AACZ,UAAM,OAAO,OAAO;AACpB,aAAS;AACT;;WAEK,KAAK;AACZ,WAAQ,MAAM,kCAAkC,IAAI;AACpD,OAAI,CAAC,SACH,QAAO,UAAU,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,IAAI,CAAC,CAAC;;;AAK3E,CAAK,OAAO;AAEZ,QAAO;EACL,cAAc,MAAM;AAClB,sBAAmB;AACnB,iBAAc;;EAEhB,eAAe,QAAQ;AACrB,uBAAoB;AACpB,iBAAc;;EAEhB,WAAW;AACT,cAAW;GACX,MAAM,IAAI;AACV,YAAS;AACT,GAAK,GAAG,OAAO;;EAElB"}
|
|
1
|
+
{"version":3,"file":"session.mjs","names":[],"sources":["../src/session.ts"],"sourcesContent":["import {\n AppBridge,\n LATEST_PROTOCOL_VERSION,\n PostMessageTransport,\n} from \"@modelcontextprotocol/ext-apps/app-bridge\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport type { CallToolResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport { z } from \"zod\";\nimport { randomUUID } from \"@copilotkit/shared\";\nimport { buildSandboxHTML } from \"./sandbox\";\nimport { mcpAppsRequestQueue } from \"./request-queue\";\nimport { ɵrunMcpFollowUp } from \"./follow-up\";\nimport type { ɵMcpFollowUpHost } from \"./follow-up\";\nimport { MCP_OPEN_LINK_BLOCKED_SCHEMES } from \"./constants\";\nimport type { MCPAppsActivityContent } from \"./content-schema\";\n\n/**\n * The MCP Apps protocol version this host negotiates. Sourced directly from the\n * ext-apps bridge (single source of truth, no hand-maintained literal). It lives\n * here (a bridge-side module) rather than in the bridge-free `./constants` /\n * `./activity` entry so the lightweight activity-registration surface stays free\n * of the ext-apps bundle; consumers that need the version import it from the\n * package root, which already loads the bridge.\n */\nexport const MCP_APPS_PROTOCOL_VERSION = LATEST_PROTOCOL_VERSION;\n\n/**\n * Permissive `ui/message` schema. ext-apps restricts the request to\n * `role: \"user\"` with no `followUp`, but CopilotKit intentionally extends\n * `ui/message` with `role` (\"user\" | \"assistant\") and `followUp` (documented\n * behavior with dedicated tests). We register our own handler (instead of the\n * bridge's strict `onmessage`) so those extensions survive.\n *\n * Going forward, widgets SHOULD pass the extensions under\n * `params._meta.copilotkit`; the top-level `role`/`followUp` fields are the\n * legacy channel, kept for backward compatibility and slated for deprecation.\n */\nconst CopilotKitUiMessageSchema = z.object({\n method: z.literal(\"ui/message\"),\n params: z\n .object({\n role: z.string().optional(),\n content: z.array(z.any()).optional(),\n followUp: z.boolean().optional(),\n _meta: z.record(z.string(), z.any()).optional(),\n })\n .passthrough(),\n});\n\n/** A resource fetched from the MCP server via the agent proxy. */\nexport interface FetchedResource {\n uri: string;\n mimeType?: string;\n text?: string;\n blob?: string;\n _meta?: {\n ui?: {\n prefersBorder?: boolean;\n csp?: {\n connectDomains?: string[];\n resourceDomains?: string[];\n };\n };\n };\n}\n\n/** Reactive callbacks the framework adapter wires to its own state. */\nexport interface McpAppSessionHooks {\n /** The widget reported a new content size (ui/notifications/size-changed). */\n onSizeChanged?(size: { width?: number; height?: number }): void;\n /** The widget finished initializing (safe to push tool input/result). */\n onInitialized?(): void;\n /** The fetched resource metadata (e.g. prefersBorder) is available. */\n onResource?(resource: FetchedResource): void;\n /** Setup failed (resource fetch, connect, ...). */\n onError?(err: Error): void;\n}\n\nexport interface BindMcpAppOptions {\n /**\n * The sandbox iframe. The adapter creates and OWNS this element (mounts it in\n * its render model, sizes it, removes it on unmount). The session only\n * configures the sandbox contract (sandbox attr, testid, srcdoc) and talks to\n * it through the bridge - it never creates, moves, or removes the iframe.\n */\n iframe: HTMLIFrameElement;\n /** Returns the current activity content (resourceUri, serverHash, tool input/result). */\n getContent: () => MCPAppsActivityContent;\n /** Returns the current agent (may change across renders). */\n getAgent: () => AbstractAgent | undefined;\n /** CopilotKit host, for ui/message follow-up runs (issue #5819). */\n host: ɵMcpFollowUpHost;\n hooks?: McpAppSessionHooks;\n}\n\nexport interface McpAppSession {\n /** Forward the tool call input to the widget (host -> app). Buffered until ready. */\n sendToolInput(args: Record<string, unknown>): void;\n /** Forward the tool result to the widget (host -> app). Buffered until ready. */\n sendToolResult(result: CallToolResult): void;\n /** Disconnect the bridge and release listeners. Does NOT remove the iframe. */\n teardown(): void;\n}\n\n/**\n * Bind an MCP App to a host-provided sandbox iframe: fetch the widget resource\n * through the agent, connect the ext-apps `AppBridge` over a PostMessage\n * transport, and wire the app<->host protocol (ui/message, ui/open-link,\n * tools/call + resources/read proxy, size, host context). Framework-agnostic:\n * the React/Vue/Angular renderers create the iframe and wire reactive state via\n * `hooks`, but all protocol logic lives here.\n */\nexport function bindMcpApp(opts: BindMcpAppOptions): McpAppSession {\n const { iframe, getContent, getAgent, host, hooks } = opts;\n\n let disposed = false;\n let ready = false;\n let bridge: AppBridge | null = null;\n let pendingToolInput: Record<string, unknown> | undefined;\n let pendingToolResult: CallToolResult | undefined;\n\n /** Flush any buffered tool input/result to the widget once it is initialized. */\n const flushPending = () => {\n if (!ready || !bridge) return;\n if (pendingToolInput !== undefined) {\n void bridge.sendToolInput({ arguments: pendingToolInput });\n pendingToolInput = undefined;\n }\n if (pendingToolResult !== undefined) {\n void bridge.sendToolResult(pendingToolResult);\n pendingToolResult = undefined;\n }\n };\n\n /** Fetch the widget resource (`resources/read`) through the agent proxy queue. */\n const fetchResource = async (): Promise<FetchedResource> => {\n const agent = getAgent();\n if (!agent) {\n throw new Error(\"No agent available to fetch resource\");\n }\n const { resourceUri, serverHash, serverId } = getContent();\n const runResult = await mcpAppsRequestQueue.enqueue(agent, () =>\n agent.runAgent({\n forwardedProps: {\n __proxiedMCPRequest: {\n serverHash,\n serverId,\n method: \"resources/read\",\n params: { uri: resourceUri },\n },\n },\n }),\n );\n const resultData = runResult.result as\n | { contents?: FetchedResource[] }\n | undefined;\n const resource = resultData?.contents?.[0];\n if (!resource) {\n throw new Error(\"No resource content in response\");\n }\n return resource;\n };\n\n /**\n * Fetch the resource, configure + load the sandbox iframe, construct the\n * AppBridge, wire the app->host handlers, and connect the transport.\n */\n const setup = async () => {\n try {\n const resource = await fetchResource();\n if (disposed) return;\n hooks?.onResource?.(resource);\n\n // Configure the sandbox iframe (contract shared across frontends).\n iframe.setAttribute(\n \"sandbox\",\n \"allow-scripts allow-same-origin allow-forms\",\n );\n // Cross-frontend MCP-apps surface contract: every frontend must expose the\n // sandbox iframe under the SAME testid so one shared probe (harness\n // `d5-mcp-apps`) and one shared e2e spec can assert the surface mounted\n // without per-frontend selectors.\n iframe.setAttribute(\"data-testid\", \"mcp-app-iframe\");\n iframe.setAttribute(\"title\", \"Interactive MCP application\");\n\n const cspDomains = resource._meta?.ui?.csp?.resourceDomains;\n iframe.srcdoc = buildSandboxHTML(cspDomains);\n\n const win = iframe.contentWindow;\n if (!win) {\n throw new Error(\"Sandbox iframe has no contentWindow\");\n }\n\n let html: string;\n if (resource.text) {\n html = resource.text;\n } else if (resource.blob) {\n html = atob(resource.blob);\n } else {\n throw new Error(\"Resource has no text or blob content\");\n }\n\n bridge = new AppBridge(\n null,\n { name: \"CopilotKit MCP Apps Host\", version: \"1.0.0\" },\n { openLinks: {}, logging: {}, message: { text: {} } },\n // Seed the host context at construction so it is already in place when\n // the widget's ui/initialize is handled (deterministic, not a race).\n // The theme follows CopilotKit's dark selector: a `.dark` ancestor.\n {\n hostContext: {\n theme: iframe.closest(\".dark\") ? \"dark\" : \"light\",\n platform: \"web\",\n },\n },\n );\n\n // Sandbox handshake: on proxy ready, load the widget HTML into the inner\n // sandboxed iframe.\n bridge.onsandboxready = () => {\n void bridge?.sendSandboxResourceReady({ html });\n };\n\n // --- App -> host requests ---\n // ui/message: custom handler preserving CopilotKit role/followUp extensions\n // (via _meta.copilotkit first, then legacy top-level fields).\n bridge.setRequestHandler(CopilotKitUiMessageSchema, async (req) => {\n const currentAgent = getAgent();\n if (!currentAgent) {\n console.warn(\"[MCPAppsRenderer] ui/message: No agent available\");\n return { isError: false };\n }\n try {\n const params = req.params;\n const ck = (params._meta?.copilotkit ?? {}) as {\n role?: string;\n followUp?: boolean;\n };\n const role =\n (ck.role as \"user\" | \"assistant\") ||\n (params.role as \"user\" | \"assistant\") ||\n \"user\";\n const textContent =\n (\n params.content as\n | Array<{ type: string; text?: string }>\n | undefined\n )\n ?.filter((c) => c.type === \"text\" && c.text)\n .map((c) => c.text)\n .join(\"\\n\") || \"\";\n if (textContent) {\n currentAgent.addMessage({\n id: randomUUID(),\n role,\n content: textContent,\n });\n }\n const followUp = ck.followUp ?? params.followUp;\n const shouldFollowUp = followUp ?? role === \"user\";\n if (shouldFollowUp && textContent) {\n const capturedThreadId = currentAgent.threadId || \"default\";\n mcpAppsRequestQueue\n .enqueue(currentAgent, () =>\n ɵrunMcpFollowUp({\n host,\n agent: currentAgent,\n capturedThreadId,\n }),\n )\n .catch((err) =>\n console.error(\n \"[MCPAppsRenderer] ui/message agent run failed:\",\n err,\n ),\n );\n }\n return { isError: false };\n } catch (err) {\n console.error(\"[MCPAppsRenderer] ui/message error:\", err);\n return { isError: true };\n }\n });\n\n bridge.onopenlink = async ({ url }) => {\n // The bridge validates `url` as a string but not the scheme. Block only\n // the script-executing / attacker-HTML schemes; everything else\n // (https universal links, custom-scheme deep links) is allowed.\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n console.warn(\n \"[MCPAppsRenderer] ui/open-link rejected: unparseable url\",\n );\n return { isError: true };\n }\n if (MCP_OPEN_LINK_BLOCKED_SCHEMES.has(parsed.protocol)) {\n console.warn(\n \"[MCPAppsRenderer] ui/open-link rejected: blocked scheme\",\n parsed.protocol,\n );\n return { isError: true };\n }\n window.open(url, \"_blank\", \"noopener,noreferrer\");\n return { isError: false };\n };\n\n bridge.oncalltool = async (params) => {\n const { serverHash, serverId } = getContent();\n const currentAgent = getAgent();\n if (!serverHash) {\n throw new Error(\"No server hash available for proxying\");\n }\n if (!currentAgent) {\n throw new Error(\"No agent available for proxying\");\n }\n const runResult = await mcpAppsRequestQueue.enqueue(currentAgent, () =>\n currentAgent.runAgent({\n forwardedProps: {\n __proxiedMCPRequest: {\n serverHash,\n serverId,\n method: \"tools/call\",\n params,\n },\n },\n }),\n );\n return (runResult.result as CallToolResult) || { content: [] };\n };\n\n // --- App -> host notifications ---\n bridge.onsizechange = (p) => {\n if (disposed) return;\n const { width, height } = (p || {}) as {\n width?: number;\n height?: number;\n };\n hooks?.onSizeChanged?.({\n width: typeof width === \"number\" ? width : undefined,\n height: typeof height === \"number\" ? height : undefined,\n });\n };\n bridge.oninitialized = () => {\n if (disposed) return;\n ready = true;\n hooks?.onInitialized?.();\n flushPending();\n };\n bridge.onloggingmessage = (p) => {\n console.log(\"[MCPAppsRenderer] App log:\", p);\n };\n\n const transport = new PostMessageTransport(win, win);\n await bridge.connect(transport);\n if (disposed) {\n await bridge.close();\n bridge = null;\n return;\n }\n } catch (err) {\n console.error(\"[MCPAppsRenderer] Setup error:\", err);\n if (!disposed) {\n hooks?.onError?.(err instanceof Error ? err : new Error(String(err)));\n }\n }\n };\n\n void setup();\n\n return {\n sendToolInput(args) {\n pendingToolInput = args;\n flushPending();\n },\n sendToolResult(result) {\n pendingToolResult = result;\n flushPending();\n },\n teardown() {\n disposed = true;\n const b = bridge;\n bridge = null;\n void b?.close();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwBA,MAAa,4BAA4B;;;;;;;;;;;;AAazC,MAAM,4BAA4B,EAAE,OAAO;CACzC,QAAQ,EAAE,QAAQ,aAAa;CAC/B,QAAQ,EACL,OAAO;EACN,MAAM,EAAE,QAAQ,CAAC,UAAU;EAC3B,SAAS,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC,UAAU;EACpC,UAAU,EAAE,SAAS,CAAC,UAAU;EAChC,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,KAAK,CAAC,CAAC,UAAU;EAChD,CAAC,CACD,aAAa;CACjB,CAAC;;;;;;;;;AAiEF,SAAgB,WAAW,MAAwC;CACjE,MAAM,EAAE,QAAQ,YAAY,UAAU,MAAM,UAAU;CAEtD,IAAI,WAAW;CACf,IAAI,QAAQ;CACZ,IAAI,SAA2B;CAC/B,IAAI;CACJ,IAAI;;CAGJ,MAAM,qBAAqB;AACzB,MAAI,CAAC,SAAS,CAAC,OAAQ;AACvB,MAAI,qBAAqB,QAAW;AAClC,GAAK,OAAO,cAAc,EAAE,WAAW,kBAAkB,CAAC;AAC1D,sBAAmB;;AAErB,MAAI,sBAAsB,QAAW;AACnC,GAAK,OAAO,eAAe,kBAAkB;AAC7C,uBAAoB;;;;CAKxB,MAAM,gBAAgB,YAAsC;EAC1D,MAAM,QAAQ,UAAU;AACxB,MAAI,CAAC,MACH,OAAM,IAAI,MAAM,uCAAuC;EAEzD,MAAM,EAAE,aAAa,YAAY,aAAa,YAAY;EAgB1D,MAAM,YAfY,MAAM,oBAAoB,QAAQ,aAClD,MAAM,SAAS,EACb,gBAAgB,EACd,qBAAqB;GACnB;GACA;GACA,QAAQ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AAM,EAAE,OAAO,WAAY,KAAK,EAAE;AAIlC,WAAO,gBAAgB;KACrB,OAAO,OAAO,UAAU,WAAW,QAAQ;KAC3C,QAAQ,OAAO,WAAW,WAAW,SAAS;KAC/C,CAAC;;AAEJ,UAAO,sBAAsB;AAC3B,QAAI,SAAU;AACd,YAAQ;AACR,WAAO,iBAAiB;AACxB,kBAAc;;AAEhB,UAAO,oBAAoB,MAAM;AAC/B,YAAQ,IAAI,8BAA8B,EAAE;;GAG9C,MAAM,YAAY,IAAI,qBAAqB,KAAK,IAAI;AACpD,SAAM,OAAO,QAAQ,UAAU;AAC/B,OAAI,UAAU;AACZ,UAAM,OAAO,OAAO;AACpB,aAAS;AACT;;WAEK,KAAK;AACZ,WAAQ,MAAM,kCAAkC,IAAI;AACpD,OAAI,CAAC,SACH,QAAO,UAAU,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,IAAI,CAAC,CAAC;;;AAK3E,CAAK,OAAO;AAEZ,QAAO;EACL,cAAc,MAAM;AAClB,sBAAmB;AACnB,iBAAc;;EAEhB,eAAe,QAAQ;AACrB,uBAAoB;AACpB,iBAAc;;EAEhB,WAAW;AACT,cAAW;GACX,MAAM,IAAI;AACV,YAAS;AACT,GAAK,GAAG,OAAO;;EAElB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@copilotkit/mcp-apps-renderer",
|
|
3
|
-
"version": "1.75.
|
|
3
|
+
"version": "1.75.2",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Framework-agnostic MCP Apps host for CopilotKit - the app<->host protocol (ext-apps AppBridge), sandbox proxy, and shared renderer consumed by the React, Vue, and Angular frontends",
|
|
6
6
|
"keywords": [
|
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
"dependencies": {
|
|
51
51
|
"@modelcontextprotocol/ext-apps": "^1.7.5",
|
|
52
52
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
53
|
-
"@copilotkit/shared": "1.75.
|
|
53
|
+
"@copilotkit/shared": "1.75.2"
|
|
54
54
|
},
|
|
55
55
|
"peerDependencies": {
|
|
56
56
|
"@ag-ui/client": "0.0.59",
|