@botdojo/chat-sdk 0.0.25 → 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,453 @@
1
1
  import 'react';
2
2
  import 'react-dom';
3
- export * from 'mcp-app-view';
3
+
4
+ // ../../node_modules/.pnpm/mcp-app-view@0.1.5_react@18.3.1/node_modules/mcp-app-view/dist/index.mjs
5
+ var McpTransport = class {
6
+ constructor(options = {}) {
7
+ var _a, _b, _c, _d;
8
+ this.targetWindow = null;
9
+ this.targetOrigin = "*";
10
+ this.learnedOrigin = null;
11
+ this.pendingRequests = /* @__PURE__ */ new Map();
12
+ this.nextRequestId = 0;
13
+ this.messageHandler = null;
14
+ this.boundHandleMessage = null;
15
+ this.started = false;
16
+ this.targetOrigin = (_a = options.targetOrigin) != null ? _a : "*";
17
+ this.requestTimeout = (_b = options.requestTimeout) != null ? _b : 3e4;
18
+ this.debug = (_c = options.debug) != null ? _c : false;
19
+ if (typeof window !== "undefined") {
20
+ this.targetWindow = (_d = options.targetWindow) != null ? _d : window.parent;
21
+ }
22
+ }
23
+ /**
24
+ * Start listening for messages
25
+ */
26
+ start(handler) {
27
+ if (this.started)
28
+ return;
29
+ if (typeof window === "undefined")
30
+ return;
31
+ this.messageHandler = handler;
32
+ this.boundHandleMessage = this.handleMessage.bind(this);
33
+ window.addEventListener("message", this.boundHandleMessage);
34
+ this.started = true;
35
+ this.log("Transport started");
36
+ }
37
+ /**
38
+ * Stop listening for messages
39
+ */
40
+ stop() {
41
+ if (!this.started)
42
+ return;
43
+ if (typeof window === "undefined")
44
+ return;
45
+ if (this.boundHandleMessage) {
46
+ window.removeEventListener("message", this.boundHandleMessage);
47
+ }
48
+ this.pendingRequests.forEach(({ timer, reject }) => {
49
+ if (timer)
50
+ clearTimeout(timer);
51
+ reject(new Error("Transport stopped"));
52
+ });
53
+ this.pendingRequests.clear();
54
+ this.messageHandler = null;
55
+ this.boundHandleMessage = null;
56
+ this.started = false;
57
+ this.log("Transport stopped");
58
+ }
59
+ /**
60
+ * Send a JSON-RPC request and wait for response
61
+ */
62
+ sendRequest(method, params, timeoutMs) {
63
+ const id = `mcp-${++this.nextRequestId}`;
64
+ const request = {
65
+ jsonrpc: "2.0",
66
+ id,
67
+ method,
68
+ params
69
+ };
70
+ const timeout = timeoutMs != null ? timeoutMs : this.requestTimeout;
71
+ return new Promise((resolve, reject) => {
72
+ const timer = setTimeout(() => {
73
+ this.pendingRequests.delete(id);
74
+ reject(new Error(`Request timeout: ${method}`));
75
+ }, timeout);
76
+ this.pendingRequests.set(id, { resolve, reject, timer });
77
+ this.send(request);
78
+ });
79
+ }
80
+ /**
81
+ * Send a JSON-RPC notification (no response expected)
82
+ */
83
+ sendNotification(method, params) {
84
+ const notification = {
85
+ jsonrpc: "2.0",
86
+ method,
87
+ params
88
+ };
89
+ this.send(notification);
90
+ }
91
+ /**
92
+ * Send a JSON-RPC success response
93
+ */
94
+ sendResponse(id, result) {
95
+ const response = {
96
+ jsonrpc: "2.0",
97
+ id,
98
+ result
99
+ };
100
+ this.send(response);
101
+ }
102
+ /**
103
+ * Send a JSON-RPC error response
104
+ */
105
+ sendError(id, code, message, data) {
106
+ const response = {
107
+ jsonrpc: "2.0",
108
+ id,
109
+ error: { code, message, data }
110
+ };
111
+ this.send(response);
112
+ }
113
+ /**
114
+ * Get the learned parent origin
115
+ */
116
+ getOrigin() {
117
+ var _a;
118
+ return (_a = this.learnedOrigin) != null ? _a : this.targetOrigin;
119
+ }
120
+ send(message) {
121
+ var _a, _b;
122
+ if (!this.targetWindow) {
123
+ this.log("Cannot send: no target window");
124
+ return;
125
+ }
126
+ const origin = (_a = this.learnedOrigin) != null ? _a : this.targetOrigin;
127
+ this.log(`Sending: ${(_b = message.method) != null ? _b : "response"}`, message);
128
+ this.targetWindow.postMessage(message, origin);
129
+ }
130
+ handleMessage(event) {
131
+ var _a, _b;
132
+ const data = event.data;
133
+ if (!data || typeof data !== "object" || data.jsonrpc !== "2.0") {
134
+ return;
135
+ }
136
+ if (!this.learnedOrigin && event.origin) {
137
+ this.learnedOrigin = event.origin;
138
+ this.log(`Learned origin: ${this.learnedOrigin}`);
139
+ }
140
+ this.log(`Received: ${(_a = data.method) != null ? _a : "response"}`, data);
141
+ if ("id" in data && !("method" in data)) {
142
+ const pending = this.pendingRequests.get(data.id);
143
+ if (pending) {
144
+ if (pending.timer)
145
+ clearTimeout(pending.timer);
146
+ this.pendingRequests.delete(data.id);
147
+ if ("error" in data) {
148
+ pending.reject(data.error);
149
+ } else {
150
+ pending.resolve(data.result);
151
+ }
152
+ }
153
+ return;
154
+ }
155
+ (_b = this.messageHandler) == null ? void 0 : _b.call(this, data);
156
+ }
157
+ log(message, data) {
158
+ if (this.debug) {
159
+ if (data !== void 0) {
160
+ console.log(`[McpTransport] ${message}`, data);
161
+ } else {
162
+ console.log(`[McpTransport] ${message}`);
163
+ }
164
+ }
165
+ }
166
+ };
167
+ var McpMethods = {
168
+ // Host → UI
169
+ INITIALIZE: "ui/initialize",
170
+ TOOL_INPUT_PARTIAL: "ui/notifications/tool-input-partial",
171
+ TOOL_INPUT: "ui/notifications/tool-input",
172
+ TOOL_RESULT: "ui/notifications/tool-result",
173
+ TOOL_CANCELLED: "ui/tool-cancelled",
174
+ HOST_CONTEXT_CHANGED: "ui/notifications/host-context-changed",
175
+ RESOURCE_TEARDOWN: "ui/resource-teardown",
176
+ // UI → Host
177
+ INITIALIZED: "ui/notifications/initialized",
178
+ SIZE_CHANGE: "ui/notifications/size-change",
179
+ OPEN_LINK: "ui/open-link",
180
+ MESSAGE: "ui/message",
181
+ TOOLS_CALL: "tools/call"
182
+ };
183
+ var EventEmitter = class {
184
+ constructor() {
185
+ this.listeners = /* @__PURE__ */ new Map();
186
+ }
187
+ on(event, listener) {
188
+ if (!this.listeners.has(event)) {
189
+ this.listeners.set(event, /* @__PURE__ */ new Set());
190
+ }
191
+ this.listeners.get(event).add(listener);
192
+ return () => {
193
+ var _a;
194
+ (_a = this.listeners.get(event)) == null ? void 0 : _a.delete(listener);
195
+ };
196
+ }
197
+ emit(event, data) {
198
+ var _a;
199
+ (_a = this.listeners.get(event)) == null ? void 0 : _a.forEach((listener) => {
200
+ try {
201
+ listener(data);
202
+ } catch (err) {
203
+ console.error(`[McpAppClient] Event handler error:`, err);
204
+ }
205
+ });
206
+ }
207
+ removeAllListeners() {
208
+ this.listeners.clear();
209
+ }
210
+ };
211
+ var McpAppClient = class {
212
+ constructor(options = {}) {
213
+ var _a;
214
+ this.emitter = new EventEmitter();
215
+ this._state = {
216
+ isInitialized: false,
217
+ appInfo: null,
218
+ hostCapabilities: null,
219
+ hostContext: null,
220
+ tool: {
221
+ name: null,
222
+ arguments: null,
223
+ result: null,
224
+ isStreaming: false
225
+ }
226
+ };
227
+ this.transport = new McpTransport(options);
228
+ this.autoAcknowledge = (_a = options.autoAcknowledge) != null ? _a : true;
229
+ }
230
+ // ===========================================================================
231
+ // Lifecycle
232
+ // ===========================================================================
233
+ /**
234
+ * Start the client and begin listening for messages
235
+ */
236
+ start() {
237
+ this.transport.start(this.handleMessage.bind(this));
238
+ this.transport.sendNotification("ui/notifications/client-ready", {});
239
+ }
240
+ /**
241
+ * Stop the client and cleanup
242
+ */
243
+ stop() {
244
+ this.transport.stop();
245
+ this.emitter.removeAllListeners();
246
+ this._state = {
247
+ isInitialized: false,
248
+ appInfo: null,
249
+ hostCapabilities: null,
250
+ hostContext: null,
251
+ tool: {
252
+ name: null,
253
+ arguments: null,
254
+ result: null,
255
+ isStreaming: false
256
+ }
257
+ };
258
+ }
259
+ // ===========================================================================
260
+ // State
261
+ // ===========================================================================
262
+ /**
263
+ * Get current client state
264
+ */
265
+ get state() {
266
+ return this._state;
267
+ }
268
+ /**
269
+ * Check if client is initialized
270
+ */
271
+ get isInitialized() {
272
+ return this._state.isInitialized;
273
+ }
274
+ // ===========================================================================
275
+ // Event Subscriptions
276
+ // ===========================================================================
277
+ /**
278
+ * Subscribe to an event
279
+ * @returns Unsubscribe function
280
+ */
281
+ on(event, listener) {
282
+ return this.emitter.on(event, listener);
283
+ }
284
+ // ===========================================================================
285
+ // UI → Host Actions (SEP-1865)
286
+ // ===========================================================================
287
+ /**
288
+ * Send ui/message to the host
289
+ */
290
+ async sendMessage(content) {
291
+ await this.transport.sendRequest(McpMethods.MESSAGE, { content });
292
+ }
293
+ /**
294
+ * Send ui/open-link to the host
295
+ */
296
+ async openLink(url) {
297
+ await this.transport.sendRequest(McpMethods.OPEN_LINK, { url });
298
+ }
299
+ /**
300
+ * Send ui/notifications/size-change to the host
301
+ */
302
+ reportSize(width, height) {
303
+ this.transport.sendNotification(McpMethods.SIZE_CHANGE, { width, height });
304
+ this.emitter.emit("sizeChange", { width, height });
305
+ }
306
+ /**
307
+ * Send tools/call to the host
308
+ */
309
+ async callTool(name, args) {
310
+ const result = await this.transport.sendRequest(McpMethods.TOOLS_CALL, {
311
+ name,
312
+ arguments: args
313
+ });
314
+ return result;
315
+ }
316
+ // ===========================================================================
317
+ // Raw Protocol Access
318
+ // ===========================================================================
319
+ /**
320
+ * Send a raw JSON-RPC request
321
+ */
322
+ sendRequest(method, params) {
323
+ return this.transport.sendRequest(method, params);
324
+ }
325
+ /**
326
+ * Send a raw JSON-RPC notification
327
+ */
328
+ sendNotification(method, params) {
329
+ this.transport.sendNotification(method, params);
330
+ }
331
+ /**
332
+ * Get the learned parent origin
333
+ */
334
+ getOrigin() {
335
+ return this.transport.getOrigin();
336
+ }
337
+ // ===========================================================================
338
+ // Internal Message Handling
339
+ // ===========================================================================
340
+ handleMessage(message) {
341
+ if (!("method" in message))
342
+ return;
343
+ const { method, params, id } = message;
344
+ switch (method) {
345
+ case McpMethods.INITIALIZE:
346
+ this.handleInitialize(params, id);
347
+ break;
348
+ case McpMethods.TOOL_INPUT_PARTIAL:
349
+ this.handleToolInputPartial(params);
350
+ break;
351
+ case McpMethods.TOOL_INPUT:
352
+ this.handleToolInput(params);
353
+ break;
354
+ case McpMethods.TOOL_RESULT:
355
+ this.handleToolResult(params);
356
+ break;
357
+ case McpMethods.HOST_CONTEXT_CHANGED:
358
+ this.handleHostContextChanged(params);
359
+ break;
360
+ case McpMethods.RESOURCE_TEARDOWN:
361
+ this.handleResourceTeardown(id);
362
+ break;
363
+ default:
364
+ if (id !== void 0) {
365
+ this.transport.sendResponse(id, { ok: true, ignored: true });
366
+ }
367
+ }
368
+ }
369
+ handleInitialize(params, id) {
370
+ this._state = {
371
+ ...this._state,
372
+ isInitialized: true,
373
+ appInfo: params.appInfo,
374
+ hostCapabilities: params.hostCapabilities,
375
+ hostContext: params.hostContext
376
+ };
377
+ if (id !== void 0) {
378
+ this.transport.sendResponse(id, { ok: true });
379
+ }
380
+ if (this.autoAcknowledge) {
381
+ this.transport.sendNotification(McpMethods.INITIALIZED, {});
382
+ }
383
+ this.emitter.emit("initialize", params);
384
+ this.emitter.emit("initialized", void 0);
385
+ }
386
+ handleToolInputPartial(params) {
387
+ const args = params.arguments;
388
+ if (args === "" || args === null || typeof args !== "object") {
389
+ return;
390
+ }
391
+ const validArgs = args;
392
+ this._state = {
393
+ ...this._state,
394
+ tool: {
395
+ name: params.tool.name,
396
+ arguments: { ...this._state.tool.arguments, ...validArgs },
397
+ result: null,
398
+ isStreaming: true
399
+ }
400
+ };
401
+ this.emitter.emit("toolInputPartial", params);
402
+ }
403
+ handleToolInput(params) {
404
+ const args = params.arguments;
405
+ if (args === "" || args === null || typeof args !== "object") {
406
+ return;
407
+ }
408
+ const validArgs = args;
409
+ this._state = {
410
+ ...this._state,
411
+ tool: {
412
+ name: params.tool.name,
413
+ arguments: validArgs,
414
+ result: null,
415
+ isStreaming: true
416
+ }
417
+ };
418
+ this.emitter.emit("toolInput", params);
419
+ }
420
+ handleToolResult(params) {
421
+ const result = params.result;
422
+ if (result === "" || result === void 0) {
423
+ return;
424
+ }
425
+ this._state = {
426
+ ...this._state,
427
+ tool: {
428
+ ...this._state.tool,
429
+ name: params.tool.name,
430
+ result,
431
+ isStreaming: false
432
+ }
433
+ };
434
+ this.emitter.emit("toolResult", params);
435
+ }
436
+ handleHostContextChanged(params) {
437
+ this._state = {
438
+ ...this._state,
439
+ hostContext: { ...this._state.hostContext, ...params }
440
+ };
441
+ this.emitter.emit("hostContextChanged", params);
442
+ }
443
+ handleResourceTeardown(id) {
444
+ if (id !== void 0) {
445
+ this.transport.sendResponse(id, { ok: true });
446
+ }
447
+ this.emitter.emit("resourceTeardown", void 0);
448
+ }
449
+ };
450
+
451
+ export { McpAppClient, McpMethods, McpTransport };
4
452
  //# sourceMappingURL=out.js.map
5
453
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/mcp-app-view/index.ts"],"names":[],"mappings":";;;;;;;;;AACA,cAAc","sourcesContent":["// Re-export mcp-app-view main module\nexport * from 'mcp-app-view';\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/transport.ts","../../../../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/protocol/client.ts"],"names":[],"mappings":";;;;;;;;;AAqCO,IAAM,eAAN,MAAmB;EAaxB,YAAY,UAA4B,CAAA,GAAI;;AAZ5C,SAAQ,eAA8B;AACtC,SAAQ,eAAuB;AAC/B,SAAQ,gBAA+B;AAIvC,SAAQ,kBAAA,oBAAsB,IAAA;AAC9B,SAAQ,gBAAgB;AACxB,SAAQ,iBAAwC;AAChD,SAAQ,qBAA6D;AACrE,SAAQ,UAAU;AAGhB,SAAK,gBAAe,aAAQ,iBAAR,YAAwB;AAC5C,SAAK,kBAAiB,aAAQ,mBAAR,YAA0B;AAChD,SAAK,SAAQ,aAAQ,UAAR,YAAiB;AAG9B,QAAI,OAAO,WAAW,aAAa;AACjC,WAAK,gBAAe,aAAQ,iBAAR,YAAwB,OAAO;IACr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;MAAA;IACf;AAGF,SAAK,QAAQ,KAAK,oBAAoB,MAAM;EAC9C;EAEQ,gBAAgB,QAA+B;AAGrD,UAAM,OAAO,OAAO;AACpB,QAAI,SAAS,MAAM,SAAS,QAAQ,OAAO,SAAS,UAAU;AAE5D;IACF;AACA,UAAM,YAAY;AAElB,SAAK,SAAS;MACZ,GAAG,KAAK;MACR,MAAM;QACJ,MAAM,OAAO,KAAK;QAClB,WAAW;QACX,QAAQ;QACR,aAAa;MAAA;IACf;AAGF,SAAK,QAAQ,KAAK,aAAa,MAAM;EACvC;EAEQ,iBAAiB,QAAgC;AAEvD,UAAM,SAAS,OAAO;AACtB,QAAI,WAAW,MAAM,WAAW,QAAW;AAEzC;IACF;AAEA,SAAK,SAAS;MACZ,GAAG,KAAK;MACR,MAAM;QACJ,GAAG,KAAK,OAAO;QACf,MAAM,OAAO,KAAK;QAClB;QACA,aAAa;MAAA;IACf;AAGF,SAAK,QAAQ,KAAK,cAAc,MAAM;EACxC;EAEQ,yBAAyB,QAA2B;AAC1D,SAAK,SAAS;MACZ,GAAG,KAAK;MACR,aAAa,EAAE,GAAG,KAAK,OAAO,aAAa,GAAG,OAAA;IAAO;AAGvD,SAAK,QAAQ,KAAK,sBAAsB,MAAM;EAChD;EAEQ,uBAAuB,IAA4B;AAEzD,QAAI,OAAO,QAAW;AACpB,WAAK,UAAU,aAAa,IAAI,EAAE,IAAI,KAAA,CAAM;IAC9C;AAEA,SAAK,QAAQ,KAAK,oBAAoB,MAAS;EACjD;AACF","sourcesContent":["/**\n * PostMessage Transport for MCP Apps\n * Handles JSON-RPC 2.0 communication with the host via postMessage\n */\n\nimport type {\n JsonRpcId,\n JsonRpcMessage,\n JsonRpcRequest,\n JsonRpcNotification,\n JsonRpcSuccess,\n JsonRpcError,\n} from './types';\n\nexport interface PendingRequest {\n resolve: (value: unknown) => void;\n reject: (reason: unknown) => void;\n timer?: ReturnType<typeof setTimeout>;\n}\n\nexport interface TransportOptions {\n /** Target window to send messages to (default: window.parent) */\n targetWindow?: Window;\n /** Target origin for postMessage (default: '*') */\n targetOrigin?: string;\n /** Timeout for requests in ms (default: 30000) */\n requestTimeout?: number;\n /** Enable debug logging */\n debug?: boolean;\n}\n\nexport type MessageHandler = (message: JsonRpcMessage) => void;\n\n/**\n * PostMessage transport layer for MCP Apps\n * Handles sending/receiving JSON-RPC 2.0 messages via postMessage\n */\nexport class McpTransport {\n private targetWindow: Window | null = null;\n private targetOrigin: string = '*';\n private learnedOrigin: string | null = null;\n private requestTimeout: number;\n private debug: boolean;\n \n private pendingRequests = new Map<JsonRpcId, PendingRequest>();\n private nextRequestId = 0;\n private messageHandler: MessageHandler | null = null;\n private boundHandleMessage: ((event: MessageEvent) => void) | null = null;\n private started = false;\n \n constructor(options: TransportOptions = {}) {\n this.targetOrigin = options.targetOrigin ?? '*';\n this.requestTimeout = options.requestTimeout ?? 30000;\n this.debug = options.debug ?? false;\n \n // Set target window (default to parent in browser)\n if (typeof window !== 'undefined') {\n this.targetWindow = options.targetWindow ?? window.parent;\n }\n }\n \n /**\n * Start listening for messages\n */\n start(handler: MessageHandler): void {\n if (this.started) return;\n if (typeof window === 'undefined') return;\n \n this.messageHandler = handler;\n this.boundHandleMessage = this.handleMessage.bind(this);\n window.addEventListener('message', this.boundHandleMessage);\n this.started = true;\n \n this.log('Transport started');\n }\n \n /**\n * Stop listening for messages\n */\n stop(): void {\n if (!this.started) return;\n if (typeof window === 'undefined') return;\n \n if (this.boundHandleMessage) {\n window.removeEventListener('message', this.boundHandleMessage);\n }\n \n // Clear pending requests\n this.pendingRequests.forEach(({ timer, reject }) => {\n if (timer) clearTimeout(timer);\n reject(new Error('Transport stopped'));\n });\n this.pendingRequests.clear();\n \n this.messageHandler = null;\n this.boundHandleMessage = null;\n this.started = false;\n \n this.log('Transport stopped');\n }\n \n /**\n * Send a JSON-RPC request and wait for response\n */\n sendRequest(method: string, params?: unknown, timeoutMs?: number): Promise<unknown> {\n const id = `mcp-${++this.nextRequestId}`;\n const request: JsonRpcRequest = {\n jsonrpc: '2.0',\n id,\n method,\n params,\n };\n \n const timeout = timeoutMs ?? this.requestTimeout;\n \n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this.pendingRequests.delete(id);\n reject(new Error(`Request timeout: ${method}`));\n }, timeout);\n \n this.pendingRequests.set(id, { resolve, reject, timer });\n this.send(request);\n });\n }\n \n /**\n * Send a JSON-RPC notification (no response expected)\n */\n sendNotification(method: string, params?: unknown): void {\n const notification: JsonRpcNotification = {\n jsonrpc: '2.0',\n method,\n params,\n };\n this.send(notification);\n }\n \n /**\n * Send a JSON-RPC success response\n */\n sendResponse(id: JsonRpcId, result: unknown): void {\n const response: JsonRpcSuccess = {\n jsonrpc: '2.0',\n id,\n result,\n };\n this.send(response);\n }\n \n /**\n * Send a JSON-RPC error response\n */\n sendError(id: JsonRpcId, code: number, message: string, data?: unknown): void {\n const response: JsonRpcError = {\n jsonrpc: '2.0',\n id,\n error: { code, message, data },\n };\n this.send(response);\n }\n \n /**\n * Get the learned parent origin\n */\n getOrigin(): string {\n return this.learnedOrigin ?? this.targetOrigin;\n }\n \n private send(message: JsonRpcMessage): void {\n if (!this.targetWindow) {\n this.log('Cannot send: no target window');\n return;\n }\n \n const origin = this.learnedOrigin ?? this.targetOrigin;\n this.log(`Sending: ${(message as JsonRpcRequest | JsonRpcNotification).method ?? 'response'}`, message);\n this.targetWindow.postMessage(message, origin);\n }\n \n private handleMessage(event: MessageEvent): void {\n const data = event.data;\n \n // Validate JSON-RPC message\n if (!data || typeof data !== 'object' || data.jsonrpc !== '2.0') {\n return;\n }\n \n // Learn origin from first valid message\n if (!this.learnedOrigin && event.origin) {\n this.learnedOrigin = event.origin;\n this.log(`Learned origin: ${this.learnedOrigin}`);\n }\n \n this.log(`Received: ${data.method ?? 'response'}`, data);\n \n // Handle response to our request\n if ('id' in data && !('method' in data)) {\n const pending = this.pendingRequests.get(data.id as JsonRpcId);\n if (pending) {\n if (pending.timer) clearTimeout(pending.timer);\n this.pendingRequests.delete(data.id as JsonRpcId);\n \n if ('error' in data) {\n pending.reject((data as JsonRpcError).error);\n } else {\n pending.resolve((data as JsonRpcSuccess).result);\n }\n }\n return;\n }\n \n // Forward to message handler\n this.messageHandler?.(data as JsonRpcMessage);\n }\n \n private log(message: string, data?: unknown): void {\n if (this.debug) {\n if (data !== undefined) {\n console.log(`[McpTransport] ${message}`, data);\n } else {\n console.log(`[McpTransport] ${message}`);\n }\n }\n }\n}\n\n","/**\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 * MCP App Client - Framework-agnostic client for MCP Apps\n * Implements SEP-1865 protocol\n */\n\nimport { McpTransport, type TransportOptions } from './transport';\nimport {\n McpMethods,\n type JsonRpcMessage,\n type JsonRpcRequest,\n type AppInfo,\n type HostCapabilities,\n type HostContext,\n type UiInitializeParams,\n type ToolInputPartialParams,\n type ToolInputParams,\n type ToolResultParams,\n type MessageContent,\n type McpEventMap,\n type McpEventType,\n} from './types';\n\n// =============================================================================\n// Event Emitter\n// =============================================================================\n\ntype EventListener<T> = (data: T) => void;\n\nclass EventEmitter<TEvents extends Record<string, unknown>> {\n private listeners = new Map<keyof TEvents, Set<EventListener<unknown>>>();\n \n on<K extends keyof TEvents>(event: K, listener: EventListener<TEvents[K]>): () => void {\n if (!this.listeners.has(event)) {\n this.listeners.set(event, new Set());\n }\n this.listeners.get(event)!.add(listener as EventListener<unknown>);\n \n return () => {\n this.listeners.get(event)?.delete(listener as EventListener<unknown>);\n };\n }\n \n emit<K extends keyof TEvents>(event: K, data: TEvents[K]): void {\n this.listeners.get(event)?.forEach(listener => {\n try {\n listener(data);\n } catch (err) {\n console.error(`[McpAppClient] Event handler error:`, err);\n }\n });\n }\n \n removeAllListeners(): void {\n this.listeners.clear();\n }\n}\n\n// =============================================================================\n// MCP App Client\n// =============================================================================\n\nexport interface McpAppClientOptions extends TransportOptions {\n /** Auto-acknowledge initialization (default: true) */\n autoAcknowledge?: boolean;\n}\n\nexport interface McpAppClientState {\n isInitialized: boolean;\n appInfo: AppInfo | null;\n hostCapabilities: HostCapabilities | null;\n hostContext: HostContext | null;\n tool: {\n name: string | null;\n arguments: Record<string, unknown> | null;\n result: unknown | null;\n isStreaming: boolean;\n };\n}\n\n/**\n * MCP App Client - Framework-agnostic implementation\n * \n * @example\n * ```ts\n * const client = new McpAppClient({ debug: true });\n * \n * client.on('initialize', (params) => {\n * console.log('Initialized:', params.appInfo);\n * });\n * \n * client.on('toolInput', (params) => {\n * console.log('Tool:', params.tool.name, params.arguments);\n * });\n * \n * client.start();\n * \n * // Send messages\n * await client.sendMessage([{ type: 'text', text: 'Hello!' }]);\n * await client.callTool('myTool', { arg: 'value' });\n * ```\n */\nexport class McpAppClient {\n private transport: McpTransport;\n private emitter = new EventEmitter<McpEventMap>();\n private autoAcknowledge: boolean;\n private _state: McpAppClientState = {\n isInitialized: false,\n appInfo: null,\n hostCapabilities: null,\n hostContext: null,\n tool: {\n name: null,\n arguments: null,\n result: null,\n isStreaming: false,\n },\n };\n \n constructor(options: McpAppClientOptions = {}) {\n this.transport = new McpTransport(options);\n this.autoAcknowledge = options.autoAcknowledge ?? true;\n }\n \n // ===========================================================================\n // Lifecycle\n // ===========================================================================\n \n /**\n * Start the client and begin listening for messages\n */\n start(): void {\n this.transport.start(this.handleMessage.bind(this));\n // Signal to proxy/host that we're ready to receive messages\n // This allows the proxy to queue messages until the client is listening\n this.transport.sendNotification('ui/notifications/client-ready', {});\n }\n \n /**\n * Stop the client and cleanup\n */\n stop(): void {\n this.transport.stop();\n this.emitter.removeAllListeners();\n this._state = {\n isInitialized: false,\n appInfo: null,\n hostCapabilities: null,\n hostContext: null,\n tool: {\n name: null,\n arguments: null,\n result: null,\n isStreaming: false,\n },\n };\n }\n \n // ===========================================================================\n // State\n // ===========================================================================\n \n /**\n * Get current client state\n */\n get state(): Readonly<McpAppClientState> {\n return this._state;\n }\n \n /**\n * Check if client is initialized\n */\n get isInitialized(): boolean {\n return this._state.isInitialized;\n }\n \n // ===========================================================================\n // Event Subscriptions\n // ===========================================================================\n \n /**\n * Subscribe to an event\n * @returns Unsubscribe function\n */\n on<K extends McpEventType>(event: K, listener: EventListener<McpEventMap[K]>): () => void {\n return this.emitter.on(event, listener);\n }\n \n // ===========================================================================\n // UI → Host Actions (SEP-1865)\n // ===========================================================================\n \n /**\n * Send ui/message to the host\n */\n async sendMessage(content: MessageContent[]): Promise<void> {\n await this.transport.sendRequest(McpMethods.MESSAGE, { content });\n }\n \n /**\n * Send ui/open-link to the host\n */\n async openLink(url: string): Promise<void> {\n await this.transport.sendRequest(McpMethods.OPEN_LINK, { url });\n }\n \n /**\n * Send ui/notifications/size-change to the host\n */\n reportSize(width: number, height: number): void {\n this.transport.sendNotification(McpMethods.SIZE_CHANGE, { width, height });\n this.emitter.emit('sizeChange', { width, height });\n }\n \n /**\n * Send tools/call to the host\n */\n async callTool<T = unknown>(name: string, args?: Record<string, unknown>): Promise<T> {\n const result = await this.transport.sendRequest(McpMethods.TOOLS_CALL, {\n name,\n arguments: args,\n });\n return result as T;\n }\n \n // ===========================================================================\n // Raw Protocol Access\n // ===========================================================================\n \n /**\n * Send a raw JSON-RPC request\n */\n sendRequest(method: string, params?: unknown): Promise<unknown> {\n return this.transport.sendRequest(method, params);\n }\n \n /**\n * Send a raw JSON-RPC notification\n */\n sendNotification(method: string, params?: unknown): void {\n this.transport.sendNotification(method, params);\n }\n \n /**\n * Get the learned parent origin\n */\n getOrigin(): string {\n return this.transport.getOrigin();\n }\n \n // ===========================================================================\n // Internal Message Handling\n // ===========================================================================\n \n private handleMessage(message: JsonRpcMessage): void {\n // Only handle requests and notifications (not responses)\n if (!('method' in message)) return;\n \n const { method, params, id } = message as JsonRpcRequest;\n \n switch (method) {\n case McpMethods.INITIALIZE:\n this.handleInitialize(params as UiInitializeParams, id);\n break;\n \n case McpMethods.TOOL_INPUT_PARTIAL:\n this.handleToolInputPartial(params as ToolInputPartialParams);\n break;\n \n case McpMethods.TOOL_INPUT:\n this.handleToolInput(params as ToolInputParams);\n break;\n \n case McpMethods.TOOL_RESULT:\n this.handleToolResult(params as ToolResultParams);\n break;\n \n case McpMethods.HOST_CONTEXT_CHANGED:\n this.handleHostContextChanged(params as HostContext);\n break;\n \n case McpMethods.RESOURCE_TEARDOWN:\n this.handleResourceTeardown(id);\n break;\n \n default:\n // Unknown method - send acknowledgment if request\n if (id !== undefined) {\n this.transport.sendResponse(id, { ok: true, ignored: true });\n }\n }\n }\n \n private handleInitialize(params: UiInitializeParams, id?: string | number): void {\n this._state = {\n ...this._state,\n isInitialized: true,\n appInfo: params.appInfo,\n hostCapabilities: params.hostCapabilities,\n hostContext: params.hostContext,\n };\n \n // Respond to request\n if (id !== undefined) {\n this.transport.sendResponse(id, { ok: true });\n }\n \n // Auto-send initialized notification\n if (this.autoAcknowledge) {\n this.transport.sendNotification(McpMethods.INITIALIZED, {});\n }\n \n this.emitter.emit('initialize', params);\n this.emitter.emit('initialized', undefined);\n }\n \n private handleToolInputPartial(params: ToolInputPartialParams): void {\n // Validate arguments - must be an object, not empty string\n // Cast to unknown first since runtime data may not match types\n const args = params.arguments as unknown;\n if (args === '' || args === null || typeof args !== 'object') {\n // Skip invalid arguments - server may send empty string during streaming\n return;\n }\n const validArgs = args as Record<string, unknown>;\n \n this._state = {\n ...this._state,\n tool: {\n name: params.tool.name,\n arguments: { ...this._state.tool.arguments, ...validArgs },\n result: null,\n isStreaming: true,\n },\n };\n \n this.emitter.emit('toolInputPartial', params);\n }\n \n private handleToolInput(params: ToolInputParams): void {\n // Validate arguments - must be an object, not empty string\n // Cast to unknown first since runtime data may not match types\n const args = params.arguments as unknown;\n if (args === '' || args === null || typeof args !== 'object') {\n // Skip invalid arguments - server may send empty string during streaming\n return;\n }\n const validArgs = args as Record<string, unknown>;\n \n this._state = {\n ...this._state,\n tool: {\n name: params.tool.name,\n arguments: validArgs,\n result: null,\n isStreaming: true,\n },\n };\n \n this.emitter.emit('toolInput', params);\n }\n \n private handleToolResult(params: ToolResultParams): void {\n // Validate result - skip if empty string (server may send empty string during streaming)\n const result = params.result;\n if (result === '' || result === undefined) {\n // Skip invalid result\n return;\n }\n \n this._state = {\n ...this._state,\n tool: {\n ...this._state.tool,\n name: params.tool.name,\n result: result,\n isStreaming: false,\n },\n };\n \n this.emitter.emit('toolResult', params);\n }\n \n private handleHostContextChanged(params: HostContext): void {\n this._state = {\n ...this._state,\n hostContext: { ...this._state.hostContext, ...params },\n };\n \n this.emitter.emit('hostContextChanged', params);\n }\n \n private handleResourceTeardown(id?: string | number): void {\n // Respond to request if needed\n if (id !== undefined) {\n this.transport.sendResponse(id, { ok: true });\n }\n \n this.emitter.emit('resourceTeardown', undefined);\n }\n}\n\n"]}