-
Notifications
You must be signed in to change notification settings - Fork 365
Expand file tree
/
Copy pathapp-bridge.test.ts
More file actions
2848 lines (2365 loc) · 89.1 KB
/
Copy pathapp-bridge.test.ts
File metadata and controls
2848 lines (2365 loc) · 89.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { describe, it, expect, beforeEach, afterEach, spyOn } from "bun:test";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
import type { ServerCapabilities } from "@modelcontextprotocol/sdk/types.js";
import {
EmptyResultSchema,
ListPromptsResultSchema,
ListResourcesResultSchema,
ListResourceTemplatesResultSchema,
PromptListChangedNotificationSchema,
ReadResourceResultSchema,
ResourceListChangedNotificationSchema,
ToolListChangedNotificationSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { z } from "zod/v4";
import { App } from "./app";
import { LATEST_PROTOCOL_VERSION } from "./types";
import {
AppBridge,
buildAllowAttribute,
getToolUiResourceUri,
isToolVisibilityModelOnly,
isToolVisibilityAppOnly,
type McpUiHostCapabilities,
} from "./app-bridge";
/** Wait for pending microtasks to complete */
const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
/**
* Create a minimal mock MCP client for testing AppBridge.
* Only implements methods that AppBridge calls.
*/
function createMockClient(
serverCapabilities: ServerCapabilities = {},
): Pick<Client, "getServerCapabilities" | "request" | "notification"> {
return {
getServerCapabilities: () => serverCapabilities,
request: async () => ({}) as never,
notification: async () => {},
};
}
const testHostInfo = { name: "TestHost", version: "1.0.0" };
const testAppInfo = { name: "TestApp", version: "1.0.0" };
const testHostCapabilities: McpUiHostCapabilities = {
experimental: {
"com.example/host-extension": { version: 1 },
},
openLinks: {},
serverTools: {},
logging: {},
};
describe("App <-> AppBridge integration", () => {
let app: App;
let bridge: AppBridge;
let appTransport: InMemoryTransport;
let bridgeTransport: InMemoryTransport;
beforeEach(() => {
[appTransport, bridgeTransport] = InMemoryTransport.createLinkedPair();
app = new App(testAppInfo, {}, { autoResize: false });
bridge = new AppBridge(
createMockClient() as Client,
testHostInfo,
testHostCapabilities,
);
});
afterEach(async () => {
await appTransport.close();
await bridgeTransport.close();
});
describe("initialization handshake", () => {
it("App.connect() triggers bridge.oninitialized", async () => {
let initializedFired = false;
bridge.oninitialized = () => {
initializedFired = true;
};
await bridge.connect(bridgeTransport);
await app.connect(appTransport);
expect(initializedFired).toBe(true);
});
it("App receives host info and capabilities after connect", async () => {
await bridge.connect(bridgeTransport);
await app.connect(appTransport);
const hostInfo = app.getHostVersion();
expect(hostInfo).toEqual(testHostInfo);
const hostCaps = app.getHostCapabilities();
expect(hostCaps).toEqual(testHostCapabilities);
});
it("Bridge receives app info and capabilities after initialization", async () => {
const appCapabilities = {
experimental: {
"com.example/app-extension": { version: 1 },
},
tools: { listChanged: true },
};
app = new App(testAppInfo, appCapabilities, { autoResize: false });
await bridge.connect(bridgeTransport);
await app.connect(appTransport);
const appInfo = bridge.getAppVersion();
expect(appInfo).toEqual(testAppInfo);
const appCaps = bridge.getAppCapabilities();
expect(appCaps).toEqual(appCapabilities);
});
it("App receives initial hostContext after connect", async () => {
// Need fresh transports for new bridge
const [newAppTransport, newBridgeTransport] =
InMemoryTransport.createLinkedPair();
const testHostContext = {
theme: "dark" as const,
locale: "en-US",
containerDimensions: { width: 800, maxHeight: 600 },
};
const newBridge = new AppBridge(
createMockClient() as Client,
testHostInfo,
testHostCapabilities,
{ hostContext: testHostContext },
);
const newApp = new App(testAppInfo, {}, { autoResize: false });
await newBridge.connect(newBridgeTransport);
await newApp.connect(newAppTransport);
const hostContext = newApp.getHostContext();
expect(hostContext).toEqual(testHostContext);
await newAppTransport.close();
await newBridgeTransport.close();
});
it("getHostContext returns undefined before connect", () => {
expect(app.getHostContext()).toBeUndefined();
});
});
describe("Host -> App notifications", () => {
beforeEach(async () => {
await bridge.connect(bridgeTransport);
});
it("sendToolInput triggers app.ontoolinput", async () => {
const receivedArgs: unknown[] = [];
app.ontoolinput = (params) => {
receivedArgs.push(params.arguments);
};
await app.connect(appTransport);
await bridge.sendToolInput({ arguments: { location: "NYC" } });
expect(receivedArgs).toEqual([{ location: "NYC" }]);
});
it("sendToolInputPartial triggers app.ontoolinputpartial", async () => {
const receivedArgs: unknown[] = [];
app.ontoolinputpartial = (params) => {
receivedArgs.push(params.arguments);
};
await app.connect(appTransport);
await bridge.sendToolInputPartial({ arguments: { loc: "N" } });
await bridge.sendToolInputPartial({ arguments: { location: "NYC" } });
expect(receivedArgs).toEqual([{ loc: "N" }, { location: "NYC" }]);
});
it("sendToolResult triggers app.ontoolresult", async () => {
const receivedResults: unknown[] = [];
app.ontoolresult = (params) => {
receivedResults.push(params);
};
await app.connect(appTransport);
await bridge.sendToolResult({
content: [{ type: "text", text: "Weather: Sunny" }],
});
expect(receivedResults).toHaveLength(1);
expect(receivedResults[0]).toEqual({
content: [{ type: "text", text: "Weather: Sunny" }],
});
});
it("sendToolCancelled triggers app.ontoolcancelled", async () => {
const receivedCancellations: unknown[] = [];
app.ontoolcancelled = (params) => {
receivedCancellations.push(params);
};
await app.connect(appTransport);
await bridge.sendToolCancelled({
reason: "User cancelled the operation",
});
expect(receivedCancellations).toHaveLength(1);
expect(receivedCancellations[0]).toEqual({
reason: "User cancelled the operation",
});
});
it("sendToolCancelled works without reason", async () => {
const receivedCancellations: unknown[] = [];
app.ontoolcancelled = (params) => {
receivedCancellations.push(params);
};
await app.connect(appTransport);
await bridge.sendToolCancelled({});
expect(receivedCancellations).toHaveLength(1);
expect(receivedCancellations[0]).toEqual({});
});
it("setHostContext triggers app.onhostcontextchanged", async () => {
const receivedContexts: unknown[] = [];
app.onhostcontextchanged = (params) => {
receivedContexts.push(params);
};
await app.connect(appTransport);
bridge.setHostContext({ theme: "dark" });
await flush();
expect(receivedContexts).toEqual([{ theme: "dark" }]);
});
it("setHostContext only sends changed values", async () => {
const receivedContexts: unknown[] = [];
app.onhostcontextchanged = (params) => {
receivedContexts.push(params);
};
await app.connect(appTransport);
bridge.setHostContext({ theme: "dark", locale: "en-US" });
await flush();
bridge.setHostContext({ theme: "dark", locale: "en-US" }); // No change
await flush();
bridge.setHostContext({ theme: "light", locale: "en-US" }); // Only theme changed
await flush();
expect(receivedContexts).toEqual([
{ theme: "dark", locale: "en-US" },
{ theme: "light" },
]);
});
it("getHostContext merges updates from onhostcontextchanged", async () => {
// Need fresh transports for new bridge
const [newAppTransport, newBridgeTransport] =
InMemoryTransport.createLinkedPair();
// Set up bridge with initial context
const initialContext = {
theme: "light" as const,
locale: "en-US",
};
const newBridge = new AppBridge(
createMockClient() as Client,
testHostInfo,
testHostCapabilities,
{ hostContext: initialContext },
);
const newApp = new App(testAppInfo, {}, { autoResize: false });
await newBridge.connect(newBridgeTransport);
// Set up handler before connecting app
newApp.onhostcontextchanged = () => {
// User handler (can be empty, we're testing getHostContext behavior)
};
await newApp.connect(newAppTransport);
// Verify initial context
expect(newApp.getHostContext()).toEqual(initialContext);
// Update context
newBridge.setHostContext({ theme: "dark", locale: "en-US" });
await flush();
// getHostContext should reflect merged state
const updatedContext = newApp.getHostContext();
expect(updatedContext?.theme).toBe("dark");
expect(updatedContext?.locale).toBe("en-US");
await newAppTransport.close();
await newBridgeTransport.close();
});
it("getHostContext updates even without user setting onhostcontextchanged", async () => {
// Need fresh transports for new bridge
const [newAppTransport, newBridgeTransport] =
InMemoryTransport.createLinkedPair();
// Set up bridge with initial context
const initialContext = {
theme: "light" as const,
locale: "en-US",
};
const newBridge = new AppBridge(
createMockClient() as Client,
testHostInfo,
testHostCapabilities,
{ hostContext: initialContext },
);
const newApp = new App(testAppInfo, {}, { autoResize: false });
await newBridge.connect(newBridgeTransport);
// Note: We do NOT set app.onhostcontextchanged here
await newApp.connect(newAppTransport);
// Verify initial context
expect(newApp.getHostContext()).toEqual(initialContext);
// Update context from bridge
newBridge.setHostContext({ theme: "dark", locale: "en-US" });
await flush();
// getHostContext should still update (default handler should work)
const updatedContext = newApp.getHostContext();
expect(updatedContext?.theme).toBe("dark");
await newAppTransport.close();
await newBridgeTransport.close();
});
it("getHostContext accumulates multiple partial updates", async () => {
// Need fresh transports for new bridge
const [newAppTransport, newBridgeTransport] =
InMemoryTransport.createLinkedPair();
const initialContext = {
theme: "light" as const,
locale: "en-US",
containerDimensions: { width: 800, maxHeight: 600 },
};
const newBridge = new AppBridge(
createMockClient() as Client,
testHostInfo,
testHostCapabilities,
{ hostContext: initialContext },
);
const newApp = new App(testAppInfo, {}, { autoResize: false });
await newBridge.connect(newBridgeTransport);
await newApp.connect(newAppTransport);
// Send partial update: only theme changes
newBridge.sendHostContextChange({ theme: "dark" });
await flush();
// Send another partial update: only containerDimensions change
newBridge.sendHostContextChange({
containerDimensions: { width: 1024, maxHeight: 768 },
});
await flush();
// getHostContext should have accumulated all updates:
// - locale from initial (unchanged)
// - theme from first partial update
// - containerDimensions from second partial update
const context = newApp.getHostContext();
expect(context?.theme).toBe("dark");
expect(context?.locale).toBe("en-US");
expect(context?.containerDimensions).toEqual({
width: 1024,
maxHeight: 768,
});
await newAppTransport.close();
await newBridgeTransport.close();
});
it("teardownResource triggers app.onteardown", async () => {
let teardownCalled = false;
app.onteardown = async () => {
teardownCalled = true;
return {};
};
await app.connect(appTransport);
await bridge.teardownResource({});
expect(teardownCalled).toBe(true);
});
it("teardownResource waits for async cleanup", async () => {
const cleanupSteps: string[] = [];
app.onteardown = async () => {
cleanupSteps.push("start");
await new Promise((resolve) => setTimeout(resolve, 10));
cleanupSteps.push("done");
return {};
};
await app.connect(appTransport);
await bridge.teardownResource({});
expect(cleanupSteps).toEqual(["start", "done"]);
});
});
describe("App -> Host notifications", () => {
beforeEach(async () => {
await bridge.connect(bridgeTransport);
});
it("app.sendSizeChanged triggers bridge.onsizechange", async () => {
const receivedSizes: unknown[] = [];
bridge.onsizechange = (params) => {
receivedSizes.push(params);
};
await app.connect(appTransport);
await app.sendSizeChanged({ width: 400, height: 600 });
expect(receivedSizes).toEqual([{ width: 400, height: 600 }]);
});
it("app.sendLog triggers bridge.onloggingmessage", async () => {
const receivedLogs: unknown[] = [];
bridge.onloggingmessage = (params) => {
receivedLogs.push(params);
};
await app.connect(appTransport);
await app.sendLog({
level: "info",
data: "Test log message",
logger: "TestApp",
});
expect(receivedLogs).toHaveLength(1);
expect(receivedLogs[0]).toMatchObject({
level: "info",
data: "Test log message",
logger: "TestApp",
});
});
it("app.updateModelContext triggers bridge.onupdatemodelcontext and returns result", async () => {
const receivedContexts: unknown[] = [];
bridge.onupdatemodelcontext = async (params) => {
receivedContexts.push(params);
return {};
};
await app.connect(appTransport);
const result = await app.updateModelContext({
content: [{ type: "text", text: "User selected 3 items" }],
});
expect(receivedContexts).toHaveLength(1);
expect(receivedContexts[0]).toMatchObject({
content: [{ type: "text", text: "User selected 3 items" }],
});
expect(result).toEqual({});
});
it("app.updateModelContext works with multiple content blocks", async () => {
const receivedContexts: unknown[] = [];
bridge.onupdatemodelcontext = async (params) => {
receivedContexts.push(params);
return {};
};
await app.connect(appTransport);
const result = await app.updateModelContext({
content: [
{ type: "text", text: "Filter applied" },
{ type: "text", text: "Category: electronics" },
],
});
expect(receivedContexts).toHaveLength(1);
expect(receivedContexts[0]).toMatchObject({
content: [
{ type: "text", text: "Filter applied" },
{ type: "text", text: "Category: electronics" },
],
});
expect(result).toEqual({});
});
it("app.updateModelContext works with structuredContent", async () => {
const receivedContexts: unknown[] = [];
bridge.onupdatemodelcontext = async (params) => {
receivedContexts.push(params);
return {};
};
await app.connect(appTransport);
const result = await app.updateModelContext({
structuredContent: { selectedItems: 3, total: 150.0, currency: "USD" },
});
expect(receivedContexts).toHaveLength(1);
expect(receivedContexts[0]).toMatchObject({
structuredContent: { selectedItems: 3, total: 150.0, currency: "USD" },
});
expect(result).toEqual({});
});
it("app.updateModelContext throws when handler throws", async () => {
bridge.onupdatemodelcontext = async () => {
throw new Error("Context update failed");
};
await app.connect(appTransport);
expect(
app.updateModelContext({
content: [{ type: "text", text: "Test" }],
}),
).rejects.toThrow("Context update failed");
});
it("app.requestTeardown allows host to initiate teardown flow", async () => {
const events: string[] = [];
bridge.onrequestteardown = async () => {
events.push("teardown-requested");
await bridge.teardownResource({});
events.push("teardown-complete");
};
app.onteardown = async () => {
events.push("persist-unsaved-state");
return {};
};
await app.connect(appTransport);
await app.requestTeardown();
await flush();
expect(events).toEqual([
"teardown-requested",
"persist-unsaved-state",
"teardown-complete",
]);
});
});
describe("App -> Host requests", () => {
beforeEach(async () => {
await bridge.connect(bridgeTransport);
});
it("app.sendMessage triggers bridge.onmessage and returns result", async () => {
const receivedMessages: unknown[] = [];
bridge.onmessage = async (params) => {
receivedMessages.push(params);
return {};
};
await app.connect(appTransport);
const result = await app.sendMessage({
role: "user",
content: [{ type: "text", text: "Hello from app" }],
});
expect(receivedMessages).toHaveLength(1);
expect(receivedMessages[0]).toMatchObject({
role: "user",
content: [{ type: "text", text: "Hello from app" }],
});
expect(result).toEqual({});
});
it("app.sendMessage returns error result when handler indicates error", async () => {
bridge.onmessage = async () => {
return { isError: true };
};
await app.connect(appTransport);
const result = await app.sendMessage({
role: "user",
content: [{ type: "text", text: "Test" }],
});
expect(result.isError).toBe(true);
});
it("app.openLink triggers bridge.onopenlink and returns result", async () => {
const receivedLinks: string[] = [];
bridge.onopenlink = async (params) => {
receivedLinks.push(params.url);
return {};
};
await app.connect(appTransport);
const result = await app.openLink({ url: "https://example.com" });
expect(receivedLinks).toEqual(["https://example.com"]);
expect(result).toEqual({});
});
it("app.openLink returns error when host denies", async () => {
bridge.onopenlink = async () => {
return { isError: true };
};
await app.connect(appTransport);
const result = await app.openLink({ url: "https://blocked.com" });
expect(result.isError).toBe(true);
});
});
describe("deprecated method aliases", () => {
beforeEach(async () => {
await bridge.connect(bridgeTransport);
await app.connect(appTransport);
});
it("app.sendOpenLink is an alias for app.openLink", async () => {
expect(app.sendOpenLink).toBe(app.openLink);
});
it("bridge.sendResourceTeardown is a deprecated alias for bridge.teardownResource", () => {
expect(bridge.sendResourceTeardown).toBe(bridge.teardownResource);
});
it("app.sendOpenLink works as deprecated alias", async () => {
const receivedLinks: string[] = [];
bridge.onopenlink = async (params) => {
receivedLinks.push(params.url);
return {};
};
await app.sendOpenLink({ url: "https://example.com" });
expect(receivedLinks).toEqual(["https://example.com"]);
});
});
describe("double-connect guard", () => {
it("AppBridge.connect() throws if already connected", async () => {
await bridge.connect(bridgeTransport);
await app.connect(appTransport);
// Attempting to connect again with a different transport should throw
const [, secondBridgeTransport] = InMemoryTransport.createLinkedPair();
expect(bridge.connect(secondBridgeTransport)).rejects.toThrow(
"AppBridge is already connected",
);
});
it("App.connect() throws if already connected", async () => {
await bridge.connect(bridgeTransport);
await app.connect(appTransport);
// Attempting to connect again should throw
const [secondAppTransport] = InMemoryTransport.createLinkedPair();
expect(app.connect(secondAppTransport)).rejects.toThrow(
"App is already connected",
);
});
it("AppBridge.connect() throws even when called with the same transport", async () => {
await bridge.connect(bridgeTransport);
await app.connect(appTransport);
// Should throw regardless of whether it's the same or a different transport
expect(bridge.connect(bridgeTransport)).rejects.toThrow(
"AppBridge is already connected",
);
});
});
describe("ping", () => {
it("App responds to ping from bridge", async () => {
await bridge.connect(bridgeTransport);
await app.connect(appTransport);
// Bridge can send ping via the protocol's request method
const result = await bridge.request(
{ method: "ping", params: {} },
EmptyResultSchema,
);
expect(result).toEqual({});
});
});
describe("App tool registration", () => {
beforeEach(async () => {
app = new App(
testAppInfo,
{ tools: { listChanged: true } },
{ autoResize: false },
);
await bridge.connect(bridgeTransport);
});
it("registerTool creates a registered tool", async () => {
const InputSchema = z.object({ name: z.string() });
const OutputSchema = z.object({ greeting: z.string() });
const tool = app.registerTool(
"greet",
{
title: "Greet User",
description: "Greets a user by name",
inputSchema: InputSchema,
outputSchema: OutputSchema,
},
async (args: any) => ({
content: [{ type: "text" as const, text: `Hello, ${args.name}!` }],
structuredContent: { greeting: `Hello, ${args.name}!` },
}),
);
expect(tool.title).toBe("Greet User");
expect(tool.description).toBe("Greets a user by name");
expect(tool.enabled).toBe(true);
});
it("registered tool can be enabled and disabled", async () => {
await app.connect(appTransport);
const tool = app.registerTool(
"test-tool",
{
description: "Test tool",
},
async (_extra: any) => ({ content: [] }),
);
expect(tool.enabled).toBe(true);
tool.disable();
expect(tool.enabled).toBe(false);
tool.enable();
expect(tool.enabled).toBe(true);
});
it("registered tool can be updated", async () => {
await app.connect(appTransport);
const tool = app.registerTool(
"test-tool",
{
description: "Original description",
},
async (_extra: any) => ({ content: [] }),
);
expect(tool.description).toBe("Original description");
tool.update({ description: "Updated description" });
expect(tool.description).toBe("Updated description");
});
it("registered tool can be removed", async () => {
await app.connect(appTransport);
const tool = app.registerTool(
"test-tool",
{
description: "Test tool",
},
async (_extra: any) => ({ content: [] }),
);
tool.remove();
// Tool should no longer be registered (internal check)
});
it("registerTool throws on duplicate name", () => {
app.registerTool("dup", {}, async () => ({ content: [] }));
expect(() =>
app.registerTool("dup", {}, async () => ({ content: [] })),
).toThrow(/already registered/);
});
it("enable/disable/update/remove pre-connect do not throw", () => {
const tool = app.registerTool("t", {}, async () => ({ content: [] }));
expect(() => tool.disable()).not.toThrow();
expect(() => tool.enable()).not.toThrow();
expect(() => tool.update({ description: "x" })).not.toThrow();
expect(() => tool.remove()).not.toThrow();
});
it("callback without inputSchema receives extra as first arg", async () => {
await app.connect(appTransport);
let receivedExtra: any;
app.registerTool("noargs", {}, async (extra: any) => {
receivedExtra = extra;
return { content: [] };
});
await bridge.callTool({ name: "noargs", arguments: {} });
expect(receivedExtra).toBeDefined();
expect(receivedExtra.signal).toBeInstanceOf(AbortSignal);
});
it("isError result skips output schema validation", async () => {
await app.connect(appTransport);
app.registerTool(
"errs",
{ outputSchema: z.object({ ok: z.boolean() }) },
async () => ({
content: [{ type: "text" as const, text: "boom" }],
isError: true,
}),
);
const res = await bridge.callTool({ name: "errs", arguments: {} });
expect(res.isError).toBe(true);
expect(res.structuredContent).toBeUndefined();
});
it("stale handle remove() does not delete a re-registered tool", async () => {
const t1 = app.registerTool("phoenix", {}, async () => ({ content: [] }));
t1.remove();
app.registerTool("phoenix", {}, async () => ({ content: [] }));
t1.remove();
await app.connect(appTransport);
const list = await bridge.listTools({});
expect(list.tools.map((t) => t.name)).toContain("phoenix");
});
it("host omitting arguments defaults to empty object", async () => {
await app.connect(appTransport);
let received: unknown;
app.registerTool(
"noargs2",
{ inputSchema: z.object({}) },
async (args) => {
received = args;
return { content: [] };
},
);
await bridge.callTool({ name: "noargs2" });
expect(received).toEqual({});
});
it("update({inputSchema}) is honored by handler validation", async () => {
await app.connect(appTransport);
const tool = app.registerTool(
"evolving",
{ inputSchema: z.object({ a: z.string() }) },
async (args: any) => ({
content: [{ type: "text" as const, text: JSON.stringify(args) }],
}),
);
expect(
bridge.callTool({ name: "evolving", arguments: { a: 123 } }),
).rejects.toThrow(/Invalid input/);
tool.update({ inputSchema: z.object({ a: z.number() }) });
const result = await bridge.callTool({
name: "evolving",
arguments: { a: 123 },
});
expect(result.content[0]).toEqual({ type: "text", text: '{"a":123}' });
});
it("tool throws error when disabled and called", async () => {
await app.connect(appTransport);
const tool = app.registerTool(
"test-tool",
{
description: "Test tool",
},
async (_extra: any) => ({ content: [] }),
);
tool.disable();
const mockExtra = {
signal: new AbortController().signal,
requestId: "test",
sendNotification: async () => {},
sendRequest: async () => ({}),
} as any;
expect((tool.handler as any)(mockExtra)).rejects.toThrow(
"Tool test-tool is disabled",
);
});
it("tool validates input schema", async () => {
const InputSchema = z.object({ name: z.string() });
const tool = app.registerTool(
"greet",
{
inputSchema: InputSchema,
},
async (args: any) => ({
content: [{ type: "text" as const, text: `Hello, ${args.name}!` }],
}),
);
// Create a mock RequestHandlerExtra
const mockExtra = {
signal: new AbortController().signal,
requestId: "test",
sendNotification: async () => {},
sendRequest: async () => ({}),
} as any;
// Valid input should work
expect(
(tool.handler as any)({ name: "Alice" }, mockExtra),
).resolves.toBeDefined();
// Invalid input should fail
expect(
(tool.handler as any)({ invalid: "field" }, mockExtra),
).rejects.toThrow("Invalid input for tool greet");
});
it("tool validates output schema", async () => {
const OutputSchema = z.object({ greeting: z.string() });
const tool = app.registerTool(
"greet",
{
outputSchema: OutputSchema,
},
async (_extra: any) => ({
content: [{ type: "text" as const, text: "Hello!" }],
structuredContent: { greeting: "Hello!" },
}),
);
// Create a mock RequestHandlerExtra
const mockExtra = {
signal: new AbortController().signal,
requestId: "test",
sendNotification: async () => {},
sendRequest: async () => ({}),
} as any;
// Valid output should work
expect((tool.handler as any)(mockExtra)).resolves.toBeDefined();
});
it("tool enable/disable/update/remove trigger sendToolListChanged", async () => {
await app.connect(appTransport);
const tool = app.registerTool(
"test-tool",
{
description: "Test tool",
},
async (_extra: any) => ({ content: [] }),
);
// The methods should not throw when connected
expect(() => tool.disable()).not.toThrow();
expect(() => tool.enable()).not.toThrow();
expect(() => tool.update({ description: "Updated" })).not.toThrow();
expect(() => tool.remove()).not.toThrow();
});
});
describe("AppBridge -> App tool requests", () => {
beforeEach(async () => {
await bridge.connect(bridgeTransport);
});
it("bridge.callTool calls app.oncalltool handler", async () => {
// App needs tool capabilities to handle tool calls
const appCapabilities = { tools: {} };
app = new App(testAppInfo, appCapabilities, { autoResize: false });
const receivedCalls: unknown[] = [];
app.oncalltool = async (params) => {
receivedCalls.push(params);
return {
content: [{ type: "text", text: `Executed: ${params.name}` }],
};
};
await app.connect(appTransport);
const result = await bridge.callTool({
name: "test-tool",
arguments: { foo: "bar" },