@botdojo/chat-sdk 0.0.26 → 0.0.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,261 @@
1
- import 'react';
1
+ import React, { useRef, useState, useCallback, useEffect } from 'react';
2
2
  import 'react-dom';
3
- export * from 'mcp-app-view/host';
3
+ import { jsx } from 'react/jsx-runtime';
4
+
5
+ var McpMethods = {
6
+ // Host → UI
7
+ INITIALIZE: "ui/initialize",
8
+ TOOL_INPUT_PARTIAL: "ui/notifications/tool-input-partial",
9
+ TOOL_INPUT: "ui/notifications/tool-input",
10
+ TOOL_RESULT: "ui/notifications/tool-result",
11
+ TOOL_CANCELLED: "ui/tool-cancelled",
12
+ HOST_CONTEXT_CHANGED: "ui/notifications/host-context-changed",
13
+ RESOURCE_TEARDOWN: "ui/resource-teardown",
14
+ // UI → Host
15
+ INITIALIZED: "ui/notifications/initialized",
16
+ SIZE_CHANGE: "ui/notifications/size-change",
17
+ OPEN_LINK: "ui/open-link",
18
+ MESSAGE: "ui/message",
19
+ TOOLS_CALL: "tools/call"
20
+ };
21
+ var McpProxyHost = React.forwardRef(
22
+ function McpProxyHost2({
23
+ proxyUrl,
24
+ appUrl,
25
+ appInfo = { name: "MCP Host", version: "1.0.0" },
26
+ hostCapabilities = { openLinks: {} },
27
+ hostContext = {},
28
+ sandboxPermissions = ["allow-scripts", "allow-forms"],
29
+ className,
30
+ style,
31
+ iframeStyle,
32
+ width = "100%",
33
+ height = "auto",
34
+ debug = false,
35
+ onInitialized,
36
+ onSizeChange,
37
+ onMessage,
38
+ onOpenLink,
39
+ onToolCall,
40
+ onError
41
+ }, ref) {
42
+ const iframeRef = useRef(null);
43
+ const [isInitialized, setIsInitialized] = useState(false);
44
+ const [iframeSize, setIframeSize] = useState(null);
45
+ const pendingRequests = useRef(/* @__PURE__ */ new Map());
46
+ const nextRequestId = useRef(0);
47
+ const initializeRetries = useRef(0);
48
+ const initializeTimer = useRef(null);
49
+ const targetOrigin = useRef("*");
50
+ const log = useCallback((message, data) => {
51
+ if (debug) {
52
+ if (data !== void 0) {
53
+ console.log(`[McpProxyHost] ${message}`, data);
54
+ } else {
55
+ console.log(`[McpProxyHost] ${message}`);
56
+ }
57
+ }
58
+ }, [debug]);
59
+ const send = useCallback((message) => {
60
+ var _a;
61
+ const iframe = iframeRef.current;
62
+ if (!(iframe == null ? void 0 : iframe.contentWindow)) {
63
+ log("Cannot send: iframe not ready");
64
+ return;
65
+ }
66
+ log(`Sending: ${(_a = message.method) != null ? _a : "response"}`, message);
67
+ iframe.contentWindow.postMessage(message, targetOrigin.current);
68
+ }, [log]);
69
+ const sendRequest = useCallback((method, params, timeoutMs = 5e3) => {
70
+ const id = `host-${++nextRequestId.current}`;
71
+ const request = { jsonrpc: "2.0", id, method, params };
72
+ return new Promise((resolve, reject) => {
73
+ const timer = setTimeout(() => {
74
+ pendingRequests.current.delete(id);
75
+ reject(new Error(`Request timeout: ${method}`));
76
+ }, timeoutMs);
77
+ pendingRequests.current.set(id, { resolve, reject, timer });
78
+ send(request);
79
+ });
80
+ }, [send]);
81
+ const sendNotification = useCallback((method, params) => {
82
+ send({ jsonrpc: "2.0", method, params });
83
+ }, [send]);
84
+ const sendResponse = useCallback((id, result) => {
85
+ send({ jsonrpc: "2.0", id, result });
86
+ }, [send]);
87
+ const sendError = useCallback((id, code, message, data) => {
88
+ send({ jsonrpc: "2.0", id, error: { code, message, data } });
89
+ }, [send]);
90
+ const sendInitialize = useCallback(() => {
91
+ const params = {
92
+ protocolVersion: "mcp-apps/0.1",
93
+ appInfo,
94
+ hostCapabilities,
95
+ hostContext
96
+ };
97
+ log("Sending ui/initialize", params);
98
+ sendRequest(McpMethods.INITIALIZE, params, 2e3).catch(() => {
99
+ if (!isInitialized && initializeRetries.current < 5) {
100
+ initializeRetries.current++;
101
+ initializeTimer.current = setTimeout(sendInitialize, 300);
102
+ }
103
+ });
104
+ }, [appInfo, hostCapabilities, hostContext, sendRequest, isInitialized, log]);
105
+ useEffect(() => {
106
+ const handleMessage = (event) => {
107
+ const data = event.data;
108
+ if (!data || typeof data !== "object" || data.jsonrpc !== "2.0")
109
+ return;
110
+ if (targetOrigin.current === "*" && event.origin) {
111
+ targetOrigin.current = event.origin;
112
+ log(`Learned target origin: ${targetOrigin.current}`);
113
+ }
114
+ if ("id" in data && !("method" in data)) {
115
+ const pending = pendingRequests.current.get(data.id);
116
+ if (pending) {
117
+ if (pending.timer)
118
+ clearTimeout(pending.timer);
119
+ pendingRequests.current.delete(data.id);
120
+ if ("error" in data) {
121
+ pending.reject(data.error);
122
+ } else {
123
+ pending.resolve(data.result);
124
+ }
125
+ }
126
+ return;
127
+ }
128
+ const { method, params, id } = data;
129
+ if (!method)
130
+ return;
131
+ log(`Received: ${method}`, params);
132
+ const handleAsync = async () => {
133
+ try {
134
+ switch (method) {
135
+ case McpMethods.INITIALIZED:
136
+ setIsInitialized(true);
137
+ initializeRetries.current = 0;
138
+ if (initializeTimer.current) {
139
+ clearTimeout(initializeTimer.current);
140
+ initializeTimer.current = null;
141
+ }
142
+ onInitialized == null ? void 0 : onInitialized();
143
+ break;
144
+ case McpMethods.SIZE_CHANGE:
145
+ const sizeParams = params;
146
+ setIframeSize(sizeParams);
147
+ onSizeChange == null ? void 0 : onSizeChange(sizeParams);
148
+ break;
149
+ case McpMethods.OPEN_LINK:
150
+ const linkParams = params;
151
+ onOpenLink == null ? void 0 : onOpenLink(linkParams.url);
152
+ if (id !== void 0)
153
+ sendResponse(id, { ok: true });
154
+ break;
155
+ case McpMethods.MESSAGE:
156
+ const msgParams = params;
157
+ await (onMessage == null ? void 0 : onMessage(msgParams));
158
+ if (id !== void 0)
159
+ sendResponse(id, { ok: true });
160
+ break;
161
+ case McpMethods.TOOLS_CALL:
162
+ const toolParams = params;
163
+ if (onToolCall) {
164
+ const result = await onToolCall(toolParams.name, toolParams.arguments);
165
+ if (id !== void 0)
166
+ sendResponse(id, result);
167
+ } else {
168
+ if (id !== void 0)
169
+ sendError(id, -32601, "Tool call handler not configured");
170
+ }
171
+ break;
172
+ default:
173
+ if (id !== void 0) {
174
+ sendResponse(id, { ok: true, ignored: true });
175
+ }
176
+ }
177
+ } catch (err) {
178
+ const error = err instanceof Error ? err : new Error(String(err));
179
+ log(`Error handling ${method}:`, error);
180
+ onError == null ? void 0 : onError(error);
181
+ if (id !== void 0) {
182
+ sendError(id, -32e3, error.message);
183
+ }
184
+ }
185
+ };
186
+ handleAsync();
187
+ };
188
+ window.addEventListener("message", handleMessage);
189
+ return () => window.removeEventListener("message", handleMessage);
190
+ }, [log, sendResponse, sendError, onInitialized, onSizeChange, onOpenLink, onMessage, onToolCall, onError]);
191
+ const handleIframeLoad = useCallback(() => {
192
+ log("Iframe loaded, sending initialize");
193
+ initializeRetries.current = 0;
194
+ sendInitialize();
195
+ }, [sendInitialize, log]);
196
+ useEffect(() => {
197
+ return () => {
198
+ if (initializeTimer.current) {
199
+ clearTimeout(initializeTimer.current);
200
+ }
201
+ pendingRequests.current.forEach(({ timer }) => {
202
+ if (timer)
203
+ clearTimeout(timer);
204
+ });
205
+ pendingRequests.current.clear();
206
+ };
207
+ }, []);
208
+ const iframeSrc = `${proxyUrl}?app=${encodeURIComponent(appUrl)}`;
209
+ React.useImperativeHandle(ref, () => ({
210
+ sendToolInputPartial: (params) => {
211
+ sendNotification(McpMethods.TOOL_INPUT_PARTIAL, params);
212
+ },
213
+ sendToolInput: (params) => {
214
+ sendNotification(McpMethods.TOOL_INPUT, params);
215
+ },
216
+ sendToolResult: (params) => {
217
+ sendNotification(McpMethods.TOOL_RESULT, params);
218
+ },
219
+ sendHostContextChanged: (context) => {
220
+ sendNotification(McpMethods.HOST_CONTEXT_CHANGED, context);
221
+ },
222
+ sendResourceTeardown: () => {
223
+ sendNotification(McpMethods.RESOURCE_TEARDOWN, {});
224
+ },
225
+ getIframe: () => iframeRef.current,
226
+ isInitialized: () => isInitialized
227
+ }), [sendNotification, isInitialized]);
228
+ const computedHeight = height === "auto" && iframeSize ? `${iframeSize.height}px` : height;
229
+ return /* @__PURE__ */ jsx(
230
+ "div",
231
+ {
232
+ className,
233
+ style: {
234
+ width: typeof width === "number" ? `${width}px` : width,
235
+ height: computedHeight === "auto" ? void 0 : typeof computedHeight === "number" ? `${computedHeight}px` : computedHeight,
236
+ ...style
237
+ },
238
+ children: /* @__PURE__ */ jsx(
239
+ "iframe",
240
+ {
241
+ ref: iframeRef,
242
+ src: iframeSrc,
243
+ sandbox: sandboxPermissions.join(" "),
244
+ onLoad: handleIframeLoad,
245
+ style: {
246
+ width: "100%",
247
+ height: computedHeight === "auto" ? iframeSize ? `${iframeSize.height}px` : "100%" : "100%",
248
+ border: "none",
249
+ ...iframeStyle
250
+ },
251
+ title: "MCP App"
252
+ }
253
+ )
254
+ }
255
+ );
256
+ }
257
+ );
258
+
259
+ export { McpProxyHost };
4
260
  //# sourceMappingURL=out.js.map
5
261
  //# sourceMappingURL=host.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/mcp-app-view/host.ts"],"names":[],"mappings":";;;;;;;;;AACA,cAAc","sourcesContent":["// Re-export mcp-app-view/host module\nexport * from 'mcp-app-view/host';\n"]}
1
+ {"version":3,"sources":["../../../../node_modules/.pnpm/mcp-app-view@0.1.5_react@18.3.1/node_modules/mcp-app-view/src/protocol/types.ts","../../../../node_modules/.pnpm/mcp-app-view@0.1.5_react@18.3.1/node_modules/mcp-app-view/src/host/McpProxyHost.tsx"],"names":["McpProxyHost"],"mappings":";;;;;;;;;;;AAwMO,IAAM,aAAa;;EAExB,YAAY;EACZ,oBAAoB;EACpB,YAAY;EACZ,aAAa;EACb,gBAAgB;EAChB,sBAAsB;EACtB,mBAAmB;;EAGnB,aAAa;EACb,aAAa;EACb,WAAW;EACX,SAAS;EACT,YAAY;AACd;ACpFO,IAAM,eAAe,MAAM;EAChC,SAASA,cACP;IACE;IACA;IACA,UAAU,EAAE,MAAM,YAAY,SAAS,QAAA;IACvC,mBAAmB,EAAE,WAAW,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AAA,CAAE;MACnD;MACA,WAAW,MAAM,UAAU;MAC3B,eAAe,MAAM;IAAA,IACnB,CAAC,kBAAkB,aAAa,CAAC;AAGrC,UAAM,iBAAiB,WAAW,UAAU,aACxC,GAAG,WAAW,MAAM,OACpB;AAEJ,WACE;MAAC;MAAA;QACC;QACA,OAAO;UACL,OAAO,OAAO,UAAU,WAAW,GAAG,KAAK,OAAO;UAClD,QAAQ,mBAAmB,SAAS,SAAa,OAAO,mBAAmB,WAAW,GAAG,cAAc,OAAO;UAC9G,GAAG;QAAA;QAGL,UAAA;UAAC;UAAA;YACC,KAAK;YACL,KAAK;YACL,SAAS,mBAAmB,KAAK,GAAG;YACpC,QAAQ;YACR,OAAO;cACL,OAAO;cACP,QAAQ,mBAAmB,SAAU,aAAa,GAAG,WAAW,MAAM,OAAO,SAAU;cACvF,QAAQ;cACR,GAAG;YAAA;YAEL,OAAM;UAAA;QAAA;MACR;IAAA;EAGN;AACF","sourcesContent":["/**\n * SEP-1865 MCP Apps Protocol Types\n * @see https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/draft/apps.mdx\n */\n\n// =============================================================================\n// JSON-RPC 2.0 Base Types\n// =============================================================================\n\nexport type JsonRpcId = string | number;\n\nexport interface JsonRpcRequest {\n jsonrpc: '2.0';\n id: JsonRpcId;\n method: string;\n params?: unknown;\n}\n\nexport interface JsonRpcNotification {\n jsonrpc: '2.0';\n method: string;\n params?: unknown;\n}\n\nexport interface JsonRpcSuccess {\n jsonrpc: '2.0';\n id: JsonRpcId;\n result: unknown;\n}\n\nexport interface JsonRpcError {\n jsonrpc: '2.0';\n id: JsonRpcId;\n error: {\n code: number;\n message: string;\n data?: unknown;\n };\n}\n\nexport type JsonRpcMessage = JsonRpcRequest | JsonRpcNotification | JsonRpcSuccess | JsonRpcError;\n\n// =============================================================================\n// SEP-1865 Core Types\n// =============================================================================\n\n/**\n * Application information sent by the host during initialization\n */\nexport interface AppInfo {\n name: string;\n version?: string;\n}\n\n/**\n * Host capabilities advertised during initialization\n */\nexport interface HostCapabilities {\n /** Host supports opening external links */\n openLinks?: Record<string, never>;\n /** Extension capabilities */\n [key: string]: unknown;\n}\n\n/**\n * SEP-1865 spec-compliant Tool schema\n */\nexport interface Tool {\n name: string;\n description?: string;\n inputSchema?: Record<string, unknown>;\n}\n\n/**\n * SEP-1865 spec-compliant toolInfo\n * @see https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/draft/apps.mdx#host-context-in-mcpuiinitializeresult\n */\nexport interface ToolInfo {\n /** JSON-RPC id of the tools/call request */\n id?: string | number;\n /** Tool schema (name, description, inputSchema) */\n tool: Tool;\n /** Tool arguments (BotDojo extension for hydration) */\n arguments?: Record<string, unknown>;\n /** Tool result (BotDojo extension for hydration) */\n result?: unknown;\n}\n\n/**\n * Host context passed to the UI during initialization and updates\n */\nexport interface HostContext {\n /** Current theme preference */\n theme?: 'light' | 'dark';\n /** Viewport dimensions */\n viewport?: {\n width: number;\n height: number;\n };\n /** Locale preference */\n locale?: string;\n /**\n * SEP-1865 spec-compliant tool metadata\n * Contains the tool schema (name, description, inputSchema) and request id.\n * Tool arguments/results come via ui/notifications/tool-input and tool-result.\n */\n toolInfo?: ToolInfo;\n /** UI state persisted by the host (BotDojo extension, not in spec) */\n state?: unknown;\n /** Extension context fields */\n [key: string]: unknown;\n}\n\n// =============================================================================\n// SEP-1865 Host → UI Messages\n// =============================================================================\n\n/**\n * ui/initialize - Host initializes the UI\n */\nexport interface UiInitializeParams {\n protocolVersion: string;\n appInfo: AppInfo;\n hostCapabilities: HostCapabilities;\n hostContext: HostContext;\n}\n\n/**\n * ui/notifications/tool-input-partial - Streaming tool arguments or progress\n */\nexport interface ToolInputPartialParams {\n tool: { name: string };\n arguments: Record<string, unknown>;\n}\n\n/**\n * ui/notifications/tool-input - Final tool arguments\n */\nexport interface ToolInputParams {\n tool: { name: string };\n arguments: Record<string, unknown>;\n}\n\n/**\n * ui/notifications/tool-result - Tool execution result\n */\nexport interface ToolResultParams {\n tool: { name: string };\n result: unknown;\n}\n\n/**\n * ui/notifications/host-context-changed - Host context update\n */\nexport type HostContextChangedParams = HostContext;\n\n// =============================================================================\n// SEP-1865 UI → Host Messages\n// =============================================================================\n\n/**\n * ui/notifications/size-change - UI reports size change\n */\nexport interface SizeChangeParams {\n width: number;\n height: number;\n}\n\n/**\n * ui/open-link - UI requests host open a URL\n */\nexport interface OpenLinkParams {\n url: string;\n}\n\n/**\n * ui/message - UI sends message to host\n */\nexport interface MessageContent {\n type: string;\n text?: string;\n [key: string]: unknown;\n}\n\nexport interface UiMessageParams {\n content: MessageContent[];\n}\n\n/**\n * tools/call - UI calls a tool on the host\n */\nexport interface ToolsCallParams {\n name: string;\n arguments?: Record<string, unknown>;\n}\n\n// =============================================================================\n// Protocol Method Constants\n// =============================================================================\n\nexport const McpMethods = {\n // Host → UI\n INITIALIZE: 'ui/initialize',\n TOOL_INPUT_PARTIAL: 'ui/notifications/tool-input-partial',\n TOOL_INPUT: 'ui/notifications/tool-input',\n TOOL_RESULT: 'ui/notifications/tool-result',\n TOOL_CANCELLED: 'ui/tool-cancelled',\n HOST_CONTEXT_CHANGED: 'ui/notifications/host-context-changed',\n RESOURCE_TEARDOWN: 'ui/resource-teardown',\n \n // UI → Host\n INITIALIZED: 'ui/notifications/initialized',\n SIZE_CHANGE: 'ui/notifications/size-change',\n OPEN_LINK: 'ui/open-link',\n MESSAGE: 'ui/message',\n TOOLS_CALL: 'tools/call',\n} as const;\n\n// =============================================================================\n// Event Types\n// =============================================================================\n\nexport type McpEventMap = {\n 'initialize': UiInitializeParams;\n 'initialized': void;\n 'toolInputPartial': ToolInputPartialParams;\n 'toolInput': ToolInputParams;\n 'toolResult': ToolResultParams;\n 'hostContextChanged': HostContextChangedParams;\n 'resourceTeardown': void;\n 'sizeChange': SizeChangeParams;\n 'error': Error;\n};\n\nexport type McpEventType = keyof McpEventMap;\n\n","/**\n * McpProxyHost - Component for hosting MCP Apps in a sandboxed iframe\n * \n * This component creates a sandboxed proxy iframe that hosts MCP Apps.\n * It handles the SEP-1865 protocol communication with the embedded app.\n */\n\nimport React, { useRef, useEffect, useCallback, useState, type CSSProperties } from 'react';\nimport type {\n JsonRpcMessage,\n JsonRpcRequest,\n JsonRpcId,\n AppInfo,\n HostCapabilities,\n HostContext,\n UiInitializeParams,\n ToolInputPartialParams,\n ToolInputParams,\n ToolResultParams,\n MessageContent,\n} from '../protocol/types';\nimport { McpMethods } from '../protocol/types';\n\n// =============================================================================\n// Types\n// =============================================================================\n\ninterface PendingRequest {\n resolve: (value: unknown) => void;\n reject: (reason?: unknown) => void;\n timer?: ReturnType<typeof setTimeout>;\n}\n\nexport interface McpProxyHostProps {\n /** URL of the proxy server that serves the sandbox iframe */\n proxyUrl: string;\n /** URL of the MCP App to host */\n appUrl: string;\n /** App info to send during initialization */\n appInfo?: AppInfo;\n /** Host capabilities */\n hostCapabilities?: HostCapabilities;\n /** Initial host context */\n hostContext?: HostContext;\n /** Sandbox permissions (default: allow-scripts allow-forms) */\n sandboxPermissions?: string[];\n /** CSS class name */\n className?: string;\n /** Inline styles */\n style?: CSSProperties;\n /** Iframe styles */\n iframeStyle?: CSSProperties;\n /** Width (default: 100%) */\n width?: string | number;\n /** Height (default: auto) */\n height?: string | number;\n /** Enable debug logging */\n debug?: boolean;\n \n // Event callbacks\n /** Called when app is initialized */\n onInitialized?: () => void;\n /** Called when app reports size change */\n onSizeChange?: (size: { width: number; height: number }) => void;\n /** Called when app sends a message */\n onMessage?: (params: { content: MessageContent[] }) => void | Promise<void>;\n /** Called when app requests to open a link */\n onOpenLink?: (url: string) => void;\n /** Called when app calls a tool */\n onToolCall?: (name: string, args?: Record<string, unknown>) => Promise<unknown>;\n /** Called on error */\n onError?: (error: Error) => void;\n}\n\nexport interface McpProxyHostRef {\n /** Send tool input partial notification */\n sendToolInputPartial: (params: ToolInputPartialParams) => void;\n /** Send tool input notification */\n sendToolInput: (params: ToolInputParams) => void;\n /** Send tool result notification */\n sendToolResult: (params: ToolResultParams) => void;\n /** Send host context changed notification */\n sendHostContextChanged: (context: HostContext) => void;\n /** Send resource teardown notification */\n sendResourceTeardown: () => void;\n /** Get the iframe element */\n getIframe: () => HTMLIFrameElement | null;\n /** Check if initialized */\n isInitialized: () => boolean;\n}\n\n// =============================================================================\n// Component\n// =============================================================================\n\n/**\n * McpProxyHost - Hosts MCP Apps in a sandboxed iframe\n * \n * @example\n * ```tsx\n * function MyHost() {\n * const hostRef = useRef<McpProxyHostRef>(null);\n * \n * const handleMessage = async (params) => {\n * console.log('Message from app:', params.content);\n * };\n * \n * const handleToolCall = async (name, args) => {\n * // Handle tool calls from the app\n * return { result: 'success' };\n * };\n * \n * // Send tool updates\n * useEffect(() => {\n * hostRef.current?.sendToolInput({\n * tool: { name: 'myTool' },\n * arguments: { step: 1 },\n * });\n * }, []);\n * \n * return (\n * <McpProxyHost\n * ref={hostRef}\n * proxyUrl=\"https://proxy.example.com\"\n * appUrl=\"https://app.example.com\"\n * onMessage={handleMessage}\n * onToolCall={handleToolCall}\n * />\n * );\n * }\n * ```\n */\nexport const McpProxyHost = React.forwardRef<McpProxyHostRef, McpProxyHostProps>(\n function McpProxyHost(\n {\n proxyUrl,\n appUrl,\n appInfo = { name: 'MCP Host', version: '1.0.0' },\n hostCapabilities = { openLinks: {} },\n hostContext = {},\n sandboxPermissions = ['allow-scripts', 'allow-forms'],\n className,\n style,\n iframeStyle,\n width = '100%',\n height = 'auto',\n debug = false,\n onInitialized,\n onSizeChange,\n onMessage,\n onOpenLink,\n onToolCall,\n onError,\n },\n ref\n ) {\n const iframeRef = useRef<HTMLIFrameElement>(null);\n const [isInitialized, setIsInitialized] = useState(false);\n const [iframeSize, setIframeSize] = useState<{ width: number; height: number } | null>(null);\n \n // Pending requests for request-response pattern\n const pendingRequests = useRef<Map<JsonRpcId, PendingRequest>>(new Map());\n const nextRequestId = useRef(0);\n const initializeRetries = useRef(0);\n const initializeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n const targetOrigin = useRef<string>('*');\n \n // Logging helper\n const log = useCallback((message: string, data?: unknown) => {\n if (debug) {\n if (data !== undefined) {\n console.log(`[McpProxyHost] ${message}`, data);\n } else {\n console.log(`[McpProxyHost] ${message}`);\n }\n }\n }, [debug]);\n \n // Send JSON-RPC message\n const send = useCallback((message: JsonRpcMessage) => {\n const iframe = iframeRef.current;\n if (!iframe?.contentWindow) {\n log('Cannot send: iframe not ready');\n return;\n }\n \n log(`Sending: ${(message as JsonRpcRequest).method ?? 'response'}`, message);\n iframe.contentWindow.postMessage(message, targetOrigin.current);\n }, [log]);\n \n // Send request and wait for response\n const sendRequest = useCallback((method: string, params?: unknown, timeoutMs = 5000): Promise<unknown> => {\n const id = `host-${++nextRequestId.current}`;\n const request: JsonRpcRequest = { jsonrpc: '2.0', id, method, params };\n \n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n pendingRequests.current.delete(id);\n reject(new Error(`Request timeout: ${method}`));\n }, timeoutMs);\n \n pendingRequests.current.set(id, { resolve, reject, timer });\n send(request);\n });\n }, [send]);\n \n // Send notification\n const sendNotification = useCallback((method: string, params?: unknown) => {\n send({ jsonrpc: '2.0', method, params });\n }, [send]);\n \n // Send response\n const sendResponse = useCallback((id: JsonRpcId, result: unknown) => {\n send({ jsonrpc: '2.0', id, result });\n }, [send]);\n \n // Send error response\n const sendError = useCallback((id: JsonRpcId, code: number, message: string, data?: unknown) => {\n send({ jsonrpc: '2.0', id, error: { code, message, data } });\n }, [send]);\n \n // Send initialization\n const sendInitialize = useCallback(() => {\n const params: UiInitializeParams = {\n protocolVersion: 'mcp-apps/0.1',\n appInfo,\n hostCapabilities,\n hostContext,\n };\n \n log('Sending ui/initialize', params);\n sendRequest(McpMethods.INITIALIZE, params, 2000).catch(() => {\n // Retry if not initialized\n if (!isInitialized && initializeRetries.current < 5) {\n initializeRetries.current++;\n initializeTimer.current = setTimeout(sendInitialize, 300);\n }\n });\n }, [appInfo, hostCapabilities, hostContext, sendRequest, isInitialized, log]);\n \n // Handle incoming messages\n useEffect(() => {\n const handleMessage = (event: MessageEvent) => {\n const data = event.data;\n if (!data || typeof data !== 'object' || data.jsonrpc !== '2.0') return;\n \n // Learn origin\n if (targetOrigin.current === '*' && event.origin) {\n targetOrigin.current = event.origin;\n log(`Learned target origin: ${targetOrigin.current}`);\n }\n \n // Handle response to our request\n if ('id' in data && !('method' in data)) {\n const pending = pendingRequests.current.get(data.id as JsonRpcId);\n if (pending) {\n if (pending.timer) clearTimeout(pending.timer);\n pendingRequests.current.delete(data.id as JsonRpcId);\n \n if ('error' in data) {\n pending.reject(data.error);\n } else {\n pending.resolve(data.result);\n }\n }\n return;\n }\n \n // Handle requests/notifications from app\n const { method, params, id } = data as JsonRpcRequest;\n if (!method) return;\n \n log(`Received: ${method}`, params);\n \n const handleAsync = async () => {\n try {\n switch (method) {\n case McpMethods.INITIALIZED:\n setIsInitialized(true);\n initializeRetries.current = 0;\n if (initializeTimer.current) {\n clearTimeout(initializeTimer.current);\n initializeTimer.current = null;\n }\n onInitialized?.();\n break;\n \n case McpMethods.SIZE_CHANGE:\n const sizeParams = params as { width: number; height: number };\n setIframeSize(sizeParams);\n onSizeChange?.(sizeParams);\n break;\n \n case McpMethods.OPEN_LINK:\n const linkParams = params as { url: string };\n onOpenLink?.(linkParams.url);\n if (id !== undefined) sendResponse(id, { ok: true });\n break;\n \n case McpMethods.MESSAGE:\n const msgParams = params as { content: MessageContent[] };\n await onMessage?.(msgParams);\n if (id !== undefined) sendResponse(id, { ok: true });\n break;\n \n case McpMethods.TOOLS_CALL:\n const toolParams = params as { name: string; arguments?: Record<string, unknown> };\n if (onToolCall) {\n const result = await onToolCall(toolParams.name, toolParams.arguments);\n if (id !== undefined) sendResponse(id, result);\n } else {\n if (id !== undefined) sendError(id, -32601, 'Tool call handler not configured');\n }\n break;\n \n default:\n // Unknown method - acknowledge if request\n if (id !== undefined) {\n sendResponse(id, { ok: true, ignored: true });\n }\n }\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n log(`Error handling ${method}:`, error);\n onError?.(error);\n if (id !== undefined) {\n sendError(id, -32000, error.message);\n }\n }\n };\n \n handleAsync();\n };\n \n window.addEventListener('message', handleMessage);\n return () => window.removeEventListener('message', handleMessage);\n }, [log, sendResponse, sendError, onInitialized, onSizeChange, onOpenLink, onMessage, onToolCall, onError]);\n \n // Initialize on iframe load\n const handleIframeLoad = useCallback(() => {\n log('Iframe loaded, sending initialize');\n initializeRetries.current = 0;\n sendInitialize();\n }, [sendInitialize, log]);\n \n // Cleanup\n useEffect(() => {\n return () => {\n if (initializeTimer.current) {\n clearTimeout(initializeTimer.current);\n }\n pendingRequests.current.forEach(({ timer }) => {\n if (timer) clearTimeout(timer);\n });\n pendingRequests.current.clear();\n };\n }, []);\n \n // Build iframe src URL\n const iframeSrc = `${proxyUrl}?app=${encodeURIComponent(appUrl)}`;\n \n // Expose ref methods\n React.useImperativeHandle(ref, () => ({\n sendToolInputPartial: (params: ToolInputPartialParams) => {\n sendNotification(McpMethods.TOOL_INPUT_PARTIAL, params);\n },\n sendToolInput: (params: ToolInputParams) => {\n sendNotification(McpMethods.TOOL_INPUT, params);\n },\n sendToolResult: (params: ToolResultParams) => {\n sendNotification(McpMethods.TOOL_RESULT, params);\n },\n sendHostContextChanged: (context: HostContext) => {\n sendNotification(McpMethods.HOST_CONTEXT_CHANGED, context);\n },\n sendResourceTeardown: () => {\n sendNotification(McpMethods.RESOURCE_TEARDOWN, {});\n },\n getIframe: () => iframeRef.current,\n isInitialized: () => isInitialized,\n }), [sendNotification, isInitialized]);\n \n // Calculate height\n const computedHeight = height === 'auto' && iframeSize \n ? `${iframeSize.height}px` \n : height;\n \n return (\n <div \n className={className} \n style={{\n width: typeof width === 'number' ? `${width}px` : width,\n height: computedHeight === 'auto' ? undefined : (typeof computedHeight === 'number' ? `${computedHeight}px` : computedHeight),\n ...style,\n }}\n >\n <iframe\n ref={iframeRef}\n src={iframeSrc}\n sandbox={sandboxPermissions.join(' ')}\n onLoad={handleIframeLoad}\n style={{\n width: '100%',\n height: computedHeight === 'auto' ? (iframeSize ? `${iframeSize.height}px` : '100%') : '100%',\n border: 'none',\n ...iframeStyle,\n }}\n title=\"MCP App\"\n />\n </div>\n );\n }\n);\n\n"]}