diff --git a/src/app-bridge.test.ts b/src/app-bridge.test.ts index 875c10e49..a2ace3c20 100644 --- a/src/app-bridge.test.ts +++ b/src/app-bridge.test.ts @@ -615,6 +615,40 @@ describe("App <-> AppBridge integration", () => { }); }); + 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(); + await 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(); + await 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 + await expect(bridge.connect(bridgeTransport)).rejects.toThrow( + "AppBridge is already connected", + ); + }); + }); + describe("ping", () => { it("App responds to ping from bridge", async () => { await bridge.connect(bridgeTransport); diff --git a/src/app-bridge.ts b/src/app-bridge.ts index 3322a0dda..6e1c02172 100644 --- a/src/app-bridge.ts +++ b/src/app-bridge.ts @@ -1409,6 +1409,11 @@ export class AppBridge extends Protocol< * ``` */ async connect(transport: Transport) { + if (this.transport) { + throw new Error( + "AppBridge is already connected. Call close() before connecting again.", + ); + } if (this._client) { // When a client was passed to the constructor, automatically forward // MCP requests/notifications between the view and the server diff --git a/src/app.ts b/src/app.ts index f813f44c8..4613e8f13 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1112,6 +1112,11 @@ export class App extends Protocol { ), options?: RequestOptions, ): Promise { + if (this.transport) { + throw new Error( + "App is already connected. Call close() before connecting again.", + ); + } await super.connect(transport); try {