@botdojo/chat-sdk 0.0.16 → 0.0.17

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,996 +1,5 @@
1
- import __React, { createContext, useRef, useState, useEffect, useContext, useCallback } from 'react';
1
+ import 'react';
2
2
  import 'react-dom';
3
- import { jsx } from 'react/jsx-runtime';
4
-
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
- HOST_CONTEXT_CHANGED: "ui/notifications/host-context-changed",
174
- RESOURCE_TEARDOWN: "ui/resource-teardown",
175
- // UI → Host
176
- INITIALIZED: "ui/notifications/initialized",
177
- SIZE_CHANGE: "ui/notifications/size-change",
178
- OPEN_LINK: "ui/open-link",
179
- MESSAGE: "ui/message",
180
- TOOLS_CALL: "tools/call"
181
- };
182
- var EventEmitter = class {
183
- constructor() {
184
- this.listeners = /* @__PURE__ */ new Map();
185
- }
186
- on(event, listener) {
187
- if (!this.listeners.has(event)) {
188
- this.listeners.set(event, /* @__PURE__ */ new Set());
189
- }
190
- this.listeners.get(event).add(listener);
191
- return () => {
192
- var _a;
193
- (_a = this.listeners.get(event)) == null ? void 0 : _a.delete(listener);
194
- };
195
- }
196
- emit(event, data) {
197
- var _a;
198
- (_a = this.listeners.get(event)) == null ? void 0 : _a.forEach((listener) => {
199
- try {
200
- listener(data);
201
- } catch (err) {
202
- console.error(`[McpAppClient] Event handler error:`, err);
203
- }
204
- });
205
- }
206
- removeAllListeners() {
207
- this.listeners.clear();
208
- }
209
- };
210
- var McpAppClient = class {
211
- constructor(options = {}) {
212
- var _a;
213
- this.emitter = new EventEmitter();
214
- this._state = {
215
- isInitialized: false,
216
- appInfo: null,
217
- hostCapabilities: null,
218
- hostContext: null,
219
- tool: {
220
- name: null,
221
- arguments: null,
222
- result: null,
223
- isStreaming: false
224
- }
225
- };
226
- this.transport = new McpTransport(options);
227
- this.autoAcknowledge = (_a = options.autoAcknowledge) != null ? _a : true;
228
- }
229
- // ===========================================================================
230
- // Lifecycle
231
- // ===========================================================================
232
- /**
233
- * Start the client and begin listening for messages
234
- */
235
- start() {
236
- this.transport.start(this.handleMessage.bind(this));
237
- this.transport.sendNotification("ui/notifications/client-ready", {});
238
- }
239
- /**
240
- * Stop the client and cleanup
241
- */
242
- stop() {
243
- this.transport.stop();
244
- this.emitter.removeAllListeners();
245
- this._state = {
246
- isInitialized: false,
247
- appInfo: null,
248
- hostCapabilities: null,
249
- hostContext: null,
250
- tool: {
251
- name: null,
252
- arguments: null,
253
- result: null,
254
- isStreaming: false
255
- }
256
- };
257
- }
258
- // ===========================================================================
259
- // State
260
- // ===========================================================================
261
- /**
262
- * Get current client state
263
- */
264
- get state() {
265
- return this._state;
266
- }
267
- /**
268
- * Check if client is initialized
269
- */
270
- get isInitialized() {
271
- return this._state.isInitialized;
272
- }
273
- // ===========================================================================
274
- // Event Subscriptions
275
- // ===========================================================================
276
- /**
277
- * Subscribe to an event
278
- * @returns Unsubscribe function
279
- */
280
- on(event, listener) {
281
- return this.emitter.on(event, listener);
282
- }
283
- // ===========================================================================
284
- // UI → Host Actions (SEP-1865)
285
- // ===========================================================================
286
- /**
287
- * Send ui/message to the host
288
- */
289
- async sendMessage(content) {
290
- await this.transport.sendRequest(McpMethods.MESSAGE, { content });
291
- }
292
- /**
293
- * Send ui/open-link to the host
294
- */
295
- async openLink(url) {
296
- await this.transport.sendRequest(McpMethods.OPEN_LINK, { url });
297
- }
298
- /**
299
- * Send ui/notifications/size-change to the host
300
- */
301
- reportSize(width, height) {
302
- this.transport.sendNotification(McpMethods.SIZE_CHANGE, { width, height });
303
- this.emitter.emit("sizeChange", { width, height });
304
- }
305
- /**
306
- * Send tools/call to the host
307
- */
308
- async callTool(name, args) {
309
- const result = await this.transport.sendRequest(McpMethods.TOOLS_CALL, {
310
- name,
311
- arguments: args
312
- });
313
- return result;
314
- }
315
- // ===========================================================================
316
- // Raw Protocol Access
317
- // ===========================================================================
318
- /**
319
- * Send a raw JSON-RPC request
320
- */
321
- sendRequest(method, params) {
322
- return this.transport.sendRequest(method, params);
323
- }
324
- /**
325
- * Send a raw JSON-RPC notification
326
- */
327
- sendNotification(method, params) {
328
- this.transport.sendNotification(method, params);
329
- }
330
- /**
331
- * Get the learned parent origin
332
- */
333
- getOrigin() {
334
- return this.transport.getOrigin();
335
- }
336
- // ===========================================================================
337
- // Internal Message Handling
338
- // ===========================================================================
339
- handleMessage(message) {
340
- if (!("method" in message))
341
- return;
342
- const { method, params, id } = message;
343
- switch (method) {
344
- case McpMethods.INITIALIZE:
345
- this.handleInitialize(params, id);
346
- break;
347
- case McpMethods.TOOL_INPUT_PARTIAL:
348
- this.handleToolInputPartial(params);
349
- break;
350
- case McpMethods.TOOL_INPUT:
351
- this.handleToolInput(params);
352
- break;
353
- case McpMethods.TOOL_RESULT:
354
- this.handleToolResult(params);
355
- break;
356
- case McpMethods.HOST_CONTEXT_CHANGED:
357
- this.handleHostContextChanged(params);
358
- break;
359
- case McpMethods.RESOURCE_TEARDOWN:
360
- this.handleResourceTeardown(id);
361
- break;
362
- default:
363
- if (id !== void 0) {
364
- this.transport.sendResponse(id, { ok: true, ignored: true });
365
- }
366
- }
367
- }
368
- handleInitialize(params, id) {
369
- this._state = {
370
- ...this._state,
371
- isInitialized: true,
372
- appInfo: params.appInfo,
373
- hostCapabilities: params.hostCapabilities,
374
- hostContext: params.hostContext
375
- };
376
- if (id !== void 0) {
377
- this.transport.sendResponse(id, { ok: true });
378
- }
379
- if (this.autoAcknowledge) {
380
- this.transport.sendNotification(McpMethods.INITIALIZED, {});
381
- }
382
- this.emitter.emit("initialize", params);
383
- this.emitter.emit("initialized", void 0);
384
- }
385
- handleToolInputPartial(params) {
386
- const args = params.arguments;
387
- if (args === "" || args === null || typeof args !== "object") {
388
- return;
389
- }
390
- const validArgs = args;
391
- this._state = {
392
- ...this._state,
393
- tool: {
394
- name: params.tool.name,
395
- arguments: { ...this._state.tool.arguments, ...validArgs },
396
- result: null,
397
- isStreaming: true
398
- }
399
- };
400
- this.emitter.emit("toolInputPartial", params);
401
- }
402
- handleToolInput(params) {
403
- const args = params.arguments;
404
- if (args === "" || args === null || typeof args !== "object") {
405
- return;
406
- }
407
- const validArgs = args;
408
- this._state = {
409
- ...this._state,
410
- tool: {
411
- name: params.tool.name,
412
- arguments: validArgs,
413
- result: null,
414
- isStreaming: true
415
- }
416
- };
417
- this.emitter.emit("toolInput", params);
418
- }
419
- handleToolResult(params) {
420
- const result = params.result;
421
- if (result === "" || result === void 0) {
422
- return;
423
- }
424
- this._state = {
425
- ...this._state,
426
- tool: {
427
- ...this._state.tool,
428
- name: params.tool.name,
429
- result,
430
- isStreaming: false
431
- }
432
- };
433
- this.emitter.emit("toolResult", params);
434
- }
435
- handleHostContextChanged(params) {
436
- this._state = {
437
- ...this._state,
438
- hostContext: { ...this._state.hostContext, ...params }
439
- };
440
- this.emitter.emit("hostContextChanged", params);
441
- }
442
- handleResourceTeardown(id) {
443
- if (id !== void 0) {
444
- this.transport.sendResponse(id, { ok: true });
445
- }
446
- this.emitter.emit("resourceTeardown", void 0);
447
- }
448
- };
449
- var McpAppContext = createContext(null);
450
- function McpAppProvider({
451
- children,
452
- clientOptions = {},
453
- onInitialize,
454
- onToolInput,
455
- onToolInputPartial,
456
- onToolResult,
457
- onHostContextChanged,
458
- onTeardown
459
- }) {
460
- const clientRef = useRef(null);
461
- if (!clientRef.current) {
462
- clientRef.current = new McpAppClient(clientOptions);
463
- }
464
- const client = clientRef.current;
465
- const [isInitialized, setIsInitialized] = useState(false);
466
- const [appInfo, setAppInfo] = useState(null);
467
- const [hostCapabilities, setHostCapabilities] = useState(null);
468
- const [hostContext, setHostContext] = useState(null);
469
- const [tool, setTool] = useState({
470
- name: null,
471
- arguments: null,
472
- result: null,
473
- isStreaming: false
474
- });
475
- useEffect(() => {
476
- if (!client)
477
- return;
478
- const unsubInit = client.on("initialize", (params) => {
479
- setIsInitialized(true);
480
- setAppInfo(params.appInfo);
481
- setHostCapabilities(params.hostCapabilities);
482
- setHostContext(params.hostContext);
483
- onInitialize == null ? void 0 : onInitialize(params.hostContext);
484
- });
485
- const unsubToolInputPartial = client.on("toolInputPartial", (params) => {
486
- setTool((prev) => ({
487
- name: params.tool.name,
488
- arguments: { ...prev.arguments, ...params.arguments },
489
- result: null,
490
- isStreaming: true
491
- }));
492
- onToolInputPartial == null ? void 0 : onToolInputPartial(params);
493
- });
494
- const unsubToolInput = client.on("toolInput", (params) => {
495
- setTool({
496
- name: params.tool.name,
497
- arguments: params.arguments,
498
- result: null,
499
- isStreaming: true
500
- });
501
- onToolInput == null ? void 0 : onToolInput(params);
502
- });
503
- const unsubToolResult = client.on("toolResult", (params) => {
504
- setTool((prev) => ({
505
- ...prev,
506
- name: params.tool.name,
507
- result: params.result,
508
- isStreaming: false
509
- }));
510
- onToolResult == null ? void 0 : onToolResult(params);
511
- });
512
- const unsubContextChanged = client.on("hostContextChanged", (params) => {
513
- setHostContext((prev) => ({ ...prev, ...params }));
514
- onHostContextChanged == null ? void 0 : onHostContextChanged(params);
515
- });
516
- const unsubTeardown = client.on("resourceTeardown", () => {
517
- onTeardown == null ? void 0 : onTeardown();
518
- });
519
- client.start();
520
- return () => {
521
- unsubInit();
522
- unsubToolInputPartial();
523
- unsubToolInput();
524
- unsubToolResult();
525
- unsubContextChanged();
526
- unsubTeardown();
527
- client.stop();
528
- };
529
- }, [client, onInitialize, onToolInput, onToolInputPartial, onToolResult, onHostContextChanged, onTeardown]);
530
- const contextValue = {
531
- client,
532
- isInitialized,
533
- appInfo,
534
- hostCapabilities,
535
- hostContext,
536
- tool,
537
- sendMessage: (content) => client.sendMessage(content),
538
- openLink: (url) => client.openLink(url),
539
- callTool: (name, args) => client.callTool(name, args),
540
- reportSize: (width, height) => client.reportSize(width, height)
541
- };
542
- return /* @__PURE__ */ jsx(McpAppContext.Provider, { value: contextValue, children });
543
- }
544
- function useMcpAppContext() {
545
- const context = useContext(McpAppContext);
546
- if (!context) {
547
- throw new Error("useMcpAppContext must be used within McpAppProvider");
548
- }
549
- return context;
550
- }
551
- function McpApp({
552
- children,
553
- className,
554
- style,
555
- autoReportSize = true,
556
- clientOptions,
557
- onInitialize,
558
- onToolInput,
559
- onToolInputPartial,
560
- onToolResult,
561
- onHostContextChanged,
562
- onTeardown
563
- }) {
564
- const containerRef = useRef(null);
565
- __React.useEffect(() => {
566
- if (!autoReportSize || !containerRef.current)
567
- return;
568
- }, [autoReportSize]);
569
- return /* @__PURE__ */ jsx(
570
- McpAppProvider,
571
- {
572
- clientOptions,
573
- onInitialize,
574
- onToolInput,
575
- onToolInputPartial,
576
- onToolResult,
577
- onHostContextChanged,
578
- onTeardown,
579
- children: /* @__PURE__ */ jsx("div", { ref: containerRef, className, style, children })
580
- }
581
- );
582
- }
583
- function useMcpApp(options = {}) {
584
- const {
585
- debug = false,
586
- containerRef,
587
- autoReportSize = !!containerRef,
588
- onToolInputPartial
589
- } = options;
590
- const clientRef = useRef(null);
591
- if (!clientRef.current) {
592
- clientRef.current = new McpAppClient({ debug });
593
- clientRef.current.start();
594
- }
595
- const client = clientRef.current;
596
- const onToolInputPartialRef = useRef(onToolInputPartial);
597
- onToolInputPartialRef.current = onToolInputPartial;
598
- const [isInitialized, setIsInitialized] = useState(false);
599
- const [appInfo, setAppInfo] = useState(null);
600
- const [hostCapabilities, setHostCapabilities] = useState(null);
601
- const [hostContext, setHostContext] = useState(null);
602
- const [tool, setTool] = useState({
603
- name: null,
604
- arguments: null,
605
- partialUpdate: null,
606
- toolProgress: null,
607
- result: null,
608
- status: "idle",
609
- isStreaming: false
610
- });
611
- useEffect(() => {
612
- if (!client)
613
- return;
614
- const unsubInit = client.on("initialize", (params) => {
615
- var _a, _b;
616
- setIsInitialized(true);
617
- setAppInfo(params.appInfo);
618
- setHostCapabilities(params.hostCapabilities);
619
- setHostContext(params.hostContext);
620
- const toolInfo = (_a = params.hostContext) == null ? void 0 : _a.toolInfo;
621
- if ((_b = toolInfo == null ? void 0 : toolInfo.tool) == null ? void 0 : _b.name) {
622
- setTool((prev) => ({
623
- ...prev,
624
- name: toolInfo.tool.name
625
- }));
626
- }
627
- });
628
- const unsubToolInputPartial = client.on("toolInputPartial", (params) => {
629
- var _a, _b;
630
- const isProgressUpdate = ((_a = params.arguments) == null ? void 0 : _a.kind) === "botdojo-tool-progress";
631
- (_b = onToolInputPartialRef.current) == null ? void 0 : _b.call(onToolInputPartialRef, params);
632
- if (isProgressUpdate) {
633
- setTool((prev) => ({
634
- ...prev,
635
- name: params.tool.name,
636
- toolProgress: params.arguments,
637
- status: "streaming",
638
- isStreaming: true
639
- }));
640
- } else {
641
- setTool((prev) => ({
642
- ...prev,
643
- name: params.tool.name,
644
- partialUpdate: params.arguments,
645
- status: "streaming",
646
- isStreaming: true
647
- }));
648
- }
649
- });
650
- const unsubToolInput = client.on("toolInput", (params) => {
651
- setTool((prev) => ({
652
- ...prev,
653
- name: params.tool.name,
654
- arguments: params.arguments,
655
- partialUpdate: null,
656
- result: null,
657
- status: "streaming",
658
- isStreaming: true
659
- }));
660
- });
661
- const unsubToolResult = client.on("toolResult", (params) => {
662
- setTool((prev) => ({
663
- ...prev,
664
- name: params.tool.name,
665
- result: params.result,
666
- toolProgress: null,
667
- status: "complete",
668
- isStreaming: false
669
- }));
670
- });
671
- const unsubContextChanged = client.on("hostContextChanged", (params) => {
672
- var _a, _b;
673
- setHostContext((prev) => ({ ...prev, ...params }));
674
- if ((_b = (_a = params == null ? void 0 : params.toolInfo) == null ? void 0 : _a.tool) == null ? void 0 : _b.name) {
675
- setTool((prev) => ({
676
- ...prev,
677
- name: params.toolInfo.tool.name
678
- }));
679
- }
680
- });
681
- const unsubTeardown = client.on("resourceTeardown", () => {
682
- setTool((prev) => ({
683
- ...prev,
684
- status: "teardown",
685
- isStreaming: false
686
- }));
687
- });
688
- const currentState = client.state;
689
- if (currentState.isInitialized) {
690
- setIsInitialized(true);
691
- setAppInfo(currentState.appInfo);
692
- setHostCapabilities(currentState.hostCapabilities);
693
- setHostContext(currentState.hostContext);
694
- if (currentState.tool.name || currentState.tool.arguments) {
695
- setTool({
696
- name: currentState.tool.name,
697
- arguments: currentState.tool.arguments,
698
- partialUpdate: null,
699
- toolProgress: null,
700
- result: currentState.tool.result,
701
- isStreaming: currentState.tool.isStreaming,
702
- status: currentState.tool.isStreaming ? "streaming" : currentState.tool.result ? "complete" : "idle"
703
- });
704
- }
705
- }
706
- return () => {
707
- unsubInit();
708
- unsubToolInputPartial();
709
- unsubToolInput();
710
- unsubToolResult();
711
- unsubContextChanged();
712
- unsubTeardown();
713
- client.stop();
714
- };
715
- }, [client]);
716
- useEffect(() => {
717
- if (!autoReportSize || !(containerRef == null ? void 0 : containerRef.current) || !client)
718
- return;
719
- const reportSize2 = () => {
720
- const el = containerRef.current;
721
- if (!el)
722
- return;
723
- const rect = el.getBoundingClientRect();
724
- const width = Math.ceil(rect.width);
725
- const height = Math.ceil(rect.height);
726
- if (width > 0 && height > 0) {
727
- client.reportSize(width, height);
728
- }
729
- };
730
- reportSize2();
731
- const observer = new ResizeObserver(reportSize2);
732
- observer.observe(containerRef.current);
733
- window.addEventListener("resize", reportSize2);
734
- return () => {
735
- observer.disconnect();
736
- window.removeEventListener("resize", reportSize2);
737
- };
738
- }, [autoReportSize, containerRef, client]);
739
- const sendMessage = useCallback(async (content) => {
740
- await client.sendMessage(content);
741
- }, [client]);
742
- const openLink = useCallback(async (url) => {
743
- await client.openLink(url);
744
- }, [client]);
745
- const callTool = useCallback(async (name, args) => {
746
- return client.callTool(name, args);
747
- }, [client]);
748
- const reportSize = useCallback((width, height) => {
749
- client.reportSize(width, height);
750
- }, [client]);
751
- const getArgumentValue = useCallback((key, fallback) => {
752
- var _a;
753
- const value = (_a = tool.arguments) == null ? void 0 : _a[key];
754
- return value != null ? value : fallback;
755
- }, [tool.arguments]);
756
- const getPartialUpdateValue = useCallback((key, fallback) => {
757
- var _a;
758
- const value = (_a = tool.partialUpdate) == null ? void 0 : _a[key];
759
- return value != null ? value : fallback;
760
- }, [tool.partialUpdate]);
761
- const getToolProgressValue = useCallback((key, fallback) => {
762
- var _a;
763
- const value = (_a = tool.toolProgress) == null ? void 0 : _a[key];
764
- return value != null ? value : fallback;
765
- }, [tool.toolProgress]);
766
- return {
767
- isInitialized,
768
- appInfo,
769
- hostCapabilities,
770
- hostContext,
771
- tool,
772
- sendMessage,
773
- openLink,
774
- callTool,
775
- reportSize,
776
- getArgumentValue,
777
- getPartialUpdateValue,
778
- getToolProgressValue,
779
- client
780
- };
781
- }
782
- function useMcpProtocol(options = {}) {
783
- var _a, _b;
784
- const { debug = false, autoAcknowledge = true } = options;
785
- const [isInitialized, setIsInitialized] = useState(false);
786
- const [appInfo, setAppInfo] = useState(null);
787
- const [hostCapabilities, setHostCapabilities] = useState(null);
788
- const [hostContext, setHostContext] = useState(null);
789
- const transportRef = useRef(null);
790
- const handlersRef = useRef({
791
- initialize: /* @__PURE__ */ new Set(),
792
- toolInputPartial: /* @__PURE__ */ new Set(),
793
- toolInput: /* @__PURE__ */ new Set(),
794
- toolResult: /* @__PURE__ */ new Set(),
795
- hostContextChanged: /* @__PURE__ */ new Set(),
796
- resourceTeardown: /* @__PURE__ */ new Set()
797
- });
798
- useEffect(() => {
799
- if (typeof window === "undefined")
800
- return;
801
- const transport = new McpTransport({ debug });
802
- transportRef.current = transport;
803
- const handleMessage = (message) => {
804
- if (!("method" in message))
805
- return;
806
- const { method, params, id } = message;
807
- switch (method) {
808
- case McpMethods.INITIALIZE: {
809
- const initParams = params;
810
- setIsInitialized(true);
811
- setAppInfo(initParams.appInfo);
812
- setHostCapabilities(initParams.hostCapabilities);
813
- setHostContext(initParams.hostContext);
814
- if (id !== void 0) {
815
- transport.sendResponse(id, { ok: true });
816
- }
817
- if (autoAcknowledge) {
818
- transport.sendNotification(McpMethods.INITIALIZED, {});
819
- }
820
- handlersRef.current.initialize.forEach((h) => h(initParams));
821
- break;
822
- }
823
- case McpMethods.TOOL_INPUT_PARTIAL: {
824
- const toolParams = params;
825
- handlersRef.current.toolInputPartial.forEach((h) => h(toolParams));
826
- break;
827
- }
828
- case McpMethods.TOOL_INPUT: {
829
- const toolParams = params;
830
- handlersRef.current.toolInput.forEach((h) => h(toolParams));
831
- break;
832
- }
833
- case McpMethods.TOOL_RESULT: {
834
- const resultParams = params;
835
- handlersRef.current.toolResult.forEach((h) => h(resultParams));
836
- break;
837
- }
838
- case McpMethods.HOST_CONTEXT_CHANGED: {
839
- const ctxParams = params;
840
- setHostContext((prev) => ({ ...prev, ...ctxParams }));
841
- handlersRef.current.hostContextChanged.forEach((h) => h(ctxParams));
842
- break;
843
- }
844
- case McpMethods.RESOURCE_TEARDOWN: {
845
- if (id !== void 0) {
846
- transport.sendResponse(id, { ok: true });
847
- }
848
- handlersRef.current.resourceTeardown.forEach((h) => h());
849
- break;
850
- }
851
- default:
852
- if (id !== void 0) {
853
- transport.sendResponse(id, { ok: true, ignored: true });
854
- }
855
- }
856
- };
857
- transport.start(handleMessage);
858
- return () => {
859
- transport.stop();
860
- transportRef.current = null;
861
- };
862
- }, [debug, autoAcknowledge]);
863
- const sendRequest = useCallback((method, params) => {
864
- if (!transportRef.current)
865
- return Promise.reject(new Error("Transport not initialized"));
866
- return transportRef.current.sendRequest(method, params);
867
- }, []);
868
- const sendNotification = useCallback((method, params) => {
869
- var _a2;
870
- (_a2 = transportRef.current) == null ? void 0 : _a2.sendNotification(method, params);
871
- }, []);
872
- const sendResponse = useCallback((id, result) => {
873
- var _a2;
874
- (_a2 = transportRef.current) == null ? void 0 : _a2.sendResponse(id, result);
875
- }, []);
876
- const sendError = useCallback((id, code, message, data) => {
877
- var _a2;
878
- (_a2 = transportRef.current) == null ? void 0 : _a2.sendError(id, code, message, data);
879
- }, []);
880
- const createSubscriber = (set) => (handler) => {
881
- set.add(handler);
882
- return () => set.delete(handler);
883
- };
884
- const onInitialize = useCallback(
885
- createSubscriber(handlersRef.current.initialize),
886
- []
887
- );
888
- const onToolInputPartial = useCallback(
889
- createSubscriber(handlersRef.current.toolInputPartial),
890
- []
891
- );
892
- const onToolInput = useCallback(
893
- createSubscriber(handlersRef.current.toolInput),
894
- []
895
- );
896
- const onToolResult = useCallback(
897
- createSubscriber(handlersRef.current.toolResult),
898
- []
899
- );
900
- const onHostContextChanged = useCallback(
901
- createSubscriber(handlersRef.current.hostContextChanged),
902
- []
903
- );
904
- const onResourceTeardown = useCallback(
905
- createSubscriber(handlersRef.current.resourceTeardown),
906
- []
907
- );
908
- return {
909
- // State
910
- isInitialized,
911
- parentOrigin: (_b = (_a = transportRef.current) == null ? void 0 : _a.getOrigin()) != null ? _b : "*",
912
- appInfo,
913
- hostCapabilities,
914
- hostContext,
915
- // Messaging
916
- sendRequest,
917
- sendNotification,
918
- sendResponse,
919
- sendError,
920
- // Event subscriptions
921
- onInitialize,
922
- onToolInputPartial,
923
- onToolInput,
924
- onToolResult,
925
- onHostContextChanged,
926
- onResourceTeardown
927
- };
928
- }
929
- var initialState = {
930
- name: null,
931
- arguments: null,
932
- partialArguments: null,
933
- result: null,
934
- status: "idle",
935
- isStreaming: false
936
- };
937
- function useMcpToolStream() {
938
- const [state, setState] = useState(initialState);
939
- const handleToolInputPartial = useCallback((params) => {
940
- setState((prev) => ({
941
- ...prev,
942
- name: params.tool.name,
943
- partialArguments: { ...prev.partialArguments, ...params.arguments },
944
- arguments: { ...prev.arguments, ...params.arguments },
945
- status: "streaming",
946
- isStreaming: true
947
- }));
948
- }, []);
949
- const handleToolInput = useCallback((params) => {
950
- setState((prev) => ({
951
- ...prev,
952
- name: params.tool.name,
953
- arguments: params.arguments,
954
- partialArguments: params.arguments,
955
- status: "streaming",
956
- isStreaming: true
957
- }));
958
- }, []);
959
- const handleToolResult = useCallback((params) => {
960
- setState((prev) => ({
961
- ...prev,
962
- name: params.tool.name,
963
- result: params.result,
964
- status: "complete",
965
- isStreaming: false
966
- }));
967
- }, []);
968
- const handleTeardown = useCallback(() => {
969
- setState((prev) => ({
970
- ...prev,
971
- status: "teardown",
972
- isStreaming: false
973
- }));
974
- }, []);
975
- const reset = useCallback(() => {
976
- setState(initialState);
977
- }, []);
978
- const getArgumentValue = useCallback((key, fallback) => {
979
- var _a, _b, _c;
980
- const value = (_c = (_a = state.arguments) == null ? void 0 : _a[key]) != null ? _c : (_b = state.partialArguments) == null ? void 0 : _b[key];
981
- return value != null ? value : fallback;
982
- }, [state.arguments, state.partialArguments]);
983
- return {
984
- ...state,
985
- getArgumentValue,
986
- handleToolInputPartial,
987
- handleToolInput,
988
- handleToolResult,
989
- handleTeardown,
990
- reset
991
- };
992
- }
993
-
994
- export { McpApp, McpAppProvider, useMcpApp, useMcpAppContext, useMcpProtocol, useMcpToolStream };
3
+ export * from 'mcp-app-view/react';
995
4
  //# sourceMappingURL=out.js.map
996
5
  //# sourceMappingURL=react.js.map