From 8d3bd3aef52fae488feabebf8c8505e05de7318b Mon Sep 17 00:00:00 2001 From: Roomote Date: Fri, 27 Nov 2026 05:04:13 +0000 Subject: [PATCH 1/3] Fix MCP OAuth sign-in lifecycle: port 0 URLs, stuck flows, reconnect loop, and stale panel status --- .../tla/McpOAuthFlowEnd.DeleteLeak.cfg | 9 + .../tla/McpOAuthFlowEnd.DisposeLeak.cfg | 9 + .../tla/McpOAuthFlowEnd.ErrorLeak.cfg | 9 + .../tla/McpOAuthFlowEnd.ReplaceLeak.cfg | 9 + docs/architecture/tla/McpOAuthFlowEnd.cfg | 8 + docs/architecture/tla/McpOAuthFlowEnd.tla | 121 ++++ .../tla/McpOAuthRedirectUrl.NoEnsure.cfg | 8 + .../tla/McpOAuthRedirectUrl.NoOverride.cfg | 8 + docs/architecture/tla/McpOAuthRedirectUrl.cfg | 7 + docs/architecture/tla/McpOAuthRedirectUrl.tla | 85 +++ .../McpOAuthStatusHandoff.NoEarlyNotify.cfg | 6 + .../tla/McpOAuthStatusHandoff.cfg | 5 + .../tla/McpOAuthStatusHandoff.tla | 67 +++ src/i18n/locales/ca/mcp.json | 1 + src/i18n/locales/de/mcp.json | 1 + src/i18n/locales/en/mcp.json | 1 + src/i18n/locales/es/mcp.json | 1 + src/i18n/locales/fr/mcp.json | 1 + src/i18n/locales/hi/mcp.json | 1 + src/i18n/locales/id/mcp.json | 1 + src/i18n/locales/it/mcp.json | 1 + src/i18n/locales/ja/mcp.json | 1 + src/i18n/locales/ko/mcp.json | 1 + src/i18n/locales/nl/mcp.json | 1 + src/i18n/locales/pl/mcp.json | 1 + src/i18n/locales/pt-BR/mcp.json | 1 + src/i18n/locales/ru/mcp.json | 1 + src/i18n/locales/tr/mcp.json | 1 + src/i18n/locales/vi/mcp.json | 1 + src/i18n/locales/zh-CN/mcp.json | 1 + src/i18n/locales/zh-TW/mcp.json | 1 + src/services/mcp/McpHub.ts | 220 +++++-- src/services/mcp/McpOAuthClientProvider.ts | 12 + src/services/mcp/__tests__/McpHub.spec.ts | 367 +++++++++++- .../__tests__/McpOAuthClientProvider.spec.ts | 114 +++- .../__tests__/mcp-oauth-flow.property.spec.ts | 557 ++++++++++++++++++ src/services/mcp/constants.ts | 6 + 37 files changed, 1594 insertions(+), 51 deletions(-) create mode 100644 docs/architecture/tla/McpOAuthFlowEnd.DeleteLeak.cfg create mode 100644 docs/architecture/tla/McpOAuthFlowEnd.DisposeLeak.cfg create mode 100644 docs/architecture/tla/McpOAuthFlowEnd.ErrorLeak.cfg create mode 100644 docs/architecture/tla/McpOAuthFlowEnd.ReplaceLeak.cfg create mode 100644 docs/architecture/tla/McpOAuthFlowEnd.cfg create mode 100644 docs/architecture/tla/McpOAuthFlowEnd.tla create mode 100644 docs/architecture/tla/McpOAuthRedirectUrl.NoEnsure.cfg create mode 100644 docs/architecture/tla/McpOAuthRedirectUrl.NoOverride.cfg create mode 100644 docs/architecture/tla/McpOAuthRedirectUrl.cfg create mode 100644 docs/architecture/tla/McpOAuthRedirectUrl.tla create mode 100644 docs/architecture/tla/McpOAuthStatusHandoff.NoEarlyNotify.cfg create mode 100644 docs/architecture/tla/McpOAuthStatusHandoff.cfg create mode 100644 docs/architecture/tla/McpOAuthStatusHandoff.tla create mode 100644 src/services/mcp/__tests__/mcp-oauth-flow.property.spec.ts diff --git a/docs/architecture/tla/McpOAuthFlowEnd.DeleteLeak.cfg b/docs/architecture/tla/McpOAuthFlowEnd.DeleteLeak.cfg new file mode 100644 index 00000000000..f914252a936 --- /dev/null +++ b/docs/architecture/tla/McpOAuthFlowEnd.DeleteLeak.cfg @@ -0,0 +1,9 @@ +\* Sabotage. deleteConnection no longer ends the flow. The invariant must fail. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + ReplaceEndsFlow = TRUE + DeleteEndsFlow = FALSE + DisposeEndsFlows = TRUE + ErrorEndsFlow = TRUE +INVARIANTS TypeOK NoDuplicateFlow NoOrphanFlow ToolNotOrphaned NoErrorLeak diff --git a/docs/architecture/tla/McpOAuthFlowEnd.DisposeLeak.cfg b/docs/architecture/tla/McpOAuthFlowEnd.DisposeLeak.cfg new file mode 100644 index 00000000000..3904bbf5ff8 --- /dev/null +++ b/docs/architecture/tla/McpOAuthFlowEnd.DisposeLeak.cfg @@ -0,0 +1,9 @@ +\* Sabotage. dispose no longer ends the flows. The invariant must fail. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + ReplaceEndsFlow = TRUE + DeleteEndsFlow = TRUE + DisposeEndsFlows = FALSE + ErrorEndsFlow = TRUE +INVARIANTS TypeOK NoDuplicateFlow NoOrphanFlow ToolNotOrphaned NoErrorLeak diff --git a/docs/architecture/tla/McpOAuthFlowEnd.ErrorLeak.cfg b/docs/architecture/tla/McpOAuthFlowEnd.ErrorLeak.cfg new file mode 100644 index 00000000000..ce12c83f988 --- /dev/null +++ b/docs/architecture/tla/McpOAuthFlowEnd.ErrorLeak.cfg @@ -0,0 +1,9 @@ +\* Sabotage. A reconnect error no longer ends the flow. The invariant must fail. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + ReplaceEndsFlow = TRUE + DeleteEndsFlow = TRUE + DisposeEndsFlows = TRUE + ErrorEndsFlow = FALSE +INVARIANTS TypeOK NoDuplicateFlow NoOrphanFlow ToolNotOrphaned NoErrorLeak diff --git a/docs/architecture/tla/McpOAuthFlowEnd.ReplaceLeak.cfg b/docs/architecture/tla/McpOAuthFlowEnd.ReplaceLeak.cfg new file mode 100644 index 00000000000..cefcb9dea65 --- /dev/null +++ b/docs/architecture/tla/McpOAuthFlowEnd.ReplaceLeak.cfg @@ -0,0 +1,9 @@ +\* Sabotage. A replaced flow no longer ends. The invariant must fail. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + ReplaceEndsFlow = FALSE + DeleteEndsFlow = TRUE + DisposeEndsFlows = TRUE + ErrorEndsFlow = TRUE +INVARIANTS TypeOK NoDuplicateFlow NoOrphanFlow ToolNotOrphaned NoErrorLeak diff --git a/docs/architecture/tla/McpOAuthFlowEnd.cfg b/docs/architecture/tla/McpOAuthFlowEnd.cfg new file mode 100644 index 00000000000..fd4e1e40fd9 --- /dev/null +++ b/docs/architecture/tla/McpOAuthFlowEnd.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + ReplaceEndsFlow = TRUE + DeleteEndsFlow = TRUE + DisposeEndsFlows = TRUE + ErrorEndsFlow = TRUE +INVARIANTS TypeOK NoDuplicateFlow NoOrphanFlow ToolNotOrphaned NoErrorLeak diff --git a/docs/architecture/tla/McpOAuthFlowEnd.tla b/docs/architecture/tla/McpOAuthFlowEnd.tla new file mode 100644 index 00000000000..96ce3047a7c --- /dev/null +++ b/docs/architecture/tla/McpOAuthFlowEnd.tla @@ -0,0 +1,121 @@ +---- MODULE McpOAuthFlowEnd ---- +EXTENDS Naturals +\* Source: McpHub._runOAuthFlow registers the watcher entry in _oauthWatchers and +\* owns the flow promise. deleteConnection(), flow replacement in _runOAuthFlow(), +\* dispose(), and the token-watcher error path remove or replace that entry. +\* Sink: McpHub.callTool awaits the re-auth promise, and the flow promise resolves +\* through the shared removal path _endOAuthWatcher. +\* Failure: a removed watcher leaves its flow pending, so the notification stays +\* open and tool calls that wait on the flow stay blocked (issue 2761). +\* Failure: an old flow removes the watcher of a newer flow, so the newer flow +\* can never time out or resolve. +\* Failure: a reconnect that throws in the token watcher leaves the flow pending. +\* Invariants: WatchedFlowIsSingle, NoOrphanFlow, ToolNotOrphaned, NoErrorLeak. +\* Fix rule: every watcher removal goes through one shared path that also ends +\* the flow, and a reconnect error ends the flow with a visible error. +\* Scope: timeouts, cancellation, and the toast paths end the flow inside the +\* flow itself; the model folds them into FlowEnds. Secret storage is an oracle. +\* Scope: at most two flows and one watcher per key. One tool call waits at a time. +\* Expect: Fixed holds. ReplaceLeak, DeleteLeak, DisposeLeak and ErrorLeak each fail. +\* Result: Fixed holds in 3 states. ReplaceLeak fails at 4 states (NoDuplicateFlow). +\* DeleteLeak fails at 4 states (NoOrphanFlow). DisposeLeak fails at 4 states +\* (NoOrphanFlow). ErrorLeak fails at 4 states (NoErrorLeak). +\* Property test: src/services/mcp/__tests__/mcp-oauth-flow.property.spec.ts. + +CONSTANTS ReplaceEndsFlow \* TRUE when a replacement flow ends the replaced flow +CONSTANTS DeleteEndsFlow \* TRUE when deleteConnection ends the flow +CONSTANTS DisposeEndsFlows \* TRUE when dispose ends all flows +CONSTANTS ErrorEndsFlow \* TRUE when a reconnect error ends the flow + +VARIABLES watcher \* a watcher entry is registered for this key +VARIABLES pending \* number of flows not yet ended (0 to 2) +VARIABLES toolWait \* a tool call waits on the re-auth promise +VARIABLES errorLeak \* latch: a reconnect error left its flow pending + +vars == <> + +Init == + /\ watcher = FALSE + /\ pending = 0 + /\ toolWait = FALSE + /\ errorLeak = FALSE + +\* connectToServer starts a flow. A replacement ends the old flow through the +\* shared path; without that rule the replaced flow stays pending forever. +StartFlow == + /\ pending' = IF watcher /\ ReplaceEndsFlow THEN pending + ELSE IF pending < 2 THEN pending + 1 ELSE 2 + /\ watcher' = TRUE + /\ UNCHANGED <> + +\* callTool hits a 401 and starts the re-auth flow it waits on. +CallTool == + /\ toolWait' = TRUE + /\ pending' = IF watcher /\ ReplaceEndsFlow THEN pending + ELSE IF pending < 2 THEN pending + 1 ELSE 2 + /\ watcher' = TRUE + /\ UNCHANGED errorLeak + +\* deleteConnection removes the watcher. The shared path also ends the flow and +\* releases the waiting tool call. +DeleteConnection == + /\ watcher' = FALSE + /\ pending' = IF watcher /\ DeleteEndsFlow THEN pending - 1 ELSE pending + /\ toolWait' = IF watcher /\ DeleteEndsFlow THEN FALSE ELSE toolWait + /\ UNCHANGED errorLeak + +\* The token watcher catches a reconnect error. The fix ends the flow and shows +\* the error on the server status; the old code only logged it. +WatcherError == + /\ pending >= 1 + /\ errorLeak' = (errorLeak \/ ~ErrorEndsFlow) + /\ pending' = IF ErrorEndsFlow THEN pending - 1 ELSE pending + /\ watcher' = IF ErrorEndsFlow THEN FALSE ELSE watcher + /\ toolWait' = IF ErrorEndsFlow THEN FALSE ELSE toolWait + +\* A flow ends inside itself: timeout, cancel, or a completed sign-in. +FlowEnds == + /\ pending >= 1 + /\ pending' = pending - 1 + /\ watcher' = FALSE + /\ toolWait' = FALSE + /\ UNCHANGED errorLeak + +\* The hub is disposed. The shared path ends every flow and releases every wait. +Dispose == + /\ watcher' = FALSE + /\ pending' = IF DisposeEndsFlows THEN 0 ELSE pending + /\ toolWait' = IF DisposeEndsFlows THEN FALSE ELSE toolWait + /\ UNCHANGED errorLeak + +Next == + \/ StartFlow + \/ CallTool + \/ DeleteConnection + \/ WatcherError + \/ FlowEnds + \/ Dispose + +Spec == Init /\ [][Next]_vars + +TypeOK == + /\ watcher \in BOOLEAN + /\ pending \in 0 .. 2 + /\ toolWait \in BOOLEAN + /\ errorLeak \in BOOLEAN + +\* A watcher entry belongs to exactly one pending flow, and a replaced flow +\* ends instead of piling up. +NoDuplicateFlow == pending <= 1 + +\* A pending flow always still owns its watcher. A removal without a flow end +\* orphans the flow. +NoOrphanFlow == pending >= 1 => watcher + +\* A waiting tool call either waits on a live flow or was released by its end. +ToolNotOrphaned == toolWait => (watcher \/ pending = 0) + +\* A reconnect error never leaves its flow pending. +NoErrorLeak == ~errorLeak + +==== diff --git a/docs/architecture/tla/McpOAuthRedirectUrl.NoEnsure.cfg b/docs/architecture/tla/McpOAuthRedirectUrl.NoEnsure.cfg new file mode 100644 index 00000000000..0a4bbf319bd --- /dev/null +++ b/docs/architecture/tla/McpOAuthRedirectUrl.NoEnsure.cfg @@ -0,0 +1,8 @@ +\* Sabotage. The listener ensure step is removed, so the override can still copy port 0. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + FixRedirectUri = TRUE + EnsureListener = FALSE + CachedClient = TRUE +INVARIANTS TypeOK NoBadOpen diff --git a/docs/architecture/tla/McpOAuthRedirectUrl.NoOverride.cfg b/docs/architecture/tla/McpOAuthRedirectUrl.NoOverride.cfg new file mode 100644 index 00000000000..0e436f7f7d1 --- /dev/null +++ b/docs/architecture/tla/McpOAuthRedirectUrl.NoOverride.cfg @@ -0,0 +1,8 @@ +\* Sabotage. The redirect_uri override is removed. The invariant must fail. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + FixRedirectUri = FALSE + EnsureListener = TRUE + CachedClient = TRUE +INVARIANTS TypeOK NoBadOpen diff --git a/docs/architecture/tla/McpOAuthRedirectUrl.cfg b/docs/architecture/tla/McpOAuthRedirectUrl.cfg new file mode 100644 index 00000000000..b14de8b8f34 --- /dev/null +++ b/docs/architecture/tla/McpOAuthRedirectUrl.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + FixRedirectUri = TRUE + EnsureListener = TRUE + CachedClient = TRUE +INVARIANTS TypeOK NoBadOpen diff --git a/docs/architecture/tla/McpOAuthRedirectUrl.tla b/docs/architecture/tla/McpOAuthRedirectUrl.tla new file mode 100644 index 00000000000..8bff3fd6948 --- /dev/null +++ b/docs/architecture/tla/McpOAuthRedirectUrl.tla @@ -0,0 +1,85 @@ +---- MODULE McpOAuthRedirectUrl ---- +\* Source: StreamableHTTPClientTransport auth() builds the authorization URL from +\* provider.redirectUrl before McpOAuthClientProvider.redirectToAuthorization runs. +\* Sink: McpHub._completeOAuthFlow opens the stored URL with authProvider.openBrowser(). +\* Failure: the opened URL carries redirect_uri port 0, because a cached client +\* returns early from registerClientIfNeeded() and never starts the listener. +\* Invariant: NoBadOpen. The opened URL redirect_uri equals the active listener +\* port and is never 0. +\* Fix rule: redirectToAuthorization starts the listener first, then overrides +\* redirect_uri. The rule covers the first connect and a later 401. +\* Scope: registerClientIfNeeded and openBrowser are oracles. The listener starts +\* only inside those two calls, as in the code. A listener that dies between the +\* URL store and the open is out of scope; the next flow stores a fresh URL. +\* A strict server that rejects a changed port is out of scope (issue follow-up). +\* Result: Fixed holds in 5 states. NoOverride fails at 4 states. NoEnsure fails +\* at 3 states. No additional failure was found. +\* Property test: src/services/mcp/__tests__/mcp-oauth-flow.property.spec.ts. + +CONSTANTS FixRedirectUri \* TRUE when redirectToAuthorization overrides redirect_uri +CONSTANTS EnsureListener \* TRUE when redirectToAuthorization starts the listener first +CONSTANTS CachedClient \* TRUE when the client registration is cached and skips DCR + +VARIABLES listenerPort \* port of the active callback listener; 0 when none +VARIABLES sdkUrlPort \* redirect_uri port the SDK wrote into the URL +VARIABLES finalUrlPort \* redirect_uri port on the URL after redirectToAuthorization +VARIABLES urlStored \* redirectToAuthorization stored the URL for openBrowser +VARIABLES opened \* the URL was opened for the user +VARIABLES badOpen \* latch: an open used a stale or zero port + +vars == <> + +Init == + /\ listenerPort = 0 + /\ sdkUrlPort = 0 + /\ finalUrlPort = 0 + /\ urlStored = FALSE + /\ opened = FALSE + /\ badOpen = FALSE + +\* registerClientIfNeeded: a fresh DCR starts the listener; a cached client +\* returns early and starts nothing. +RegisterClient == + /\ listenerPort' = IF CachedClient \/ listenerPort # 0 THEN listenerPort ELSE 1 + /\ UNCHANGED <> + +\* The SDK builds the URL from provider.redirectUrl before the listener starts. +SdkBuildsUrl == + /\ sdkUrlPort' = listenerPort + /\ UNCHANGED <> + +\* redirectToAuthorization: ensure the listener owns a real port, then set redirect_uri. +Redirect == + /\ listenerPort' = IF EnsureListener /\ listenerPort = 0 THEN 1 ELSE listenerPort + /\ finalUrlPort' = IF FixRedirectUri THEN listenerPort' ELSE sdkUrlPort + /\ urlStored' = TRUE + /\ UNCHANGED <> + +\* The user confirmed the toast and the stored URL is opened. A stale or zero +\* port at open time is a bad open. +OpenBrowser == + /\ urlStored + /\ opened' = TRUE + /\ badOpen' = (badOpen \/ finalUrlPort # listenerPort \/ finalUrlPort = 0) + /\ UNCHANGED <> + +Next == + \/ RegisterClient + \/ SdkBuildsUrl + \/ Redirect + \/ OpenBrowser + +Spec == Init /\ [][Next]_vars + +TypeOK == + /\ listenerPort \in {0, 1} + /\ sdkUrlPort \in {0, 1} + /\ finalUrlPort \in {0, 1} + /\ urlStored \in BOOLEAN + /\ opened \in BOOLEAN + /\ badOpen \in BOOLEAN + +\* The opened URL always carries the active listener port, and never port 0. +NoBadOpen == ~badOpen + +==== diff --git a/docs/architecture/tla/McpOAuthStatusHandoff.NoEarlyNotify.cfg b/docs/architecture/tla/McpOAuthStatusHandoff.NoEarlyNotify.cfg new file mode 100644 index 00000000000..eb40d3361e7 --- /dev/null +++ b/docs/architecture/tla/McpOAuthStatusHandoff.NoEarlyNotify.cfg @@ -0,0 +1,6 @@ +\* Sabotage. The status change no longer updates the panel. The invariant must fail. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + NotifyOnConnected = FALSE +INVARIANTS TypeOK PanelShowsConnected diff --git a/docs/architecture/tla/McpOAuthStatusHandoff.cfg b/docs/architecture/tla/McpOAuthStatusHandoff.cfg new file mode 100644 index 00000000000..d5eb42498c0 --- /dev/null +++ b/docs/architecture/tla/McpOAuthStatusHandoff.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + NotifyOnConnected = TRUE +INVARIANTS TypeOK PanelShowsConnected diff --git a/docs/architecture/tla/McpOAuthStatusHandoff.tla b/docs/architecture/tla/McpOAuthStatusHandoff.tla new file mode 100644 index 00000000000..7b4853f6696 --- /dev/null +++ b/docs/architecture/tla/McpOAuthStatusHandoff.tla @@ -0,0 +1,67 @@ +---- MODULE McpOAuthStatusHandoff ---- +EXTENDS Naturals +\* Source: McpHub.connectToServer sets server.status to "connected" and then +\* awaits fetchToolsList, fetchResourcesList, and fetchResourceTemplatesList. +\* Sink: notifyWebviewOfServerChanges pushes the server list to the MCP panel. +\* Failure: the panel shows "connecting" until every list request finishes, and a +\* list request can wait a full request timeout (issue 2761, reproduction row: +\* three slow list requests delayed the first panel update to 3 s). +\* Invariant: PanelShowsConnected. When the server status is "connected", the +\* panel already shows "connected", even while list requests are pending. +\* Fix rule: notifyWebviewOfServerChanges runs when the status changes, and runs +\* again when the lists arrive. +\* Scope: one server, one connect, and up to two list requests. Reconnects, +\* 401 flows, and transport errors are outside this model. +\* Expect: Fixed holds. NoEarlyNotify fails. +\* Result: Fixed holds in 4 states. NoEarlyNotify fails at 2 states +\* (PanelShowsConnected). No additional failure was found. +\* Property test: src/services/mcp/__tests__/mcp-oauth-flow.property.spec.ts. + +CONSTANTS NotifyOnConnected \* TRUE when the status change itself updates the panel + +VARIABLES status \* connection status the hub holds for the server +VARIABLES panelStatus \* status the panel last received +VARIABLES pendingLists \* list requests not finished yet (0 to 2) +VARIABLES listsArrived \* the list results were fetched + +vars == <> + +Init == + /\ status = "connecting" + /\ panelStatus = "connecting" + /\ pendingLists = 0 + /\ listsArrived = FALSE + +\* client.connect succeeded. The fix updates the panel in the same step; the +\* old code only fetched the lists here. +ConnectOk == + /\ status' = "connected" + /\ pendingLists' = 2 + /\ listsArrived' = FALSE + /\ panelStatus' = IF NotifyOnConnected THEN "connected" ELSE panelStatus + +\* A list request finished. Only after all of them does the old code update the +\* panel; the fix updates again when the lists arrive. +ListDone == + /\ pendingLists >= 1 + /\ pendingLists' = pendingLists - 1 + /\ panelStatus' = IF pendingLists = 1 THEN "connected" ELSE panelStatus + /\ listsArrived' = (pendingLists = 1) + /\ UNCHANGED status + +Next == + \/ ConnectOk + \/ ListDone + +Spec == Init /\ [][Next]_vars + +TypeOK == + /\ status \in {"connecting", "connected"} + /\ panelStatus \in {"connecting", "connected"} + /\ pendingLists \in 0 .. 2 + /\ listsArrived \in BOOLEAN + +\* While the lists are still pending, the panel already shows connected. +PanelShowsConnected == (status = "connected" /\ ~listsArrived) => panelStatus = "connected" + +==== diff --git a/src/i18n/locales/ca/mcp.json b/src/i18n/locales/ca/mcp.json index 2bfbec328b3..2ff24bf0b4b 100644 --- a/src/i18n/locales/ca/mcp.json +++ b/src/i18n/locales/ca/mcp.json @@ -40,6 +40,7 @@ "authenticateButton": "Autenticar", "cancelled": "L'autenticació OAuth ha estat cancel·lada", "timedOut": "L'autenticació OAuth ha expirat", + "retriesExhausted": "L'inici de sessió OAuth per \"{{name}}\" ha fallat després de diversos intents. Torna a connectar el servidor per iniciar la sessió de nou.", "connected": "El servidor MCP \"{{name}}\" s'ha connectat correctament després de l'autenticació OAuth." } } diff --git a/src/i18n/locales/de/mcp.json b/src/i18n/locales/de/mcp.json index be492a0268f..ed32e53c7d9 100644 --- a/src/i18n/locales/de/mcp.json +++ b/src/i18n/locales/de/mcp.json @@ -39,6 +39,7 @@ "authenticateButton": "Authentifizieren", "cancelled": "OAuth-Authentifizierung wurde abgebrochen", "timedOut": "OAuth-Authentifizierung ist abgelaufen", + "retriesExhausted": "Die OAuth-Anmeldung für \"{{name}}\" ist nach wiederholten Versuchen fehlgeschlagen. Verbinde den Server erneut, um dich neu anzumelden.", "connected": "MCP-Server \"{{name}}\" wurde nach der OAuth-Authentifizierung erfolgreich verbunden." } } diff --git a/src/i18n/locales/en/mcp.json b/src/i18n/locales/en/mcp.json index e309bbd7b87..27be1231695 100644 --- a/src/i18n/locales/en/mcp.json +++ b/src/i18n/locales/en/mcp.json @@ -39,6 +39,7 @@ "authenticateButton": "Authenticate", "cancelled": "OAuth authentication was cancelled", "timedOut": "OAuth authentication timed out", + "retriesExhausted": "OAuth sign-in for \"{{name}}\" failed after repeated retries. Reconnect the server to sign in again.", "connected": "MCP server \"{{name}}\" connected successfully after OAuth authentication." } } diff --git a/src/i18n/locales/es/mcp.json b/src/i18n/locales/es/mcp.json index a65d37a5009..bf3f1ec508a 100644 --- a/src/i18n/locales/es/mcp.json +++ b/src/i18n/locales/es/mcp.json @@ -40,6 +40,7 @@ "authenticateButton": "Autenticar", "cancelled": "La autenticación OAuth fue cancelada", "timedOut": "La autenticación OAuth ha expirado", + "retriesExhausted": "El inicio de sesión OAuth para \"{{name}}\" falló después de varios intentos. Vuelve a conectar el servidor para iniciar sesión de nuevo.", "connected": "El servidor MCP \"{{name}}\" se conectó correctamente tras la autenticación OAuth." } } diff --git a/src/i18n/locales/fr/mcp.json b/src/i18n/locales/fr/mcp.json index ba05cc0e9cd..6dcda367de9 100644 --- a/src/i18n/locales/fr/mcp.json +++ b/src/i18n/locales/fr/mcp.json @@ -40,6 +40,7 @@ "authenticateButton": "Authentifier", "cancelled": "L'authentification OAuth a été annulée", "timedOut": "L'authentification OAuth a expiré", + "retriesExhausted": "La connexion OAuth pour \"{{name}}\" a échoué après plusieurs tentatives. Reconnectez le serveur pour vous connecter à nouveau.", "connected": "Le serveur MCP \"{{name}}\" s'est connecté avec succès après l'authentification OAuth." } } diff --git a/src/i18n/locales/hi/mcp.json b/src/i18n/locales/hi/mcp.json index 2536e79922e..e014d9c1c67 100644 --- a/src/i18n/locales/hi/mcp.json +++ b/src/i18n/locales/hi/mcp.json @@ -39,6 +39,7 @@ "authenticateButton": "प्रमाणित करें", "cancelled": "OAuth प्रमाणीकरण रद्द किया गया", "timedOut": "OAuth प्रमाणीकरण का समय समाप्त हो गया", + "retriesExhausted": "\"{{name}}\" के लिए OAuth साइन-इन बार-बार प्रयासों के बाद विफल हो गया। फिर से साइन इन करने के लिए सर्वर को पुनः कनेक्ट करें।", "connected": "OAuth प्रमाणीकरण के बाद MCP सर्वर \"{{name}}\" सफलतापूर्वक कनेक्ट हो गया।" } } diff --git a/src/i18n/locales/id/mcp.json b/src/i18n/locales/id/mcp.json index cd9e0c3b369..8774952ad4b 100644 --- a/src/i18n/locales/id/mcp.json +++ b/src/i18n/locales/id/mcp.json @@ -38,6 +38,7 @@ "authenticateButton": "Autentikasi", "cancelled": "Autentikasi OAuth dibatalkan", "timedOut": "Autentikasi OAuth habis waktu", + "retriesExhausted": "Proses masuk OAuth untuk \"{{name}}\" gagal setelah beberapa kali percobaan. Sambungkan ulang server untuk masuk kembali.", "connected": "Server MCP \"{{name}}\" berhasil terhubung setelah autentikasi OAuth." } } diff --git a/src/i18n/locales/it/mcp.json b/src/i18n/locales/it/mcp.json index 7927818cb30..c69291cc4e9 100644 --- a/src/i18n/locales/it/mcp.json +++ b/src/i18n/locales/it/mcp.json @@ -40,6 +40,7 @@ "authenticateButton": "Autenticarsi", "cancelled": "L'autenticazione OAuth è stata annullata", "timedOut": "L'autenticazione OAuth è scaduta", + "retriesExhausted": "L'accesso OAuth per \"{{name}}\" non è riuscito dopo ripetuti tentativi. Riconnetti il server per accedere di nuovo.", "connected": "Il server MCP \"{{name}}\" si è connesso con successo dopo l'autenticazione OAuth." } } diff --git a/src/i18n/locales/ja/mcp.json b/src/i18n/locales/ja/mcp.json index e7850e6640b..00f58c0afd4 100644 --- a/src/i18n/locales/ja/mcp.json +++ b/src/i18n/locales/ja/mcp.json @@ -38,6 +38,7 @@ "authenticateButton": "認証する", "cancelled": "OAuth認証がキャンセルされました", "timedOut": "OAuth認証がタイムアウトしました", + "retriesExhausted": "\"{{name}}\"のOAuthサインインは繰り返し失敗しました。サーバーに再接続して再度サインインしてください。", "connected": "OAuth認証後、MCPサーバー \"{{name}}\" が正常に接続されました。" } } diff --git a/src/i18n/locales/ko/mcp.json b/src/i18n/locales/ko/mcp.json index 5422f14506a..4e456d6c3c4 100644 --- a/src/i18n/locales/ko/mcp.json +++ b/src/i18n/locales/ko/mcp.json @@ -38,6 +38,7 @@ "authenticateButton": "인증", "cancelled": "OAuth 인증이 취소되었습니다", "timedOut": "OAuth 인증 시간이 초과되었습니다", + "retriesExhausted": "\"{{name}}\"의 OAuth 로그인이 반복된 재시도 후 실패했습니다. 서버에 다시 연결하여 다시 로그인하세요.", "connected": "OAuth 인증 후 MCP 서버 \"{{name}}\"가 성공적으로 연결되었습니다." } } diff --git a/src/i18n/locales/nl/mcp.json b/src/i18n/locales/nl/mcp.json index a0898b31395..5b9826ae8ca 100644 --- a/src/i18n/locales/nl/mcp.json +++ b/src/i18n/locales/nl/mcp.json @@ -39,6 +39,7 @@ "authenticateButton": "Authenticeren", "cancelled": "OAuth-authenticatie is geannuleerd", "timedOut": "OAuth-authenticatie is verlopen", + "retriesExhausted": "OAuth-aanmelding voor \"{{name}}\" is na herhaalde pogingen mislukt. Verbind de server opnieuw om opnieuw aan te melden.", "connected": "MCP-server \"{{name}}\" is succesvol verbonden na OAuth-authenticatie." } } diff --git a/src/i18n/locales/pl/mcp.json b/src/i18n/locales/pl/mcp.json index 44242522ad4..28e121b353f 100644 --- a/src/i18n/locales/pl/mcp.json +++ b/src/i18n/locales/pl/mcp.json @@ -41,6 +41,7 @@ "authenticateButton": "Uwierzytelnij", "cancelled": "Uwierzytelnianie OAuth zostało anulowane", "timedOut": "Uwierzytelnianie OAuth przekroczyło limit czasu", + "retriesExhausted": "Logowanie OAuth dla \"{{name}}\" nie powiodło się po wielu próbach. Połącz serwer ponownie, aby zalogować się jeszcze raz.", "connected": "Serwer MCP \"{{name}}\" połączył się pomyślnie po uwierzytelnieniu OAuth." } } diff --git a/src/i18n/locales/pt-BR/mcp.json b/src/i18n/locales/pt-BR/mcp.json index ff019a6a404..f52a7d5c69b 100644 --- a/src/i18n/locales/pt-BR/mcp.json +++ b/src/i18n/locales/pt-BR/mcp.json @@ -40,6 +40,7 @@ "authenticateButton": "Autenticar", "cancelled": "A autenticação OAuth foi cancelada", "timedOut": "A autenticação OAuth expirou", + "retriesExhausted": "O login OAuth para \"{{name}}\" falhou após repetidas tentativas. Reconecte o servidor para entrar novamente.", "connected": "O servidor MCP \"{{name}}\" foi conectado com sucesso após a autenticação OAuth." } } diff --git a/src/i18n/locales/ru/mcp.json b/src/i18n/locales/ru/mcp.json index b1296fcbb80..138449325b7 100644 --- a/src/i18n/locales/ru/mcp.json +++ b/src/i18n/locales/ru/mcp.json @@ -41,6 +41,7 @@ "authenticateButton": "Аутентифицировать", "cancelled": "Аутентификация OAuth отменена", "timedOut": "Время аутентификации OAuth истекло", + "retriesExhausted": "Вход OAuth для \"{{name}}\" не удалось выполнить после повторных попыток. Подключите сервер заново, чтобы войти снова.", "connected": "Сервер MCP \"{{name}}\" успешно подключён после аутентификации OAuth." } } diff --git a/src/i18n/locales/tr/mcp.json b/src/i18n/locales/tr/mcp.json index f753324d3cf..f444fe83661 100644 --- a/src/i18n/locales/tr/mcp.json +++ b/src/i18n/locales/tr/mcp.json @@ -39,6 +39,7 @@ "authenticateButton": "Kimlik Doğrula", "cancelled": "OAuth kimlik doğrulaması iptal edildi", "timedOut": "OAuth kimlik doğrulaması zaman aşımına uğradı", + "retriesExhausted": "\"{{name}}\" için OAuth oturum açma işlemi tekrarlanan denemelerden sonra başarısız oldu. Tekrar oturum açmak için sunucuya yeniden bağlanın.", "connected": "MCP sunucusu \"{{name}}\" OAuth kimlik doğrulamasından sonra başarıyla bağlandı." } } diff --git a/src/i18n/locales/vi/mcp.json b/src/i18n/locales/vi/mcp.json index ca67e58fd22..ff4b9018097 100644 --- a/src/i18n/locales/vi/mcp.json +++ b/src/i18n/locales/vi/mcp.json @@ -38,6 +38,7 @@ "authenticateButton": "Xác thực", "cancelled": "Xác thực OAuth đã bị hủy", "timedOut": "Xác thực OAuth đã hết thời gian chờ", + "retriesExhausted": "Đăng nhập OAuth cho \"{{name}}\" đã thất bại sau nhiều lần thử. Kết nối lại máy chủ để đăng nhập lại.", "connected": "Máy chủ MCP \"{{name}}\" đã kết nối thành công sau khi xác thực OAuth." } } diff --git a/src/i18n/locales/zh-CN/mcp.json b/src/i18n/locales/zh-CN/mcp.json index 0fba9e23c8e..6cc8e0b67c8 100644 --- a/src/i18n/locales/zh-CN/mcp.json +++ b/src/i18n/locales/zh-CN/mcp.json @@ -38,6 +38,7 @@ "authenticateButton": "验证身份", "cancelled": "OAuth 身份验证已取消", "timedOut": "OAuth 身份验证已超时", + "retriesExhausted": "{{name}} 的 OAuth 登录在多次重试后失败。请重新连接服务器以再次登录。", "connected": "OAuth 身份验证后,MCP 服务 \"{{name}}\" 已成功连接。" } } diff --git a/src/i18n/locales/zh-TW/mcp.json b/src/i18n/locales/zh-TW/mcp.json index b5468882d1e..5246afa57da 100644 --- a/src/i18n/locales/zh-TW/mcp.json +++ b/src/i18n/locales/zh-TW/mcp.json @@ -38,6 +38,7 @@ "authenticateButton": "驗證身份", "cancelled": "OAuth 身份驗證已取消", "timedOut": "OAuth 身份驗證已逾時", + "retriesExhausted": "{{name}} 的 OAuth 登入在多次重試後失敗。請重新連接伺服器以再次登入。", "connected": "OAuth 身份驗證後,MCP 伺服器 \"{{name}}\" 已成功連線。" } } diff --git a/src/services/mcp/McpHub.ts b/src/services/mcp/McpHub.ts index 818729c46b9..e5141c50188 100644 --- a/src/services/mcp/McpHub.ts +++ b/src/services/mcp/McpHub.ts @@ -37,7 +37,13 @@ import { GlobalFileNames } from "../../shared/globalFileNames" import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js" import { fileExistsAtPath } from "../../utils/fs" -import { TOKEN_EXPIRY_BUFFER_MS, OAUTH_FLOW_TIMEOUT_MS } from "./constants" +import { + OAUTH_FLOW_TIMEOUT_MS, + OAUTH_TOKEN_RETRY_BASE_DELAY_MS, + OAUTH_TOKEN_RETRY_MAX_ATTEMPTS, + OAUTH_TOKEN_RETRY_MAX_DELAY_MS, + TOKEN_EXPIRY_BUFFER_MS, +} from "./constants" import { SecretStorageService } from "./SecretStorageService" import { McpOAuthClientProvider } from "./McpOAuthClientProvider" import { arePathsEqual, getWorkspacePath } from "../../utils/path" @@ -64,6 +70,17 @@ export type DisconnectedMcpConnection = { export type McpConnection = ConnectedMcpConnection | DisconnectedMcpConnection +/** + * A registered OAuth flow watcher: the cross-window token subscription, its + * flow timeout, and the shared removal path that also ends the flow. + */ +interface McpOAuthWatcher { + unsubscribe: () => void + abortHandle: NodeJS.Timeout + /** Ends the flow this watcher belongs to. Idempotent; never removes another flow's entry. */ + endFlow: () => void +} + // Enum for disable reasons export enum DisableReason { MCP_DISABLED = "mcpDisabled", @@ -201,8 +218,10 @@ export class McpHub { private sanitizedNameRegistry: Map = new Map() private initializationPromise: Promise private secretStorage?: SecretStorageService - private reauthPromises: Map> = new Map() - private _oauthWatchers: Map void; abortHandle: NodeJS.Timeout }> = new Map() + private reauthPromises: Map> = new Map() + private _oauthWatchers: Map = new Map() + /** Tracks automatic reconnects that reuse a saved token the server rejected, per server URL. */ + private oauthTokenRetries: Map = new Map() constructor(provider: ClineProvider, secretStorage?: SecretStorageService) { this.providerRef = new WeakRef(provider) @@ -904,7 +923,10 @@ export class McpHub { // Mid-session re-auth triggered by a tool call (401) connection.server.status = "connecting" - const reauthKey = `${name}:${source}` + // Key the re-auth flow by the connection itself, not the server + // name. A key shared across connections lets an old flow swallow + // the 401 of a newer connection and leave it connecting forever. + const reauthKey = connection let reauthPromise = this.reauthPromises.get(reauthKey) if (!reauthPromise) { reauthPromise = this._initiateOAuthFlow( @@ -1071,10 +1093,21 @@ export class McpHub { connection.server.error = "" connection.server.instructions = client.getInstructions() + // A successful connect also resets the rejected-token retry bound. + if (configInjected.type === "streamable-http" && configInjected.url) { + this.oauthTokenRetries.delete(configInjected.url) + } + + // The list requests below can each take up to the request timeout. Update + // the panel now so the server shows connected immediately, then update it + // again when the tool, resource, and template lists arrive. + await this.notifyWebviewOfServerChanges() + // Initial fetch of tools and resources connection.server.tools = await this.fetchToolsList(name, source) connection.server.resources = await this.fetchResourcesList(name, source) connection.server.resourceTemplates = await this.fetchResourceTemplatesList(name, source) + await this.notifyWebviewOfServerChanges() } catch (error) { await pendingAuthProvider?.close() // Update status with error @@ -1147,10 +1180,31 @@ export class McpHub { unsubscribeCrossWindow() if (!this.isDisposed && tokenToUse && Date.now() < tokenToUse.expires_at - TOKEN_EXPIRY_BUFFER_MS) { + // The server just rejected this saved token. Reconnect after a delay, a + // bounded number of times. Without the bound, an always-rejecting server + // turns this path into an unlimited reconnect loop. + const tokenKey = tokenToUse.tokens?.access_token + const retryState = this.oauthTokenRetries.get(serverUrl) + const attempt = retryState && retryState.tokenKey === tokenKey ? retryState.count + 1 : 1 + if (attempt > OAUTH_TOKEN_RETRY_MAX_ATTEMPTS) { + // A new token resets the count; the same rejected token does not get + // another automatic retry. End with a visible error instead. + this.oauthTokenRetries.delete(serverUrl) + await this._surfaceOAuthReconnectFailure(name, source, t("mcp:oauth.flow.retriesExhausted", { name })) + return + } + this.oauthTokenRetries.set(serverUrl, { tokenKey, count: attempt }) + await delay(Math.min(OAUTH_TOKEN_RETRY_BASE_DELAY_MS * 2 ** (attempt - 1), OAUTH_TOKEN_RETRY_MAX_DELAY_MS)) await authProvider.close() await this.deleteConnection(name, source) - await this.connectToServer(name, config, source) - await this.notifyWebviewOfServerChanges() + try { + await this.connectToServer(name, config, source) + await this.notifyWebviewOfServerChanges() + } catch (error) { + // A reconnect that throws must not propagate out of this detached flow: + // connectToServer already surfaced the error on the server status. + console.error(`[McpHub] OAuth reconnect failed for "${name}":`, error) + } return } @@ -1178,6 +1232,24 @@ export class McpHub { ) } + /** + * Ends a reconnect episode with a visible error: the server status becomes + * disconnected and the message is recorded, so the panel shows why the + * sign-in did not finish. + */ + private async _surfaceOAuthReconnectFailure( + name: string, + source: "global" | "project", + message: string, + ): Promise { + const conn = this.findConnection(name, source) + if (conn && conn.server.status !== "connected") { + conn.server.status = "disconnected" + this.appendErrorMessage(conn, message) + await this.notifyWebviewOfServerChanges() + } + } + private _runOAuthFlow( name: string, source: "global" | "project", @@ -1192,16 +1264,18 @@ export class McpHub { ): Promise { const watcherKey = `${name}:${source}` - // Cancel any existing watcher for this connection before starting a new one - const existing = this._oauthWatchers.get(watcherKey) - if (existing) { - existing.unsubscribe() - clearTimeout(existing.abortHandle) - this._oauthWatchers.delete(watcherKey) - } + // Cancel any existing watcher for this connection before starting a new one. + // The shared removal path also ends the replaced flow, so it cannot stay + // pending after its watcher is gone. + this._endOAuthWatcher(watcherKey) return new Promise((resolve) => { let disposed = false + // A const holder keeps the TDZ safety: the cancellation callback can fire + // synchronously during registration, before the assignment completes. It + // then reads undefined and cleanup() runs without a disposable, which is + // correct. + const cancellation = { disposable: undefined as vscode.Disposable | undefined } const cleanup = (disposable?: vscode.Disposable) => { if (disposed) return @@ -1209,7 +1283,10 @@ export class McpHub { clearTimeout(timeoutHandle) unsubscribe() disposable?.dispose() - this._oauthWatchers.delete(watcherKey) + // An ended flow must not remove a newer flow's watcher for this key. + if (this._oauthWatchers.get(watcherKey) === watcher) { + this._oauthWatchers.delete(watcherKey) + } } // --- Cross-window token watcher --- @@ -1219,7 +1296,7 @@ export class McpHub { // from another window fired after _completeOAuthFlow already succeeded). const conn = this.findConnection(name, source) if (!conn || conn.server.status === "connected") { - cleanup(cancellationDisposable) + cleanup(cancellation.disposable) return } try { @@ -1228,7 +1305,7 @@ export class McpHub { // fired while getOAuthData was in flight. if (disposed || this.isDisposed) return if (data && Date.now() < data.expires_at - TOKEN_EXPIRY_BUFFER_MS) { - cleanup(cancellationDisposable) + cleanup(cancellation.disposable) await authProvider.close() await this.deleteConnection(name, source) const validatedConfig = this.validateServerConfig(config, name) @@ -1237,7 +1314,18 @@ export class McpHub { resolve() } } catch (err) { + // A reconnect that throws must not leave this flow pending: end the + // flow and surface the error on the server status. console.error(`[McpHub] OAuth token watcher failed for "${name}":`, err) + cleanup(cancellation.disposable) + void authProvider.close() + const conn = this.findConnection(name, source) + if (conn && conn.server.status !== "connected") { + conn.server.status = "disconnected" + this.appendErrorMessage(conn, err instanceof Error ? err.message : `${err}`) + void this.notifyWebviewOfServerChanges() + } + resolve() } } @@ -1252,7 +1340,7 @@ export class McpHub { // --- Timeout --- const timeoutHandle = setTimeout(() => { if (disposed) return - cleanup(cancellationDisposable) + cleanup(cancellation.disposable) void authProvider.close() const conn = this.findConnection(name, source) if (conn && conn.server.status === "connecting") { @@ -1269,18 +1357,29 @@ export class McpHub { // synchronously inside onCancellationRequested(...), and cleanup() must find // the watcher entry in the map in order to delete it. Registering after the // callback would leave an orphan entry that survives disposal. - this._oauthWatchers.set(watcherKey, { unsubscribe, abortHandle: timeoutHandle }) + const watcher: McpOAuthWatcher = { + unsubscribe, + abortHandle: timeoutHandle, + // Shared removal path: an external removal (deleteConnection, flow + // replacement, dispose) ends this flow instead of leaving it pending. + endFlow: () => { + if (disposed) return + cleanup(cancellation.disposable) + resolve() + }, + } + this._oauthWatchers.set(watcherKey, watcher) // --- Cancellation (progress bar's Cancel button) --- - const cancellationDisposable = cancellationToken.onCancellationRequested(() => { + cancellation.disposable = cancellationToken.onCancellationRequested(() => { if (disposed) return - // Don't pass cancellationDisposable here: if the token was already + // Don't pass cancellation.disposable here: if the token was already // cancelled at registration time, VS Code fires this callback // synchronously inside onCancellationRequested(...) — before the - // `const cancellationDisposable = ...` assignment completes, so the - // binding is still in the TDZ. VS Code also disposes its own - // listener once the token transitions to cancelled, so explicit - // disposal from inside the callback would be redundant anyway. + // assignment completes, so the holder still holds undefined. VS Code + // also disposes its own listener once the token transitions to + // cancelled, so explicit disposal from inside the callback would be + // redundant anyway. cleanup() void authProvider.close() const conn = this.findConnection(name, source) @@ -1295,7 +1394,7 @@ export class McpHub { // In test mode, skip user interaction and proceed directly to complete the OAuth flow. if (process.env.MCP_OAUTH_TEST_MODE === "true") { void (async () => { - cleanup(cancellationDisposable) + cleanup(cancellation.disposable) try { await this._completeOAuthFlow( authProvider, @@ -1333,12 +1432,24 @@ export class McpHub { const tokens = await this.secretStorage!.getOAuthData(serverUrl, oauthClientId) if (disposed) return if (tokens && Date.now() < tokens.expires_at - TOKEN_EXPIRY_BUFFER_MS) { - cleanup(cancellationDisposable) - await authProvider.close() - await this.deleteConnection(name, source) - const validatedFastPathConfig = this.validateServerConfig(config, name) - await this.connectToServer(name, validatedFastPathConfig, source) - await this.notifyWebviewOfServerChanges() + cleanup(cancellation.disposable) + try { + await authProvider.close() + await this.deleteConnection(name, source) + const validatedFastPathConfig = this.validateServerConfig(config, name) + await this.connectToServer(name, validatedFastPathConfig, source) + await this.notifyWebviewOfServerChanges() + } catch (error) { + // A reconnect that throws must not leave this flow pending: end the + // flow and surface the error on the server status. + await authProvider.close().catch(() => {}) + const conn = this.findConnection(name, source) + if (conn && conn.server.status !== "connected") { + conn.server.status = "disconnected" + this.appendErrorMessage(conn, error instanceof Error ? error.message : `${error}`) + void this.notifyWebviewOfServerChanges() + } + } resolve() return } @@ -1346,7 +1457,7 @@ export class McpHub { // Clean up before exchanging tokens — this sets disposed=true so the // cross-window token watcher doesn't race to reconnect when SecretStorage // fires onDidChange during token exchange inside _completeOAuthFlow. - cleanup(cancellationDisposable) + cleanup(cancellation.disposable) try { await this._completeOAuthFlow(authProvider, transport, connection, name, source, cancellationToken) } catch { @@ -1595,15 +1706,29 @@ export class McpHub { } } - async deleteConnection(name: string, source?: "global" | "project"): Promise { - // Cancel any active OAuth token watchers for this connection - const watcherKey = `${name}:${source}` + /** + * Shared removal path for an OAuth watcher: ends the flow the watcher + * belongs to. deleteConnection(), flow replacement in _runOAuthFlow(), and + * dispose() must all go through this so a removed watcher never leaves its + * flow pending. The flow's own cleanup unsubscribes and clears the timeout, + * so each listener still runs exactly once. + * + * @returns true when a watcher was registered under this key. + */ + private _endOAuthWatcher(watcherKey: string): boolean { const watcher = this._oauthWatchers.get(watcherKey) - if (watcher) { - watcher.unsubscribe() - clearTimeout(watcher.abortHandle) - this._oauthWatchers.delete(watcherKey) - } + if (!watcher) return false + // Remove first so the ended flow's cleanup cannot see this entry again, + // and so it can never remove a newer flow's watcher under this key. + this._oauthWatchers.delete(watcherKey) + watcher.endFlow() + return true + } + + async deleteConnection(name: string, source?: "global" | "project"): Promise { + // Cancel any active OAuth flow for this connection. The shared path also + // ends the flow, so tool calls waiting on it are released immediately. + this._endOAuthWatcher(`${name}:${source}`) // Clean up file watchers for this server this.removeFileWatchersForServer(name) @@ -2302,7 +2427,10 @@ export class McpHub { // Mid-session re-auth triggered by a tool call (401) connection.server.status = "connecting" - const reauthKey = `${serverName}:${source || connection.server.source || "global"}` + // Key the re-auth flow by the connection itself, not the server name. + // A key shared across connections lets an old flow swallow the 401 of a + // newer connection, and a tool call would wait on the wrong flow. + const reauthKey = connection let reauthPromise = this.reauthPromises.get(reauthKey) if (!reauthPromise) { @@ -2557,13 +2685,13 @@ export class McpHub { this.isProgrammaticUpdate = false - // Cancel all active OAuth token watchers and in-flight reauth promises - for (const { unsubscribe, abortHandle } of this._oauthWatchers.values()) { - unsubscribe() - clearTimeout(abortHandle) + // End all active OAuth flows and in-flight reauth promises through the + // shared removal path, so nothing stays pending after disposal. + for (const watcherKey of [...this._oauthWatchers.keys()]) { + this._endOAuthWatcher(watcherKey) } - this._oauthWatchers.clear() this.reauthPromises.clear() + this.oauthTokenRetries.clear() this.removeAllFileWatchers() diff --git a/src/services/mcp/McpOAuthClientProvider.ts b/src/services/mcp/McpOAuthClientProvider.ts index 794f53dcda7..be79d744076 100644 --- a/src/services/mcp/McpOAuthClientProvider.ts +++ b/src/services/mcp/McpOAuthClientProvider.ts @@ -343,6 +343,11 @@ export class McpOAuthClientProvider implements OAuthClientProvider { // Reuse the cached registration only for the issuer that created it. Otherwise // the stored client_secret would go to an authorization server the MCP server chose. if (cachedData?.client_info && cachedData.issuer === this._authServerMeta?.issuer) { + // The SDK can start an authorization for a cached client without going + // through DCR, so start the listener here too. redirectUrl then carries + // the active port instead of 0, and redirectToAuthorization() keeps the + // authorization URL's redirect_uri in sync with that port. + await this._ensureCallbackServer() // Use the full DCR response, override redirect_uris with the // current port (which may have changed between sessions). this._clientInfo = { @@ -453,6 +458,13 @@ export class McpOAuthClientProvider implements OAuthClientProvider { // openBrowser(), which McpHub calls only after the user confirms the toast. await this._ensureCallbackServer() + // The SDK built this URL before the listener started, so it can carry + // port 0 (a cached client returns early from registerClientIfNeeded() + // and never starts the listener there). Override redirect_uri now that + // the listener owns its final port. This covers the first connect and + // a later 401. + authorizationUrl.searchParams.set("redirect_uri", this.redirectUrl) + // Workaround for SDK metadata discovery bug (see utils/oauth.ts for issue links). // The SDK's discoverOAuthMetadata() builds a wrong well-known URL for issuers // with path components, causing it to fall back to a default "/authorize" path. diff --git a/src/services/mcp/__tests__/McpHub.spec.ts b/src/services/mcp/__tests__/McpHub.spec.ts index 35ff10d64b1..d7b6ab36238 100644 --- a/src/services/mcp/__tests__/McpHub.spec.ts +++ b/src/services/mcp/__tests__/McpHub.spec.ts @@ -12,7 +12,8 @@ import type { SecretStorageService } from "../SecretStorageService" import type { McpHub as McpHubType, McpConnection, ConnectedMcpConnection, DisconnectedMcpConnection } from "../McpHub" import { ServerConfigSchema, McpHub } from "../McpHub" import { McpOAuthClientProvider } from "../McpOAuthClientProvider" -import { OAUTH_FLOW_TIMEOUT_MS } from "../constants" +import { OAUTH_FLOW_TIMEOUT_MS, OAUTH_TOKEN_RETRY_MAX_ATTEMPTS } from "../constants" +import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js" import { t } from "../../../i18n" type McpHubPrivate = { @@ -3464,5 +3465,369 @@ describe("McpHub", () => { await vi.advanceTimersByTimeAsync(OAUTH_FLOW_TIMEOUT_MS) await secondFlow }) + + it("keeps the newer flow's watcher when the replaced flow's toast resolves later", async () => { + vi.useFakeTimers() + let resolveFirstToast: (choice?: string) => void + vsc.window.showInformationMessage.mockImplementationOnce( + () => + new Promise((resolve) => { + resolveFirstToast = resolve + }), + ) + vsc.window.showInformationMessage.mockImplementation(() => new Promise(() => {})) + + const hub = mcpHub as unknown as { + _oauthWatchers: Map + _initiateOAuthFlow: ( + name: string, + source: "global" | "project", + config: unknown, + authProvider: unknown, + transport: unknown, + connection: unknown, + ) => Promise + } + const watcherKey = `${serverName}:${source}` + + const firstFlow = hub._initiateOAuthFlow(serverName, source, config, mockAuthProvider, {}, mockConnection) + await vi.advanceTimersByTimeAsync(0) + const firstEntry = hub._oauthWatchers.get(watcherKey) + + const secondFlow = hub._initiateOAuthFlow(serverName, source, config, mockAuthProvider, {}, mockConnection) + await vi.advanceTimersByTimeAsync(0) + const secondEntry = hub._oauthWatchers.get(watcherKey) + expect(secondEntry).toBeDefined() + expect(secondEntry).not.toBe(firstEntry) + + // The stale toast resolves with Authenticate. The replaced flow is already + // disposed, so it must neither reconnect nor touch the newer flow's watcher. + resolveFirstToast!(t("mcp:oauth.flow.authenticateButton")) + await vi.advanceTimersByTimeAsync(0) + await firstFlow + + // The newer flow still owns the watcher: its unsubscribe never ran. + expect(secondEntry?.unsubscribe).not.toHaveBeenCalled() + expect(hub._oauthWatchers.get(watcherKey)).toBe(secondEntry) + + // The newer flow still ends through its own timeout. + await vi.advanceTimersByTimeAsync(OAUTH_FLOW_TIMEOUT_MS) + await secondFlow + expect(hub._oauthWatchers.size).toBe(0) + }) + + it("ends the flow and surfaces the error when the token-watcher reconnect throws", async () => { + vi.useFakeTimers() + const hub = mcpHub as unknown as { + _oauthWatchers: Map + _initiateOAuthFlow: ( + name: string, + source: "global" | "project", + config: unknown, + authProvider: unknown, + transport: unknown, + connection: unknown, + ) => Promise + appendErrorMessage: Mock & ((connection: unknown, message: string) => void) + connectToServer: Mock & ((...args: unknown[]) => Promise) + } + const closeMock = vi.fn().mockResolvedValue(undefined) + mockAuthProvider.close = closeMock + hub.connectToServer.mockRejectedValue(new Error("reconnect failed")) + // Two subscriptions happen: the cross-window pre-read watcher in + // _initiateOAuthFlow stays silent; the flow watcher delivers valid tokens. + let subscriptions = 0 + mockSecretStorage.onDidChange.mockImplementation((_url: string, cb: () => void) => { + subscriptions += 1 + if (subscriptions === 1) return vi.fn() + queueMicrotask(() => { + mockSecretStorage.getOAuthData.mockResolvedValue({ expires_at: Date.now() + 10 * 60 * 1000 }) + cb() + }) + return vi.fn() + }) + + // Must resolve through the catch path instead of staying pending forever. + await hub._initiateOAuthFlow(serverName, source, config, mockAuthProvider, {}, mockConnection) + + expect(mockConnection.server.status).toBe("disconnected") + expect(hub.appendErrorMessage).toHaveBeenCalledWith(mockConnection, "reconnect failed") + expect(closeMock).toHaveBeenCalled() + expect(hub._oauthWatchers.size).toBe(0) + }) + + it("ends the flow and surfaces the error when the Authenticate fast-path reconnect throws", async () => { + vsc.window.showInformationMessage.mockResolvedValueOnce(t("mcp:oauth.flow.authenticateButton")) + mockSecretStorage.getOAuthData + .mockResolvedValueOnce(undefined) // no tokens before the flow starts + .mockResolvedValue({ expires_at: Date.now() + 10 * 60 * 1000 }) // tokens at click time + const hub = mcpHub as unknown as { + _oauthWatchers: Map + _initiateOAuthFlow: ( + name: string, + source: "global" | "project", + config: unknown, + authProvider: unknown, + transport: unknown, + connection: unknown, + ) => Promise + appendErrorMessage: Mock & ((connection: unknown, message: string) => void) + connectToServer: Mock & ((...args: unknown[]) => Promise) + } + hub.connectToServer.mockRejectedValue(new Error("fast reconnect failed")) + + await hub._initiateOAuthFlow(serverName, source, config, mockAuthProvider, {}, mockConnection) + + expect(mockConnection.server.status).toBe("disconnected") + expect(hub.appendErrorMessage).toHaveBeenCalledWith(mockConnection, "fast reconnect failed") + expect(hub._oauthWatchers.size).toBe(0) + }) + + it("does not wait for an ended flow when a tool call hits a 401", async () => { + vi.useFakeTimers() + const requestMock = vi.fn().mockRejectedValue(new UnauthorizedError()) + // Minimal connected-connection double: request rejects with 401, the + // transport and client close, and the auth provider drives the flow. + const localConnection = { + type: "connected", + server: { name: serverName, config: JSON.stringify(config), status: "connected", source }, + client: { close: vi.fn().mockResolvedValue(undefined), request: requestMock }, + transport: { close: vi.fn().mockResolvedValue(undefined) }, + authProvider: mockAuthProvider, + } as unknown as ConnectedMcpConnection + mcpHub.connections = [localConnection] + + // This test drives the real findConnection, deleteConnection, and OAuth flow. + vi.mocked(mcpHub["findConnection"]).mockRestore() + vi.mocked(mcpHub["deleteConnection"]).mockRestore() + + const hub = mcpHub as unknown as { + _oauthWatchers: Map + callTool: typeof mcpHub.callTool + deleteConnection: (name: string, source?: "global" | "project") => Promise + } + + const callPromise = mcpHub.callTool(serverName, "some-tool", {}, source) + await vi.advanceTimersByTimeAsync(0) + // The 401 started a real OAuth flow and the tool call is waiting on it. + expect(hub._oauthWatchers.size).toBe(1) + expect(requestMock).toHaveBeenCalledTimes(1) + + // Deleting the connection ends the flow through the shared removal path. + // Attach the rejection expectation first so the fast failure is handled. + const callAssertion = expect(callPromise).rejects.toThrow( + `Failed to reconnect to server ${serverName} after OAuth`, + ) + await hub.deleteConnection(serverName, source) + await vi.advanceTimersByTimeAsync(1000) + + // The tool call must fail fast, not wait for the 5-minute flow timeout. + await callAssertion + expect(hub._oauthWatchers.size).toBe(0) + }) + }) + + describe("OAuth reconnect fault injection (connect path)", () => { + const serverName = "rejected-server" + const serverUrl = "https://rejected.example.com/mcp" + + /** + * Wires the SDK doubles so every `client.connect()` rejects with + * UnauthorizedError for the first `rejectCount` attempts. The saved token in + * SecretStorage never expires, so each 401 drives the automatic reconnect + * path exactly like the issue's fake-server reproduction did. + */ + async function setupRejectingServer(rejectCount: number): Promise<{ connectCount: () => number }> { + let connectCount = 0 + const connect = vi.fn(async () => { + connectCount += 1 + if (connectCount <= rejectCount) { + throw new UnauthorizedError() + } + }) + const streamableModule = await import("@modelcontextprotocol/sdk/client/streamableHttp.js") + vi.mocked(streamableModule.StreamableHTTPClientTransport).mockImplementation(function () { + return { close: vi.fn().mockResolvedValue(undefined) } as unknown as StreamableHTTPClientTransport + }) + const clientModule = await import("@modelcontextprotocol/sdk/client/index.js") + vi.mocked(clientModule.Client).mockImplementation(function () { + return { + connect, + close: vi.fn().mockResolvedValue(undefined), + getInstructions: vi.fn(), + request: vi.fn().mockResolvedValue({ tools: [], resources: [], resourceTemplates: [] }), + } as unknown as Client + }) + const authProvider = { + hasMetadata: true, + registerClientIfNeeded: vi.fn().mockResolvedValue(undefined), + close: vi.fn().mockResolvedValue(undefined), + } + vi.mocked(McpOAuthClientProvider.create).mockResolvedValue( + authProvider as unknown as McpOAuthClientProvider, + ) + return { connectCount: () => connectCount } + } + + /** A hub whose SecretStorage holds one unexpired, never-changing saved token. */ + async function createHubWithSavedToken(): Promise { + const secretStorage = { + hasOAuthData: vi.fn().mockResolvedValue(true), + getOAuthData: vi.fn().mockResolvedValue({ + tokens: { access_token: "rejected-token" }, + expires_at: Date.now() + 60 * 60 * 1000, + issuer: "https://auth.example.com", + }), + onDidChange: vi.fn().mockReturnValue(vi.fn()), + deleteOAuthData: vi.fn().mockResolvedValue(undefined), + } + // No project config in this harness: the project-level initialization + // must not connect a second copy of the server. + vi.mocked(fs.access).mockRejectedValue(new Error("no project config")) + vi.mocked(fs.readFile).mockResolvedValue( + JSON.stringify({ + mcpServers: { + [serverName]: { + type: "streamable-http", + url: serverUrl, + }, + }, + }), + ) + const hub = new McpHub(mockProvider as ClineProvider, secretStorage as unknown as SecretStorageService) + await hub.waitUntilReady() + return hub + } + + it("ends in connected when the server accepts the token after two 401s", async () => { + const { connectCount } = await setupRejectingServer(2) + const hub = await createHubWithSavedToken() + try { + await vi.waitFor(() => { + const conn = hub.connections.find((c) => c.server.name === serverName) + expect(conn?.server.status).toBe("connected") + }) + // Initial connect plus one reconnect per rejected attempt. + expect(connectCount()).toBe(3) + } finally { + await hub.dispose() + } + }) + + it("bounds the reconnect attempts and ends with a visible error for an always-rejecting server", async () => { + const { connectCount } = await setupRejectingServer(Number.POSITIVE_INFINITY) + const hub = await createHubWithSavedToken() + try { + await vi.waitFor(() => { + const conn = hub.connections.find((c) => c.server.name === serverName) + expect(conn?.server.status).toBe("disconnected") + }) + // One initial connect plus the bounded retries — then the loop stops. + expect(connectCount()).toBe(1 + OAUTH_TOKEN_RETRY_MAX_ATTEMPTS) + const conn = hub.connections.find((c) => c.server.name === serverName) + expect(conn?.server.error).toBe(t("mcp:oauth.flow.retriesExhausted", { name: serverName })) + // Let any remaining detached work settle; the count must stay bounded. + await new Promise((resolve) => setTimeout(resolve, 20)) + expect(connectCount()).toBe(1 + OAUTH_TOKEN_RETRY_MAX_ATTEMPTS) + } finally { + await hub.dispose() + } + }) + + it("delays each automatic reconnect of the same rejected token", async () => { + await setupRejectingServer(Number.POSITIVE_INFINITY) + const hub = await createHubWithSavedToken() + try { + const delayModule = await import("delay") + const delayMock = vi.mocked(delayModule.default) + await vi.waitFor(() => { + const conn = hub.connections.find((c) => c.server.name === serverName) + expect(conn?.server.status).toBe("disconnected") + }) + // Exponential backoff for the three bounded attempts. Filter out the + // unrelated short delays the hub uses elsewhere (100ms, 500ms). + const backoffCalls = delayMock.mock.calls.map((args) => args[0]).filter((ms) => ms >= 1000) + expect(backoffCalls).toEqual([1000, 2000, 4000]) + } finally { + await hub.dispose() + } + }) + + it("updates the panel when the status changes to connected and again when the lists arrive", async () => { + let resolveTools!: (value: { tools: Array<{ name: string }> }) => void + const streamableModule = await import("@modelcontextprotocol/sdk/client/streamableHttp.js") + vi.mocked(streamableModule.StreamableHTTPClientTransport).mockImplementation(function () { + return { close: vi.fn().mockResolvedValue(undefined) } as unknown as StreamableHTTPClientTransport + }) + const clientModule = await import("@modelcontextprotocol/sdk/client/index.js") + vi.mocked(clientModule.Client).mockImplementation(function () { + return { + connect: vi.fn().mockResolvedValue(undefined), + close: vi.fn().mockResolvedValue(undefined), + getInstructions: vi.fn(), + request: vi.fn((request: { method: string }) => { + if (request.method === "tools/list") { + return new Promise((resolve) => { + resolveTools = resolve + }) + } + return Promise.resolve({ resources: [], resourceTemplates: [] }) + }), + } as unknown as Client + }) + const authProvider = { + hasMetadata: true, + registerClientIfNeeded: vi.fn().mockResolvedValue(undefined), + close: vi.fn().mockResolvedValue(undefined), + } + vi.mocked(McpOAuthClientProvider.create).mockResolvedValue( + authProvider as unknown as McpOAuthClientProvider, + ) + const secretStorage = { + hasOAuthData: vi.fn().mockResolvedValue(false), + onDidChange: vi.fn().mockReturnValue(vi.fn()), + } + vi.mocked(fs.access).mockRejectedValue(new Error("no project config")) + vi.mocked(fs.readFile).mockResolvedValue( + JSON.stringify({ + mcpServers: { + [serverName]: { + type: "streamable-http", + url: serverUrl, + }, + }, + }), + ) + const hub = new McpHub(mockProvider as ClineProvider, secretStorage as unknown as SecretStorageService) + try { + const notifySpy = vi.spyOn( + hub as unknown as { notifyWebviewOfServerChanges: () => Promise }, + "notifyWebviewOfServerChanges", + ) + const ready = hub.waitUntilReady() + const conn = () => { + const found = hub.connections.find((c) => c.server.name === serverName) + return found?.type === "connected" ? found : undefined + } + + // The panel shows connected while the tools list is still pending. + await vi.waitFor(() => { + expect(conn()?.server.status).toBe("connected") + expect(notifySpy).toHaveBeenCalledTimes(1) + }) + expect(conn()?.server.tools).toBeUndefined() + + // When the lists arrive, the panel updates again with their results. + resolveTools!({ tools: [{ name: "slow-tool" }] }) + await ready + // The early connected update plus at least one post-list update. + await vi.waitFor(() => expect(notifySpy.mock.calls.length).toBeGreaterThanOrEqual(2)) + expect(conn()?.server.tools).toEqual([ + { name: "slow-tool", alwaysAllow: false, enabledForPrompt: true }, + ]) + } finally { + await hub.dispose() + } + }) }) }) diff --git a/src/services/mcp/__tests__/McpOAuthClientProvider.spec.ts b/src/services/mcp/__tests__/McpOAuthClientProvider.spec.ts index 185bf4c4617..6ff1de39ed5 100644 --- a/src/services/mcp/__tests__/McpOAuthClientProvider.spec.ts +++ b/src/services/mcp/__tests__/McpOAuthClientProvider.spec.ts @@ -35,8 +35,9 @@ vi.mock("@modelcontextprotocol/sdk/client/auth.js", () => ({ }), })) -// Set up fetch mock to return auth metadata with "none" auth method -mockFetch.mockResolvedValue({ +// Default auth metadata with "none" auth method. Shared with beforeEach so the +// default can be restored after queued one-time responses are reset. +const defaultAuthServerFetch = () => ({ ok: true, json: () => Promise.resolve({ @@ -49,6 +50,7 @@ mockFetch.mockResolvedValue({ grant_types_supported: ["authorization_code", "refresh_token"], }), }) +mockFetch.mockImplementation(defaultAuthServerFetch) import { McpOAuthClientProvider } from "../McpOAuthClientProvider" import { SecretStorageService, StoredMcpOAuthData } from "../SecretStorageService" @@ -166,6 +168,9 @@ describe("McpOAuthClientProvider", () => { // clearAllMocks() keeps queued one-time listeners. Reset them so a failed test cannot leak them. vi.mocked(startCallbackServer).mockReset() vi.mocked(stopCallbackServer).mockReset().mockResolvedValue(undefined) + // Same for queued one-time fetch responses. + mockFetch.mockReset() + mockFetch.mockImplementation(defaultAuthServerFetch) McpOAuthClientProvider.clearNonOAuthCache() }) @@ -334,12 +339,113 @@ describe("McpOAuthClientProvider", () => { const secretStorage = createMockSecretStorage() const provider = await McpOAuthClientProvider.create("https://example.com/mcp", secretStorage) // Port 0 is intentional: the server starts lazily in _ensureCallbackServer(). - // DCR and authorization flows always call _ensureCallbackServer() first to obtain - // a real port before using redirectUrl, so port 0 is never sent to an OAuth server. + // A cached client returns early from registerClientIfNeeded() without DCR, so + // port 0 IS what the SDK puts into the authorization URL at this point. The + // fix lives in redirectToAuthorization(), which starts the listener first and + // then overrides redirect_uri with the active port before the URL is stored. expect(provider.redirectUrl).toBe("http://127.0.0.1:0/callback") }) }) + describe("redirectToAuthorization redirect_uri", () => { + /** Builds an authorization URL exactly like the SDK does before the listener starts. */ + function sdkAuthorizationUrl(): URL { + return new URL( + "https://auth.example.com/authorize?client_id=abc&code_challenge=xyz&code_challenge_method=S256&redirect_uri=http%3A%2F%2F127.0.0.1%3A0%2Fcallback", + ) + } + + it("overrides redirect_uri with the active listener port for a fresh client", async () => { + mockOAuthDiscovery() + mockCallbackListeners(1) + const provider = await McpOAuthClientProvider.create("https://example.com/mcp", createMockSecretStorage()) + + const url = sdkAuthorizationUrl() + await provider.redirectToAuthorization(url) + + expect(url.searchParams.get("redirect_uri")).toBe("http://127.0.0.1:12345/callback") + // The SDK-generated parameters survive the override. + expect(url.searchParams.get("client_id")).toBe("abc") + expect(url.searchParams.get("code_challenge")).toBe("xyz") + await provider.close() + }) + + it("covers the cached-client path that returns early from registerClientIfNeeded", async () => { + mockOAuthDiscovery() + const secretStorage = createMockSecretStorage() + await secretStorage.saveOAuthData("https://example.com/mcp", { + tokens: { access_token: "stale", token_type: "Bearer" }, + expires_at: Date.now() + 60 * 60 * 1000, + issuer: "https://auth.example.com", + client_info: { + client_id: "cached-client", + redirect_uris: ["http://127.0.0.1:9999/callback"], + }, + }) + mockCallbackListeners(1) + const provider = await McpOAuthClientProvider.create("https://example.com/mcp", secretStorage) + + // The cached early-return path must also start the listener, so both the + // stored client info and the authorization URL carry the active port. + await provider.registerClientIfNeeded() + expect(await provider.clientInformation()).toMatchObject({ + redirect_uris: ["http://127.0.0.1:12345/callback"], + }) + + const url = sdkAuthorizationUrl() + await provider.redirectToAuthorization(url) + expect(url.searchParams.get("redirect_uri")).toBe("http://127.0.0.1:12345/callback") + await provider.close() + }) + + it("carries the replacement listener's port on a later 401", async () => { + mockOAuthDiscovery() + const listeners = mockCallbackListeners(2) + const provider = await McpOAuthClientProvider.create("https://example.com/mcp", createMockSecretStorage()) + + const firstUrl = sdkAuthorizationUrl() + await provider.redirectToAuthorization(firstUrl) + expect(firstUrl.searchParams.get("redirect_uri")).toBe("http://127.0.0.1:12345/callback") + + // The first listener dies (for example a callback timeout). A later 401 + // starts a replacement listener, and the new URL must carry ITS port. + listeners[0].result.reject(new Error("Callback timeout")) + await flushPromises() + + const secondUrl = sdkAuthorizationUrl() + await provider.redirectToAuthorization(secondUrl) + expect(secondUrl.searchParams.get("redirect_uri")).toBe("http://127.0.0.1:12346/callback") + await provider.close() + }) + + it("still sends a real port when a failed token refresh forces full re-auth", async () => { + mockOAuthDiscovery() + // The refresh exchange is rejected by the server. + mockFetch.mockResolvedValueOnce({ + ok: false, + status: 400, + text: () => Promise.resolve("invalid_grant"), + }) + const secretStorage = createMockSecretStorage() + await secretStorage.saveOAuthData("https://example.com/mcp", { + tokens: { access_token: "expired", refresh_token: "dead-refresh", token_type: "Bearer" }, + expires_at: Date.now() - 1000, + issuer: "https://auth.example.com", + }) + mockCallbackListeners(1) + const provider = await McpOAuthClientProvider.create("https://example.com/mcp", secretStorage) + + // The failed refresh clears the stale data; the next sign-in is a full flow. + expect(await provider.tokens()).toBeUndefined() + expect(secretStorage.deleteOAuthData).toHaveBeenCalled() + + const url = sdkAuthorizationUrl() + await provider.redirectToAuthorization(url) + expect(url.searchParams.get("redirect_uri")).toBe("http://127.0.0.1:12345/callback") + await provider.close() + }) + }) + describe("clientMetadata", () => { it("should return correct metadata with redirect URI", async () => { setupCallbackServerMock() diff --git a/src/services/mcp/__tests__/mcp-oauth-flow.property.spec.ts b/src/services/mcp/__tests__/mcp-oauth-flow.property.spec.ts new file mode 100644 index 00000000000..7b2cabddc1a --- /dev/null +++ b/src/services/mcp/__tests__/mcp-oauth-flow.property.spec.ts @@ -0,0 +1,557 @@ +import * as fs from "fs/promises" +import type { Server } from "http" + +import type { Mock } from "vitest" +import type { Uri } from "vscode" +import type { Client } from "@modelcontextprotocol/sdk/client/index.js" +import type { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js" + +import type { ClineProvider } from "../../../core/webview/ClineProvider" +import type { SecretStorageService, StoredMcpOAuthData } from "../SecretStorageService" +import type { CallbackResult } from "../utils/callbackServer" + +import { McpHub } from "../McpHub" +import { McpOAuthClientProvider } from "../McpOAuthClientProvider" + +// The module mock above stands in for the McpHub tests. The redirect property +// drives the real provider implementation, so it imports the actual module. +async function realProvider() { + const actual = await vi.importActual("../McpOAuthClientProvider") + return actual.McpOAuthClientProvider +} + +// --------------------------------------------------------------------------- +// Module doubles, mirroring the sibling spec files in this folder. +// --------------------------------------------------------------------------- + +vi.mock("fs/promises", () => { + const access = vi.fn().mockRejectedValue(new Error("no project config")) + const writeFile = vi.fn().mockResolvedValue(undefined) + const readFile = vi.fn().mockResolvedValue("{}") + const unlink = vi.fn().mockResolvedValue(undefined) + const rename = vi.fn().mockResolvedValue(undefined) + const lstat = vi.fn().mockImplementation(() => Promise.resolve({ isDirectory: () => true })) + const mkdir = vi.fn().mockResolvedValue(undefined) + const shared = { access, writeFile, readFile, unlink, rename, lstat, mkdir } + return { default: shared, ...shared } +}) + +vi.mock("../../../utils/safeWriteJson", () => ({ + safeWriteJson: vi.fn(async (filePath: string) => { + const fsModule = await import("fs/promises") + return fsModule.writeFile(filePath, "{}", "utf8") + }), +})) + +vi.mock("delay", () => ({ default: vi.fn().mockResolvedValue(undefined) })) + +vi.mock("vscode", () => ({ + workspace: { + createFileSystemWatcher: vi.fn().mockReturnValue({ + onDidChange: vi.fn(), + onDidCreate: vi.fn(), + onDidDelete: vi.fn(), + dispose: vi.fn(), + }), + onDidSaveTextDocument: vi.fn(), + onDidChangeWorkspaceFolders: vi.fn(), + workspaceFolders: [], + }, + window: { + showErrorMessage: vi.fn(), + showInformationMessage: vi.fn(), + showWarningMessage: vi.fn(), + withProgress: vi.fn().mockImplementation((_options: unknown, task: (p: unknown, t: unknown) => unknown) => { + const progress = { report: vi.fn() } + const token = { + isCancellationRequested: false, + onCancellationRequested: vi.fn(() => ({ dispose: vi.fn() })), + } + return task(progress, token) + }), + }, + env: { + openExternal: vi.fn().mockResolvedValue(true), + }, + Uri: { + parse: vi.fn((url: string) => ({ toString: () => url })), + }, + ProgressLocation: { + Notification: 15, + }, + Disposable: { + from: vi.fn(), + }, +})) + +vi.mock("../../../core/webview/ClineProvider") + +vi.mock("@modelcontextprotocol/sdk/client/stdio.js", () => ({ + StdioClientTransport: vi.fn(), + getDefaultEnvironment: vi.fn().mockReturnValue({ PATH: "/usr/bin" }), +})) + +vi.mock("@modelcontextprotocol/sdk/client/index.js", () => ({ + Client: vi.fn(), +})) + +vi.mock("@modelcontextprotocol/sdk/client/streamableHttp.js", () => ({ + StreamableHTTPClientTransport: vi.fn(), +})) + +vi.mock("../McpOAuthClientProvider", () => ({ + McpOAuthClientProvider: { + create: vi.fn(), + isKnownNonOAuth: vi.fn().mockReturnValue(false), + clearNonOAuthCache: vi.fn(), + }, +})) + +vi.mock("chokidar", () => ({ + default: { + watch: vi.fn().mockReturnValue({ + on: vi.fn().mockReturnThis(), + close: vi.fn(), + }), + }, +})) + +vi.mock("../utils/callbackServer", () => ({ + startCallbackServer: vi.fn(), + stopCallbackServer: vi.fn().mockResolvedValue(undefined), +})) + +import * as vscode from "vscode" +import { startCallbackServer, stopCallbackServer } from "../utils/callbackServer" +import { TOKEN_EXPIRY_BUFFER_MS } from "../constants" + +// --------------------------------------------------------------------------- +// Deterministic pseudo-random histories (mulberry32), seeded per property. +// --------------------------------------------------------------------------- + +function makeRandom(seed: number): () => number { + let state = seed >>> 0 + return () => { + state = (state + 0x6d2b79f5) >>> 0 + let t = state + t = Math.imul(t ^ (t >>> 15), t | 1) + t ^= t + Math.imul(t ^ (t >>> 7), t | 61) + return ((t ^ (t >>> 14)) >>> 0) / 4294967296 + } +} + +function pick(random: () => number, items: readonly T[]): T { + return items[Math.floor(random() * items.length)] +} + +async function flushPromises(): Promise { + await new Promise((resolve) => setTimeout(resolve, 0)) +} + +// --------------------------------------------------------------------------- +// Provider doubles. +// --------------------------------------------------------------------------- + +function createMockSecretStorage(): SecretStorageService { + const store = new Map() + const key = (url: string, clientId?: string) => `${url}:${clientId ?? "dynamic"}` + return { + getOAuthData: vi.fn(async (url: string, clientId?: string) => { + const raw = store.get(key(url, clientId)) + return raw ? (JSON.parse(raw) as StoredMcpOAuthData) : undefined + }), + saveOAuthData: vi.fn(async (url: string, data: StoredMcpOAuthData, clientId?: string) => { + store.set(key(url, clientId), JSON.stringify(data)) + }), + deleteOAuthData: vi.fn(async (url: string, clientId?: string) => { + store.delete(key(url, clientId)) + }), + hasOAuthData: vi.fn(async (url: string, clientId?: string) => store.has(key(url, clientId))), + onDidChange: vi.fn(() => vi.fn()), + } as unknown as SecretStorageService +} + +/** Queues one callback listener whose port is 30000 + index. */ +function queueListener(index: number): void { + const server = { close: vi.fn((cb: () => void) => cb()) } + const result = new Promise(() => {}) + vi.mocked(startCallbackServer).mockResolvedValueOnce({ + server: server as unknown as Server, + port: 30000 + index, + result, + cancel: vi.fn(), + }) +} + +const mockFetch = vi.fn() +const originalFetch = global.fetch +global.fetch = mockFetch + +vi.mock("@modelcontextprotocol/sdk/client/auth.js", () => ({ + discoverOAuthProtectedResourceMetadata: vi.fn().mockResolvedValue({ + resource: "", + authorization_servers: ["https://auth.example.com"], + }), +})) + +function queueDiscoveryFetch(): void { + mockFetch.mockResolvedValueOnce({ + ok: true, + json: () => + Promise.resolve({ + issuer: "https://auth.example.com", + authorization_endpoint: "https://auth.example.com/authorize", + token_endpoint: "https://auth.example.com/token", + token_endpoint_auth_methods_supported: ["none"], + grant_types_supported: ["authorization_code", "refresh_token"], + }), + }) +} + +// --------------------------------------------------------------------------- +// Hub doubles for the flow and status properties. +// --------------------------------------------------------------------------- + +const mockProvider = { + ensureSettingsDirectoryExists: vi.fn().mockResolvedValue("/mock/settings/path"), + postMessageToWebview: vi.fn(), + getState: vi.fn().mockResolvedValue({ mcpEnabled: true }), + context: { + extension: { packageJSON: { version: "1.0.0" } }, + }, +} as unknown as ClineProvider + +function createTestSecretStorage(oauthData: unknown): SecretStorageService { + return { + hasOAuthData: vi.fn().mockResolvedValue(oauthData !== undefined), + getOAuthData: vi.fn().mockResolvedValue(oauthData), + deleteOAuthData: vi.fn().mockResolvedValue(undefined), + onDidChange: vi.fn(() => vi.fn()), + } as unknown as SecretStorageService +} + +const serverName = "property-server" +const serverUrl = "https://property.example.com/mcp" +const oauthConfig = { type: "streamable-http", url: serverUrl } + +type TestConnection = { + type: "connected" + server: { name: string; config: string; status: string; source?: string } + client: { request: Mock; close: Mock } + transport: { close: Mock } + authProvider?: unknown +} + +type FlowHandle = { + connection: TestConnection + authProvider: { close: Mock } + cancellationToken?: { onCancellationRequested: Mock } + promise: Promise + resolved: boolean +} + +type FlowHub = { + waitUntilReady: () => Promise + _runOAuthFlow: ( + name: string, + source: "global" | "project", + config: unknown, + serverUrl: string, + authProvider: unknown, + transport: unknown, + connection: unknown, + progress: unknown, + cancellationToken: unknown, + oauthClientId?: string, + ) => Promise + deleteConnection: (name: string, source?: string) => Promise + notifyWebviewOfServerChanges: Mock + findConnection: Mock + validateServerConfig: Mock + appendErrorMessage: Mock + _oauthWatchers: Map + connections: TestConnection[] + secretStorage: SecretStorageService + dispose: () => Promise +} + +async function createFlowHub(): Promise { + const hub = new McpHub(mockProvider) as unknown as FlowHub + // Settle the background initialization first: its updateServerConnections pass + // would otherwise delete test connections that are absent from the settings file. + await hub.waitUntilReady() + hub.connections = [] + hub.secretStorage = createTestSecretStorage(undefined) + hub.notifyWebviewOfServerChanges = vi.fn().mockResolvedValue(undefined) + hub.findConnection = vi.fn(() => hub.connections[0]) + hub.validateServerConfig = vi.fn().mockReturnValue(oauthConfig) + hub.appendErrorMessage = vi.fn().mockImplementation((connection: TestConnection, message: string) => { + connection.server.status = "disconnected" + void message + }) + return hub +} + +/** Starts one real _runOAuthFlow with a toast that never resolves. */ +function startFlow(hub: FlowHub): FlowHandle { + const connection: TestConnection = { + type: "connected", + server: { name: serverName, config: JSON.stringify(oauthConfig), status: "connecting", source: "global" }, + client: { request: vi.fn(), close: vi.fn().mockResolvedValue(undefined) }, + transport: { close: vi.fn().mockResolvedValue(undefined) }, + } + const authProvider = { close: vi.fn().mockResolvedValue(undefined) } + hub.connections = [connection] + const cancellationToken = { + isCancellationRequested: false, + onCancellationRequested: vi.fn(() => ({ dispose: vi.fn() })), + } + const flowPromise = hub._runOAuthFlow( + serverName, + "global", + oauthConfig, + serverUrl, + authProvider, + {}, + connection, + { report: vi.fn() }, + cancellationToken, + undefined, + ) + const handle: FlowHandle = { + connection, + authProvider, + cancellationToken, + promise: flowPromise, + resolved: false, + } + void flowPromise.then(() => { + handle.resolved = true + }) + return handle +} + +// --------------------------------------------------------------------------- +// The properties, one per invariant sentence in the TLA+ specs. +// --------------------------------------------------------------------------- + +describe("MCP OAuth flow property tests", () => { + beforeEach(() => { + vi.clearAllMocks() + mockFetch.mockReset() + vi.mocked(startCallbackServer).mockReset() + vi.mocked(stopCallbackServer).mockReset().mockResolvedValue(undefined) + McpOAuthClientProvider.clearNonOAuthCache() + }) + + // Invariant: McpOAuthRedirectUrl.NoBadOpen. + it("redirect property: every opened URL carries the active listener port and never port 0", async () => { + const random = makeRandom(20261127) + const histories = 24 + + for (let history = 0; history < histories; history++) { + // The client registration may be cached, which skips DCR entirely. + const cached = random() < 0.5 + const secretStorage = createMockSecretStorage() + queueDiscoveryFetch() + if (cached) { + await secretStorage.saveOAuthData("https://example.com/mcp", { + tokens: { access_token: "seed", token_type: "Bearer" }, + expires_at: Date.now() + TOKEN_EXPIRY_BUFFER_MS + 60 * 1000, + issuer: "https://auth.example.com", + client_info: { client_id: "cached-client", redirect_uris: [] }, + } as StoredMcpOAuthData) + } + queueListener(0) + const RealProvider = await realProvider() + const provider = await RealProvider.create("https://example.com/mcp", secretStorage) + + // A later 401 round re-auths through a replacement listener. + const rounds = 1 + Math.floor(random() * 2) + for (let round = 0; round < rounds; round++) { + if (round > 0) { + await provider.close() + queueListener(round) + } + const url = new URL( + "https://auth.example.com/authorize?client_id=abc&redirect_uri=http%3A%2F%2F127.0.0.1%3A0%2Fcallback", + ) + await provider.redirectToAuthorization(url) + const redirectUri = url.searchParams.get("redirect_uri") ?? "" + const redirectPort = Number(new URL(redirectUri).port) + expect(redirectPort).toBe(30000 + round) + expect(redirectPort).not.toBe(0) + + // The opened URL is the stored one. + await provider.openBrowser() + const openedUri = vi.mocked(vscode.env.openExternal).mock.calls.at(-1)?.[0] as Uri + expect(new URL(String(openedUri)).searchParams.get("redirect_uri")).toBe( + `http://127.0.0.1:${30000 + round}/callback`, + ) + } + await provider.close() + } + }) + + // Invariants: McpOAuthFlowEnd.NoDuplicateFlow, NoOrphanFlow, ToolNotOrphaned. + it("flow-end property: a removed watcher always ends its flow, and tool waits are released", async () => { + const random = makeRandom(486) + const histories = 16 + const actions = ["start", "replace", "delete", "tool", "dispose"] as const + + for (let history = 0; history < histories; history++) { + const hub = await createFlowHub() + const flows: FlowHandle[] = [] + let toolWaiting = false + + const steps = 3 + Math.floor(random() * 4) + for (let step = 0; step < steps; step++) { + const action = pick(random, actions) + if (action === "start" || action === "replace" || action === "tool") { + if (action === "tool") { + toolWaiting = true + } + // Starting a flow replaces any existing watcher through the shared path. + flows.push(startFlow(hub)) + } else if (action === "delete") { + await hub.deleteConnection(serverName, "global") + } else { + // Dispose ends every flow; the history stops here. + await hub.dispose() + await flushPromises() + break + } + await flushPromises() + + // NoDuplicateFlow: at most one unresolved flow. + const unresolved = flows.filter((flow) => !flow.resolved) + expect(unresolved.length).toBeLessThanOrEqual(1) + // NoOrphanFlow: a pending flow still owns the watcher. + expect(unresolved.length === 1).toBe(hub._oauthWatchers.size === 1) + // ToolNotOrphaned: a tool wait is live on a flow or was released by its end. + if (toolWaiting) { + expect(hub._oauthWatchers.size === 1 || unresolved.length === 0).toBe(true) + } + } + + // Every flow promise settles once the hub goes away. + await hub.dispose() + await flushPromises() + for (const flow of flows) { + await flow.promise + expect(flow.resolved).toBe(true) + } + } + }) + + // Invariant: McpOAuthFlowEnd.NoErrorLeak. + it("error-leak property: a reconnect error in the token watcher ends the flow", async () => { + const random = makeRandom(987654321) + const histories = 8 + + for (let history = 0; history < histories; history++) { + const hub = await createFlowHub() + const flow = startFlow(hub) + await flushPromises() + expect(hub._oauthWatchers.size).toBe(1) + + // The token watcher fires and the reconnect it triggers throws. + const secretStorage = hub.secretStorage + ;(secretStorage.getOAuthData as Mock).mockResolvedValue({ + expires_at: Date.now() + 10 * 60 * 1000, + }) + const watcherCallbacks = (secretStorage.onDidChange as Mock).mock.calls.map((call) => call[1] as () => void) + expect(watcherCallbacks.length).toBe(1) + watcherCallbacks[0]() + await flushPromises() + await flushPromises() + void random + + expect(flow.resolved).toBe(true) + expect(hub._oauthWatchers.size).toBe(0) + await hub.dispose() + } + }) + + // Invariant: McpOAuthStatusHandoff.PanelShowsConnected. + it("status-handoff property: the panel shows connected before slow lists finish, then updates again", async () => { + const random = makeRandom(13579) + const histories = 10 + + const streamableModule = await import("@modelcontextprotocol/sdk/client/streamableHttp.js") + const clientModule = await import("@modelcontextprotocol/sdk/client/index.js") + + for (let history = 0; history < histories; history++) { + // The lists finish in a random order, possibly after other work. + const toolsDeferred = deferred() + const resourcesDeferred = deferred() + vi.mocked(streamableModule.StreamableHTTPClientTransport).mockImplementation(function () { + return { close: vi.fn().mockResolvedValue(undefined) } as unknown as StreamableHTTPClientTransport + }) + vi.mocked(clientModule.Client).mockImplementation(function () { + return { + connect: vi.fn().mockResolvedValue(undefined), + close: vi.fn().mockResolvedValue(undefined), + getInstructions: vi.fn(), + request: vi.fn((request: { method: string }) => { + if (request.method === "tools/list") return toolsDeferred.promise + return resourcesDeferred.promise + }), + } as unknown as Client + }) + const authProvider = { + hasMetadata: true, + registerClientIfNeeded: vi.fn().mockResolvedValue(undefined), + close: vi.fn().mockResolvedValue(undefined), + } + vi.mocked(McpOAuthClientProvider.create).mockResolvedValue( + authProvider as unknown as McpOAuthClientProvider, + ) + + vi.mocked(fs.readFile).mockResolvedValue(JSON.stringify({ mcpServers: { [serverName]: oauthConfig } })) + const hub = new McpHub(mockProvider, createTestSecretStorage(undefined)) + const hubDouble = hub as unknown as { + notifyWebviewOfServerChanges: Mock + connections: Array<{ server: { name: string; status: string; tools?: unknown } }> + dispose: () => Promise + } + const notifySpy = vi.spyOn(hubDouble, "notifyWebviewOfServerChanges").mockResolvedValue(undefined) + + try { + const ready = hub.waitUntilReady() + const conn = () => hubDouble.connections.find((c) => c.server.name === serverName) + + // PanelShowsConnected: connected at the status change, before any list. + await vi.waitFor(() => { + expect(conn()?.server.status).toBe("connected") + expect(notifySpy).toHaveBeenCalledTimes(1) + }) + expect(conn()?.server.tools).toBeUndefined() + + // The lists finish in a random order and the panel updates again. + const order = random() < 0.5 ? [toolsDeferred, resourcesDeferred] : [resourcesDeferred, toolsDeferred] + for (const entry of order) { + entry.resolve() + await flushPromises() + } + await ready + await vi.waitFor(() => expect(notifySpy.mock.calls.length).toBeGreaterThanOrEqual(2)) + expect(conn()?.server.tools).toEqual([]) + } finally { + await hubDouble.dispose() + } + } + }) +}) + +function deferred(): { promise: Promise>; resolve: () => void } { + let resolve!: () => void + const promise = new Promise>((res) => { + resolve = res as () => void + }) + return { promise, resolve } +} + +afterAll(async () => { + global.fetch = originalFetch +}) diff --git a/src/services/mcp/constants.ts b/src/services/mcp/constants.ts index 8107ee4a293..e662a8bc1d5 100644 --- a/src/services/mcp/constants.ts +++ b/src/services/mcp/constants.ts @@ -1,2 +1,8 @@ export const TOKEN_EXPIRY_BUFFER_MS = 5 * 60 * 1000 // 5 minutes export const OAUTH_FLOW_TIMEOUT_MS = 5 * 60 * 1000 // 5 minutes +// Bounds for automatic reconnects that reuse a saved token the server rejected. +// Each retry delays before reconnecting; at the limit the flow ends with a +// visible error instead of retrying the same rejected token again. +export const OAUTH_TOKEN_RETRY_MAX_ATTEMPTS = 3 +export const OAUTH_TOKEN_RETRY_BASE_DELAY_MS = 1000 +export const OAUTH_TOKEN_RETRY_MAX_DELAY_MS = 10_000 From e4817fe19f49536a318685c168c813b7893721f0 Mon Sep 17 00:00:00 2001 From: Elliott de Launay Date: Sat, 28 Nov 2026 04:55:44 +0000 Subject: [PATCH 2/3] fix: preserve MCP OAuth recovery and simplify flow cleanup --- ...pConnectionOwnership.DeleteReplacement.cfg | 9 + .../tla/McpConnectionOwnership.LateDetach.cfg | 9 + .../tla/McpConnectionOwnership.LateSetup.cfg | 9 + ...McpConnectionOwnership.LostRecoveryRow.cfg | 9 + .../tla/McpConnectionOwnership.cfg | 9 + .../tla/McpConnectionOwnership.tla | 79 ++ .../tla/McpOAuthFlowEnd.BrowserTimer.cfg | 14 + .../tla/McpOAuthFlowEnd.DeleteLeak.cfg | 8 +- .../tla/McpOAuthFlowEnd.DisposeLeak.cfg | 8 +- .../tla/McpOAuthFlowEnd.DoubleClaim.cfg | 14 + .../tla/McpOAuthFlowEnd.ErrorLeak.cfg | 8 +- .../tla/McpOAuthFlowEnd.FinishTimer.cfg | 14 + .../tla/McpOAuthFlowEnd.IgnoreOutcome.cfg | 14 + .../tla/McpOAuthFlowEnd.ReconnectTimer.cfg | 14 + .../tla/McpOAuthFlowEnd.ReplaceLeak.cfg | 8 +- .../tla/McpOAuthFlowEnd.StaleContinuation.cfg | 14 + docs/architecture/tla/McpOAuthFlowEnd.cfg | 8 +- docs/architecture/tla/McpOAuthFlowEnd.tla | 158 +++- .../McpOAuthRedirectUrl.LostCachedClient.cfg | 7 + .../tla/McpOAuthRedirectUrl.NoEnsure.cfg | 4 +- .../tla/McpOAuthRedirectUrl.NoOverride.cfg | 4 +- docs/architecture/tla/McpOAuthRedirectUrl.cfg | 4 +- docs/architecture/tla/McpOAuthRedirectUrl.tla | 38 +- .../tla/McpOAuthRetry.DiscoveryLoop.cfg | 5 + .../tla/McpOAuthRetry.ResetOnInitialize.cfg | 5 + docs/architecture/tla/McpOAuthRetry.cfg | 5 + docs/architecture/tla/McpOAuthRetry.tla | 44 + ...cpOAuthStatusHandoff.GenericDuringAuth.cfg | 7 + .../McpOAuthStatusHandoff.NoEarlyNotify.cfg | 4 +- .../McpOAuthStatusHandoff.StaleTransport.cfg | 7 + .../tla/McpOAuthStatusHandoff.cfg | 4 +- .../tla/McpOAuthStatusHandoff.tla | 45 +- src/eslint-suppressions.json | 2 +- src/services/mcp/McpHub.ts | 867 ++++++++---------- src/services/mcp/McpOAuthClientProvider.ts | 9 +- src/services/mcp/McpOAuthFlow.ts | 83 ++ src/services/mcp/__tests__/McpHub.spec.ts | 369 ++++++-- .../__tests__/McpOAuthClientProvider.spec.ts | 16 + .../mcp/__tests__/McpOAuthFlow.spec.ts | 107 +++ .../__tests__/mcp-oauth-flow.property.spec.ts | 333 ++++++- .../mcp-oauth-ownership.integration.spec.ts | 272 ++++++ 41 files changed, 1984 insertions(+), 663 deletions(-) create mode 100644 docs/architecture/tla/McpConnectionOwnership.DeleteReplacement.cfg create mode 100644 docs/architecture/tla/McpConnectionOwnership.LateDetach.cfg create mode 100644 docs/architecture/tla/McpConnectionOwnership.LateSetup.cfg create mode 100644 docs/architecture/tla/McpConnectionOwnership.LostRecoveryRow.cfg create mode 100644 docs/architecture/tla/McpConnectionOwnership.cfg create mode 100644 docs/architecture/tla/McpConnectionOwnership.tla create mode 100644 docs/architecture/tla/McpOAuthFlowEnd.BrowserTimer.cfg create mode 100644 docs/architecture/tla/McpOAuthFlowEnd.DoubleClaim.cfg create mode 100644 docs/architecture/tla/McpOAuthFlowEnd.FinishTimer.cfg create mode 100644 docs/architecture/tla/McpOAuthFlowEnd.IgnoreOutcome.cfg create mode 100644 docs/architecture/tla/McpOAuthFlowEnd.ReconnectTimer.cfg create mode 100644 docs/architecture/tla/McpOAuthFlowEnd.StaleContinuation.cfg create mode 100644 docs/architecture/tla/McpOAuthRedirectUrl.LostCachedClient.cfg create mode 100644 docs/architecture/tla/McpOAuthRetry.DiscoveryLoop.cfg create mode 100644 docs/architecture/tla/McpOAuthRetry.ResetOnInitialize.cfg create mode 100644 docs/architecture/tla/McpOAuthRetry.cfg create mode 100644 docs/architecture/tla/McpOAuthRetry.tla create mode 100644 docs/architecture/tla/McpOAuthStatusHandoff.GenericDuringAuth.cfg create mode 100644 docs/architecture/tla/McpOAuthStatusHandoff.StaleTransport.cfg create mode 100644 src/services/mcp/McpOAuthFlow.ts create mode 100644 src/services/mcp/__tests__/McpOAuthFlow.spec.ts create mode 100644 src/services/mcp/__tests__/mcp-oauth-ownership.integration.spec.ts diff --git a/docs/architecture/tla/McpConnectionOwnership.DeleteReplacement.cfg b/docs/architecture/tla/McpConnectionOwnership.DeleteReplacement.cfg new file mode 100644 index 00000000000..8a0e8ac8701 --- /dev/null +++ b/docs/architecture/tla/McpConnectionOwnership.DeleteReplacement.cfg @@ -0,0 +1,9 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + KeepStoppedRow = TRUE + GuardSetup = TRUE + DetachBeforeClose = TRUE + CheckClosing = FALSE + PreserveReplacement = FALSE +INVARIANTS TypeOK NoStaleAccess ReplacementRetained NoLateSetup RecoveryVisible diff --git a/docs/architecture/tla/McpConnectionOwnership.LateDetach.cfg b/docs/architecture/tla/McpConnectionOwnership.LateDetach.cfg new file mode 100644 index 00000000000..12ffc49a02a --- /dev/null +++ b/docs/architecture/tla/McpConnectionOwnership.LateDetach.cfg @@ -0,0 +1,9 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + KeepStoppedRow = TRUE + GuardSetup = TRUE + DetachBeforeClose = FALSE + CheckClosing = FALSE + PreserveReplacement = TRUE +INVARIANTS TypeOK NoStaleAccess ReplacementRetained NoLateSetup RecoveryVisible diff --git a/docs/architecture/tla/McpConnectionOwnership.LateSetup.cfg b/docs/architecture/tla/McpConnectionOwnership.LateSetup.cfg new file mode 100644 index 00000000000..818a2f0fe10 --- /dev/null +++ b/docs/architecture/tla/McpConnectionOwnership.LateSetup.cfg @@ -0,0 +1,9 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + KeepStoppedRow = TRUE + GuardSetup = FALSE + DetachBeforeClose = TRUE + CheckClosing = FALSE + PreserveReplacement = TRUE +INVARIANTS TypeOK NoStaleAccess ReplacementRetained NoLateSetup RecoveryVisible diff --git a/docs/architecture/tla/McpConnectionOwnership.LostRecoveryRow.cfg b/docs/architecture/tla/McpConnectionOwnership.LostRecoveryRow.cfg new file mode 100644 index 00000000000..a295965c45c --- /dev/null +++ b/docs/architecture/tla/McpConnectionOwnership.LostRecoveryRow.cfg @@ -0,0 +1,9 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + KeepStoppedRow = FALSE + GuardSetup = TRUE + DetachBeforeClose = TRUE + CheckClosing = FALSE + PreserveReplacement = TRUE +INVARIANTS TypeOK NoStaleAccess ReplacementRetained NoLateSetup RecoveryVisible diff --git a/docs/architecture/tla/McpConnectionOwnership.cfg b/docs/architecture/tla/McpConnectionOwnership.cfg new file mode 100644 index 00000000000..b3c822dac12 --- /dev/null +++ b/docs/architecture/tla/McpConnectionOwnership.cfg @@ -0,0 +1,9 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + KeepStoppedRow = TRUE + GuardSetup = TRUE + DetachBeforeClose = TRUE + CheckClosing = FALSE + PreserveReplacement = TRUE +INVARIANTS TypeOK NoStaleAccess ReplacementRetained NoLateSetup RecoveryVisible diff --git a/docs/architecture/tla/McpConnectionOwnership.tla b/docs/architecture/tla/McpConnectionOwnership.tla new file mode 100644 index 00000000000..f1ee6ea188f --- /dev/null +++ b/docs/architecture/tla/McpConnectionOwnership.tla @@ -0,0 +1,79 @@ +---- MODULE McpConnectionOwnership ---- +EXTENDS Naturals +\* Source: McpHub.deleteConnection removes a connection and awaits SDK cleanup. +\* Sink: isCurrentOAuthConnection gates continuations; cleanup must preserve a replacement. +\* Failure: removing the closing set permits access while the old connection remains registered. +\* Failure: cleanup by server name removes a replacement published during the await. +\* Invariants: NoStaleAccess, ReplacementRetained, and NoLateSetup. +\* Expect: synchronous removal replaces the closing-set guard. No new defect is expected. +\* Cost: one agent; a two-connection model, property tests, and a runtime refactor. +\* Result: fixed holds in 28 states. LateDetach fails at 5, DeleteReplacement at 11, LateSetup at 9. +\* Finding: the refactor needs cancellation to invalidate its reconnect setup permit. +\* Replay: the held HTTP initialize case passes after cancelling the owned setup. +\* Runtime sabotage: late registry removal fails two tests; missing setup cancellation fails one. +\* Review ratchet: PR #2762, follow-up D in the supplied review. Added 1, covered 0, gap 0. +\* Expect: StopReconnect without KeepStoppedRow violates RecoveryVisible. +\* Cost: one agent; row visibility model and real HTTP regression cases. +\* Follow-up result: LostRecoveryRow fails at 10 states. Cancel and timeout fail before the fix. +\* Replay: both error rows are posted to the panel and can restart against a real HTTP server. +\* Runtime sabotage: removing recovery fails the cancel and timeout cases. A later delete still wins. +\* Gap: the model does not describe SDK resource cleanup or browser behavior. +\* Simplification: McpHub.stopOAuthReconnect performs StopReconnect as one synchronous operation. +\* Source: an abort callback supplies the owner, revision, validated config, and reason. +\* Sink: cleanup starts, and a cancel or timeout retains the error row before any await. +\* Expect: existing RecoveryVisible and ReplacementRetained still hold. No new defect is expected. +\* Cost: one agent; function extraction with no extra model state or dependencies. +\* Simplification result: fixed holds in 28 states and all four failure variants still fail. +\* Null result: all 17 HTTP cases pass after extraction. No new runtime defect was found. +\* Runtime sabotage: removing the extracted recovery step fails cancel and timeout cases. +CONSTANTS DetachBeforeClose, CheckClosing, PreserveReplacement, GuardSetup, KeepStoppedRow +\* registered = 3 is a disconnected row with an error and an enabled retry action. +VARIABLES registered, closing, staleAccess, replacementLost, permit, setup, latePublish, recoveryRequired +vars == <> +Init == + /\ registered = 1 /\ closing = 0 + /\ staleAccess = FALSE /\ replacementLost = FALSE + /\ permit = TRUE /\ setup = TRUE /\ latePublish = FALSE /\ recoveryRequired = FALSE +BeginClose == + /\ closing = 0 /\ registered = 1 + /\ closing' = 1 + /\ registered' = IF DetachBeforeClose THEN 0 ELSE registered + /\ UNCHANGED <> +ContinueOld == + /\ staleAccess' = (staleAccess \/ (registered = 1 /\ closing = 1 /\ ~CheckClosing)) + /\ UNCHANGED <> +PublishReplacement == + /\ closing = 1 /\ registered # 2 + /\ registered' = 2 /\ recoveryRequired' = FALSE + /\ UNCHANGED <> +CompleteClose == + /\ closing = 1 + /\ registered' = IF PreserveReplacement /\ registered \in {2, 3} THEN registered ELSE 0 + /\ closing' = 2 + /\ replacementLost' = (replacementLost \/ (registered \in {2, 3} /\ ~PreserveReplacement)) + /\ UNCHANGED <> +CancelSetup == + /\ permit' = FALSE + /\ UNCHANGED <> +PublishSetup == + /\ setup + /\ setup' = FALSE + /\ latePublish' = (~permit /\ ~GuardSetup) + /\ UNCHANGED <> +\* Cancel or a callback timeout stops reconnect, but retains an error row. +StopReconnect == + /\ registered = 2 + /\ registered' = IF KeepStoppedRow THEN 3 ELSE 0 + /\ recoveryRequired' = TRUE + /\ UNCHANGED <> +NoLateSetup == ~latePublish +RecoveryVisible == recoveryRequired => registered = 3 +Next == StopReconnect \/ BeginClose \/ ContinueOld \/ PublishReplacement \/ CompleteClose \/ CancelSetup \/ PublishSetup +Spec == Init /\ [][Next]_vars +TypeOK == /\ registered \in 0..3 /\ closing \in 0..2 + /\ staleAccess \in BOOLEAN /\ replacementLost \in BOOLEAN + /\ permit \in BOOLEAN /\ setup \in BOOLEAN /\ latePublish \in BOOLEAN + /\ recoveryRequired \in BOOLEAN +NoStaleAccess == ~staleAccess +ReplacementRetained == ~replacementLost +==== diff --git a/docs/architecture/tla/McpOAuthFlowEnd.BrowserTimer.cfg b/docs/architecture/tla/McpOAuthFlowEnd.BrowserTimer.cfg new file mode 100644 index 00000000000..0ba3c3f1e3e --- /dev/null +++ b/docs/architecture/tla/McpOAuthFlowEnd.BrowserTimer.cfg @@ -0,0 +1,14 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + StopOnFinish = TRUE + StopOnClaim = FALSE + StopOnReconnect = TRUE + CheckOutcome = TRUE + ClaimOnce = TRUE + GuardContinuation = TRUE + ReplaceEndsFlow = TRUE + DeleteEndsFlow = TRUE + DisposeEndsFlows = TRUE + ErrorEndsFlow = TRUE +INVARIANTS TypeOK NoDuplicateFlow NoOrphanFlow ToolNotOrphaned NoErrorLeak NoStaleWrite OneContinuation ToolRequiresSuccess TimerOnlyWhileWaiting diff --git a/docs/architecture/tla/McpOAuthFlowEnd.DeleteLeak.cfg b/docs/architecture/tla/McpOAuthFlowEnd.DeleteLeak.cfg index f914252a936..4828a6e4572 100644 --- a/docs/architecture/tla/McpOAuthFlowEnd.DeleteLeak.cfg +++ b/docs/architecture/tla/McpOAuthFlowEnd.DeleteLeak.cfg @@ -2,8 +2,14 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANTS + StopOnFinish = TRUE + StopOnClaim = TRUE + StopOnReconnect = TRUE + CheckOutcome = TRUE + ClaimOnce = TRUE + GuardContinuation = TRUE ReplaceEndsFlow = TRUE DeleteEndsFlow = FALSE DisposeEndsFlows = TRUE ErrorEndsFlow = TRUE -INVARIANTS TypeOK NoDuplicateFlow NoOrphanFlow ToolNotOrphaned NoErrorLeak +INVARIANTS TypeOK NoDuplicateFlow NoOrphanFlow ToolNotOrphaned NoErrorLeak NoStaleWrite OneContinuation ToolRequiresSuccess TimerOnlyWhileWaiting diff --git a/docs/architecture/tla/McpOAuthFlowEnd.DisposeLeak.cfg b/docs/architecture/tla/McpOAuthFlowEnd.DisposeLeak.cfg index 3904bbf5ff8..900f0fa98a3 100644 --- a/docs/architecture/tla/McpOAuthFlowEnd.DisposeLeak.cfg +++ b/docs/architecture/tla/McpOAuthFlowEnd.DisposeLeak.cfg @@ -2,8 +2,14 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANTS + StopOnFinish = TRUE + StopOnClaim = TRUE + StopOnReconnect = TRUE + CheckOutcome = TRUE + ClaimOnce = TRUE + GuardContinuation = TRUE ReplaceEndsFlow = TRUE DeleteEndsFlow = TRUE DisposeEndsFlows = FALSE ErrorEndsFlow = TRUE -INVARIANTS TypeOK NoDuplicateFlow NoOrphanFlow ToolNotOrphaned NoErrorLeak +INVARIANTS TypeOK NoDuplicateFlow NoOrphanFlow ToolNotOrphaned NoErrorLeak NoStaleWrite OneContinuation ToolRequiresSuccess TimerOnlyWhileWaiting diff --git a/docs/architecture/tla/McpOAuthFlowEnd.DoubleClaim.cfg b/docs/architecture/tla/McpOAuthFlowEnd.DoubleClaim.cfg new file mode 100644 index 00000000000..a490c2526a8 --- /dev/null +++ b/docs/architecture/tla/McpOAuthFlowEnd.DoubleClaim.cfg @@ -0,0 +1,14 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + StopOnFinish = TRUE + StopOnClaim = TRUE + StopOnReconnect = TRUE + CheckOutcome = TRUE + ClaimOnce = FALSE + GuardContinuation = TRUE + ReplaceEndsFlow = TRUE + DeleteEndsFlow = TRUE + DisposeEndsFlows = TRUE + ErrorEndsFlow = TRUE +INVARIANTS TypeOK NoDuplicateFlow NoOrphanFlow ToolNotOrphaned NoErrorLeak NoStaleWrite OneContinuation ToolRequiresSuccess TimerOnlyWhileWaiting diff --git a/docs/architecture/tla/McpOAuthFlowEnd.ErrorLeak.cfg b/docs/architecture/tla/McpOAuthFlowEnd.ErrorLeak.cfg index ce12c83f988..2557d67d0f3 100644 --- a/docs/architecture/tla/McpOAuthFlowEnd.ErrorLeak.cfg +++ b/docs/architecture/tla/McpOAuthFlowEnd.ErrorLeak.cfg @@ -2,8 +2,14 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANTS + StopOnFinish = TRUE + StopOnClaim = TRUE + StopOnReconnect = TRUE + CheckOutcome = TRUE + ClaimOnce = TRUE + GuardContinuation = TRUE ReplaceEndsFlow = TRUE DeleteEndsFlow = TRUE DisposeEndsFlows = TRUE ErrorEndsFlow = FALSE -INVARIANTS TypeOK NoDuplicateFlow NoOrphanFlow ToolNotOrphaned NoErrorLeak +INVARIANTS TypeOK NoDuplicateFlow NoOrphanFlow ToolNotOrphaned NoErrorLeak NoStaleWrite OneContinuation ToolRequiresSuccess TimerOnlyWhileWaiting diff --git a/docs/architecture/tla/McpOAuthFlowEnd.FinishTimer.cfg b/docs/architecture/tla/McpOAuthFlowEnd.FinishTimer.cfg new file mode 100644 index 00000000000..556ee674edc --- /dev/null +++ b/docs/architecture/tla/McpOAuthFlowEnd.FinishTimer.cfg @@ -0,0 +1,14 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + StopOnFinish = FALSE + StopOnClaim = TRUE + StopOnReconnect = TRUE + CheckOutcome = TRUE + ClaimOnce = TRUE + GuardContinuation = TRUE + ReplaceEndsFlow = TRUE + DeleteEndsFlow = TRUE + DisposeEndsFlows = TRUE + ErrorEndsFlow = TRUE +INVARIANTS TypeOK NoDuplicateFlow NoOrphanFlow ToolNotOrphaned NoErrorLeak NoStaleWrite OneContinuation ToolRequiresSuccess TimerOnlyWhileWaiting diff --git a/docs/architecture/tla/McpOAuthFlowEnd.IgnoreOutcome.cfg b/docs/architecture/tla/McpOAuthFlowEnd.IgnoreOutcome.cfg new file mode 100644 index 00000000000..f280703b746 --- /dev/null +++ b/docs/architecture/tla/McpOAuthFlowEnd.IgnoreOutcome.cfg @@ -0,0 +1,14 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + StopOnFinish = TRUE + StopOnClaim = TRUE + StopOnReconnect = TRUE + CheckOutcome = FALSE + ClaimOnce = TRUE + GuardContinuation = TRUE + ReplaceEndsFlow = TRUE + DeleteEndsFlow = TRUE + DisposeEndsFlows = TRUE + ErrorEndsFlow = TRUE +INVARIANTS TypeOK NoDuplicateFlow NoOrphanFlow ToolNotOrphaned NoErrorLeak NoStaleWrite OneContinuation ToolRequiresSuccess TimerOnlyWhileWaiting diff --git a/docs/architecture/tla/McpOAuthFlowEnd.ReconnectTimer.cfg b/docs/architecture/tla/McpOAuthFlowEnd.ReconnectTimer.cfg new file mode 100644 index 00000000000..30d142e8f36 --- /dev/null +++ b/docs/architecture/tla/McpOAuthFlowEnd.ReconnectTimer.cfg @@ -0,0 +1,14 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + StopOnFinish = TRUE + StopOnClaim = TRUE + StopOnReconnect = FALSE + CheckOutcome = TRUE + ClaimOnce = TRUE + GuardContinuation = TRUE + ReplaceEndsFlow = TRUE + DeleteEndsFlow = TRUE + DisposeEndsFlows = TRUE + ErrorEndsFlow = TRUE +INVARIANTS TypeOK NoDuplicateFlow NoOrphanFlow ToolNotOrphaned NoErrorLeak NoStaleWrite OneContinuation ToolRequiresSuccess TimerOnlyWhileWaiting diff --git a/docs/architecture/tla/McpOAuthFlowEnd.ReplaceLeak.cfg b/docs/architecture/tla/McpOAuthFlowEnd.ReplaceLeak.cfg index cefcb9dea65..294ab5088fc 100644 --- a/docs/architecture/tla/McpOAuthFlowEnd.ReplaceLeak.cfg +++ b/docs/architecture/tla/McpOAuthFlowEnd.ReplaceLeak.cfg @@ -2,8 +2,14 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANTS + StopOnFinish = TRUE + StopOnClaim = TRUE + StopOnReconnect = TRUE + CheckOutcome = TRUE + ClaimOnce = TRUE + GuardContinuation = TRUE ReplaceEndsFlow = FALSE DeleteEndsFlow = TRUE DisposeEndsFlows = TRUE ErrorEndsFlow = TRUE -INVARIANTS TypeOK NoDuplicateFlow NoOrphanFlow ToolNotOrphaned NoErrorLeak +INVARIANTS TypeOK NoDuplicateFlow NoOrphanFlow ToolNotOrphaned NoErrorLeak NoStaleWrite OneContinuation ToolRequiresSuccess TimerOnlyWhileWaiting diff --git a/docs/architecture/tla/McpOAuthFlowEnd.StaleContinuation.cfg b/docs/architecture/tla/McpOAuthFlowEnd.StaleContinuation.cfg new file mode 100644 index 00000000000..a7ea5f8b0e6 --- /dev/null +++ b/docs/architecture/tla/McpOAuthFlowEnd.StaleContinuation.cfg @@ -0,0 +1,14 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + StopOnFinish = TRUE + StopOnClaim = TRUE + StopOnReconnect = TRUE + CheckOutcome = TRUE + ClaimOnce = TRUE + GuardContinuation = FALSE + ReplaceEndsFlow = TRUE + DeleteEndsFlow = TRUE + DisposeEndsFlows = TRUE + ErrorEndsFlow = TRUE +INVARIANTS TypeOK NoDuplicateFlow NoOrphanFlow ToolNotOrphaned NoErrorLeak NoStaleWrite OneContinuation ToolRequiresSuccess TimerOnlyWhileWaiting diff --git a/docs/architecture/tla/McpOAuthFlowEnd.cfg b/docs/architecture/tla/McpOAuthFlowEnd.cfg index fd4e1e40fd9..f1be329bccf 100644 --- a/docs/architecture/tla/McpOAuthFlowEnd.cfg +++ b/docs/architecture/tla/McpOAuthFlowEnd.cfg @@ -1,8 +1,14 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANTS + StopOnFinish = TRUE + StopOnClaim = TRUE + StopOnReconnect = TRUE + CheckOutcome = TRUE + ClaimOnce = TRUE + GuardContinuation = TRUE ReplaceEndsFlow = TRUE DeleteEndsFlow = TRUE DisposeEndsFlows = TRUE ErrorEndsFlow = TRUE -INVARIANTS TypeOK NoDuplicateFlow NoOrphanFlow ToolNotOrphaned NoErrorLeak +INVARIANTS TypeOK NoDuplicateFlow NoOrphanFlow ToolNotOrphaned NoErrorLeak NoStaleWrite OneContinuation ToolRequiresSuccess TimerOnlyWhileWaiting diff --git a/docs/architecture/tla/McpOAuthFlowEnd.tla b/docs/architecture/tla/McpOAuthFlowEnd.tla index 96ce3047a7c..61d773d6d16 100644 --- a/docs/architecture/tla/McpOAuthFlowEnd.tla +++ b/docs/architecture/tla/McpOAuthFlowEnd.tla @@ -1,27 +1,66 @@ ---- MODULE McpOAuthFlowEnd ---- EXTENDS Naturals -\* Source: McpHub._runOAuthFlow registers the watcher entry in _oauthWatchers and -\* owns the flow promise. deleteConnection(), flow replacement in _runOAuthFlow(), +\* Source: McpHub.createOAuthFlow registers one entry in oauthFlows. +\* McpOAuthFlow owns the completion promise. deleteConnection(), flow replacement in createOAuthFlow(), \* dispose(), and the token-watcher error path remove or replace that entry. \* Sink: McpHub.callTool awaits the re-auth promise, and the flow promise resolves -\* through the shared removal path _endOAuthWatcher. +\* through McpOAuthFlow.finish. \* Failure: a removed watcher leaves its flow pending, so the notification stays \* open and tool calls that wait on the flow stay blocked (issue 2761). \* Failure: an old flow removes the watcher of a newer flow, so the newer flow \* can never time out or resolve. \* Failure: a reconnect that throws in the token watcher leaves the flow pending. -\* Invariants: WatchedFlowIsSingle, NoOrphanFlow, ToolNotOrphaned, NoErrorLeak. +\* Invariants: NoDuplicateFlow, NoOrphanFlow, ToolNotOrphaned, NoErrorLeak. \* Fix rule: every watcher removal goes through one shared path that also ends \* the flow, and a reconnect error ends the flow with a visible error. \* Scope: timeouts, cancellation, and the toast paths end the flow inside the \* flow itself; the model folds them into FlowEnds. Secret storage is an oracle. \* Scope: at most two flows and one watcher per key. One tool call waits at a time. \* Expect: Fixed holds. ReplaceLeak, DeleteLeak, DisposeLeak and ErrorLeak each fail. -\* Result: Fixed holds in 3 states. ReplaceLeak fails at 4 states (NoDuplicateFlow). -\* DeleteLeak fails at 4 states (NoOrphanFlow). DisposeLeak fails at 4 states -\* (NoOrphanFlow). ErrorLeak fails at 4 states (NoErrorLeak). +\* Result: Fixed holds in 672 states. ReplaceLeak fails at 80 states (NoDuplicateFlow). +\* DeleteLeak fails at 80 states (NoOrphanFlow). DisposeLeak fails at 80 states +\* (NoOrphanFlow). ErrorLeak fails at 80 states (NoErrorLeak). \* Property test: src/services/mcp/__tests__/mcp-oauth-flow.property.spec.ts. +\* Review ratchet: PR #2762, supplied review findings #1, #2, #3, #8 and #29. +\* Added: stale work must not reconnect or change a replacement connection. +\* Expect: the ownership guard blocks a stale continuation after each wait. +\* Cost: one agent, about 20 minutes across four models and their code tests. +\* Replay: 25 ownership cases and eight real HTTP cases pass. Guard sabotage fails. +\* Findings #42 and #44: corrected the invariant name, tool-wait check, and header. +\* Ratchet: covered 0, added 8. Retry and redirect findings have their own model. +\* Gap: task abort and scope step-up need separate source and sink models. +\* Simplification expectation: one flow owns cleanup and settlement; only one callback can claim its work. +\* Failure: token and toast callbacks both start reconnect work for the same flow. +\* Invariants: OneContinuation claims work once. ToolRequiresSuccess accepts only a connected outcome. +\* Scope: the claim and outcome oracles each describe one flow episode. +\* Sources: https://stately.ai/docs/invoke and https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal +\* Cost: one agent; shared flow object and synchronous registry removal. +\* Result: DoubleClaim fails in 71 states; IgnoreOutcome in 51; StaleContinuation in 75. +\* Findings: one terminal outcome also closes review #10. No new legacy runtime defect was found. +\* Runtime sabotage: claim and outcome guards fail five and four tests when removed. +\* Replay: synchronous removal fails before the refactor. The new HTTP cancellation cases pass. +\* Covered: NoStaleWrite also requires a current-connection check after the panel update. +\* Review ratchet: PR #2762 follow-ups A and D. Added 2 timer rules, covered 0, gap 0. +\* Failure: the approval timer cuts short browser authentication or reconnect setup. +\* Expect: TimerOnlyWhileWaiting fails when claim or reconnect keeps the timer armed. +\* Cost: one agent; two timer transitions and fake-time properties. +\* Timer result: BrowserTimer fails at 3 states; ReconnectTimer fails at 4. +\* Replay: a late Authenticate click fails before the fix; waiting, browser, and reconnect tests pass. +\* Runtime sabotage: removing either timer cleanup fails its phase test. +\* Simplification: McpOAuthFlow.transitionTo owns the timer exit action for every phase change. +\* Failure: a terminal transition leaves the approval timer armed. +\* Invariant: TimerOnlyWhileWaiting includes ended flows as well as browser and reconnect work. +\* Expect: no new runtime defect. FinishTimer sabotage must fail; the existing guards must still hold. +\* Cost: one agent; one timer transition and terminal-outcome property cases. +\* Simplification result: fixed holds in 672 states; FinishTimer fails at 2 states. +\* Null result: terminal timer properties passed before and after extraction. No new runtime defect was found. +\* Runtime sabotage: removing shared timer cleanup or the terminal guard fails the phase tests. +CONSTANTS StopOnFinish +CONSTANTS StopOnClaim, StopOnReconnect +CONSTANTS CheckOutcome +CONSTANTS ClaimOnce +CONSTANTS GuardContinuation CONSTANTS ReplaceEndsFlow \* TRUE when a replacement flow ends the replaced flow CONSTANTS DeleteEndsFlow \* TRUE when deleteConnection ends the flow CONSTANTS DisposeEndsFlows \* TRUE when dispose ends all flows @@ -32,9 +71,16 @@ VARIABLES pending \* number of flows not yet ended (0 to 2) VARIABLES toolWait \* a tool call waits on the re-auth promise VARIABLES errorLeak \* latch: a reconnect error left its flow pending -vars == <> +VARIABLES current, active, staleWrite, claims, flowResult, toolRetried, timerPhase, timerArmed +vars == <> Init == + /\ timerPhase = "waiting" /\ timerArmed = TRUE + /\ flowResult = "waiting" /\ toolRetried = FALSE + /\ claims = 0 + /\ current = TRUE + /\ active = TRUE + /\ staleWrite = FALSE /\ watcher = FALSE /\ pending = 0 /\ toolWait = FALSE @@ -43,6 +89,10 @@ Init == \* connectToServer starts a flow. A replacement ends the old flow through the \* shared path; without that rule the replaced flow stays pending forever. StartFlow == + /\ UNCHANGED <> + /\ UNCHANGED <> + /\ UNCHANGED claims + /\ UNCHANGED <> /\ pending' = IF watcher /\ ReplaceEndsFlow THEN pending ELSE IF pending < 2 THEN pending + 1 ELSE 2 /\ watcher' = TRUE @@ -50,6 +100,10 @@ StartFlow == \* callTool hits a 401 and starts the re-auth flow it waits on. CallTool == + /\ UNCHANGED <> + /\ UNCHANGED <> + /\ UNCHANGED claims + /\ UNCHANGED <> /\ toolWait' = TRUE /\ pending' = IF watcher /\ ReplaceEndsFlow THEN pending ELSE IF pending < 2 THEN pending + 1 ELSE 2 @@ -59,6 +113,10 @@ CallTool == \* deleteConnection removes the watcher. The shared path also ends the flow and \* releases the waiting tool call. DeleteConnection == + /\ UNCHANGED <> + /\ UNCHANGED <> + /\ UNCHANGED claims + /\ UNCHANGED <> /\ watcher' = FALSE /\ pending' = IF watcher /\ DeleteEndsFlow THEN pending - 1 ELSE pending /\ toolWait' = IF watcher /\ DeleteEndsFlow THEN FALSE ELSE toolWait @@ -67,6 +125,10 @@ DeleteConnection == \* The token watcher catches a reconnect error. The fix ends the flow and shows \* the error on the server status; the old code only logged it. WatcherError == + /\ UNCHANGED <> + /\ UNCHANGED <> + /\ UNCHANGED claims + /\ UNCHANGED <> /\ pending >= 1 /\ errorLeak' = (errorLeak \/ ~ErrorEndsFlow) /\ pending' = IF ErrorEndsFlow THEN pending - 1 ELSE pending @@ -75,6 +137,10 @@ WatcherError == \* A flow ends inside itself: timeout, cancel, or a completed sign-in. FlowEnds == + /\ UNCHANGED <> + /\ UNCHANGED <> + /\ UNCHANGED claims + /\ UNCHANGED <> /\ pending >= 1 /\ pending' = pending - 1 /\ watcher' = FALSE @@ -83,12 +149,81 @@ FlowEnds == \* The hub is disposed. The shared path ends every flow and releases every wait. Dispose == + /\ UNCHANGED <> + /\ UNCHANGED <> + /\ UNCHANGED claims + /\ UNCHANGED <> /\ watcher' = FALSE /\ pending' = IF DisposeEndsFlows THEN 0 ELSE pending /\ toolWait' = IF DisposeEndsFlows THEN FALSE ELSE toolWait /\ UNCHANGED errorLeak +Invalidate == + /\ UNCHANGED <> + /\ UNCHANGED <> + /\ UNCHANGED claims + /\ current' = FALSE + /\ UNCHANGED <> + +\* An await resumes after delete, disable, dispose, or replacement. +Continue == + /\ UNCHANGED <> + /\ UNCHANGED <> + /\ UNCHANGED claims + /\ active + /\ active' = FALSE + /\ staleWrite' = (~current /\ ~GuardContinuation) + /\ UNCHANGED <> + +NoStaleWrite == ~staleWrite + +Claim == + /\ UNCHANGED <> + /\ UNCHANGED <> + /\ claims < 2 + /\ (claims = 0 \/ ~ClaimOnce) + /\ claims' = claims + 1 + /\ UNCHANGED <> + +OneContinuation == claims <= 1 + +Settle == + /\ UNCHANGED <> + /\ flowResult = "waiting" + /\ flowResult' \in {"connected", "cancelled", "failed", "removed", "timed-out"} + /\ UNCHANGED <> +RetryTool == + /\ UNCHANGED <> + /\ flowResult # "waiting" + /\ toolRetried' = (toolRetried \/ (~CheckOutcome \/ flowResult = "connected")) + /\ UNCHANGED <> +ToolRequiresSuccess == toolRetried => flowResult = "connected" + +\* One phase transition owns the approval timer exit action. +ChangeTimerPhase(nextPhase, stopTimer) == + /\ timerPhase' = nextPhase + /\ timerArmed' = IF stopTimer THEN FALSE ELSE timerArmed + /\ UNCHANGED <> +ClaimBrowser == + /\ timerPhase = "waiting" + /\ ChangeTimerPhase("browser", StopOnClaim) +StartReconnect == + /\ timerPhase \in {"waiting", "browser"} + /\ ChangeTimerPhase("reconnecting", StopOnReconnect) +FinishTimer == + /\ timerPhase # "ended" + /\ ChangeTimerPhase("ended", StopOnFinish) +TimerOnlyWhileWaiting == timerArmed => timerPhase = "waiting" + Next == + \/ FinishTimer + \/ ClaimBrowser + \/ StartReconnect + \/ Settle + \/ RetryTool + \/ Claim + \/ Invalidate + \/ Continue \/ StartFlow \/ CallTool \/ DeleteConnection @@ -99,6 +234,11 @@ Next == Spec == Init /\ [][Next]_vars TypeOK == + /\ timerPhase \in {"waiting", "browser", "reconnecting", "ended"} + /\ timerArmed \in BOOLEAN + /\ claims \in 0..2 + /\ flowResult \in {"waiting", "connected", "cancelled", "removed", "failed", "timed-out"} + /\ toolRetried \in BOOLEAN /\ watcher \in BOOLEAN /\ pending \in 0 .. 2 /\ toolWait \in BOOLEAN @@ -113,7 +253,7 @@ NoDuplicateFlow == pending <= 1 NoOrphanFlow == pending >= 1 => watcher \* A waiting tool call either waits on a live flow or was released by its end. -ToolNotOrphaned == toolWait => (watcher \/ pending = 0) +ToolNotOrphaned == toolWait => (watcher /\ pending = 1) \* A reconnect error never leaves its flow pending. NoErrorLeak == ~errorLeak diff --git a/docs/architecture/tla/McpOAuthRedirectUrl.LostCachedClient.cfg b/docs/architecture/tla/McpOAuthRedirectUrl.LostCachedClient.cfg new file mode 100644 index 00000000000..b2686c9b261 --- /dev/null +++ b/docs/architecture/tla/McpOAuthRedirectUrl.LostCachedClient.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + FixRedirectUri = TRUE + EnsureListener = TRUE + PreserveCachedClient = FALSE +INVARIANTS TypeOK NoBadOpen CachedRegistrationRetained diff --git a/docs/architecture/tla/McpOAuthRedirectUrl.NoEnsure.cfg b/docs/architecture/tla/McpOAuthRedirectUrl.NoEnsure.cfg index 0a4bbf319bd..e3122d576c6 100644 --- a/docs/architecture/tla/McpOAuthRedirectUrl.NoEnsure.cfg +++ b/docs/architecture/tla/McpOAuthRedirectUrl.NoEnsure.cfg @@ -4,5 +4,5 @@ CHECK_DEADLOCK FALSE CONSTANTS FixRedirectUri = TRUE EnsureListener = FALSE - CachedClient = TRUE -INVARIANTS TypeOK NoBadOpen + PreserveCachedClient = TRUE +INVARIANTS TypeOK NoBadOpen CachedRegistrationRetained diff --git a/docs/architecture/tla/McpOAuthRedirectUrl.NoOverride.cfg b/docs/architecture/tla/McpOAuthRedirectUrl.NoOverride.cfg index 0e436f7f7d1..3087d61079a 100644 --- a/docs/architecture/tla/McpOAuthRedirectUrl.NoOverride.cfg +++ b/docs/architecture/tla/McpOAuthRedirectUrl.NoOverride.cfg @@ -4,5 +4,5 @@ CHECK_DEADLOCK FALSE CONSTANTS FixRedirectUri = FALSE EnsureListener = TRUE - CachedClient = TRUE -INVARIANTS TypeOK NoBadOpen + PreserveCachedClient = TRUE +INVARIANTS TypeOK NoBadOpen CachedRegistrationRetained diff --git a/docs/architecture/tla/McpOAuthRedirectUrl.cfg b/docs/architecture/tla/McpOAuthRedirectUrl.cfg index b14de8b8f34..f4a408f8d5d 100644 --- a/docs/architecture/tla/McpOAuthRedirectUrl.cfg +++ b/docs/architecture/tla/McpOAuthRedirectUrl.cfg @@ -3,5 +3,5 @@ CHECK_DEADLOCK FALSE CONSTANTS FixRedirectUri = TRUE EnsureListener = TRUE - CachedClient = TRUE -INVARIANTS TypeOK NoBadOpen + PreserveCachedClient = TRUE +INVARIANTS TypeOK NoBadOpen CachedRegistrationRetained diff --git a/docs/architecture/tla/McpOAuthRedirectUrl.tla b/docs/architecture/tla/McpOAuthRedirectUrl.tla index 8bff3fd6948..4b3739e79c4 100644 --- a/docs/architecture/tla/McpOAuthRedirectUrl.tla +++ b/docs/architecture/tla/McpOAuthRedirectUrl.tla @@ -2,23 +2,26 @@ \* Source: StreamableHTTPClientTransport auth() builds the authorization URL from \* provider.redirectUrl before McpOAuthClientProvider.redirectToAuthorization runs. \* Sink: McpHub._completeOAuthFlow opens the stored URL with authProvider.openBrowser(). -\* Failure: the opened URL carries redirect_uri port 0, because a cached client -\* returns early from registerClientIfNeeded() and never starts the listener. +\* Failure: the opened URL carries port 0 when the SDK builds it before listener startup. \* Invariant: NoBadOpen. The opened URL redirect_uri equals the active listener \* port and is never 0. \* Fix rule: redirectToAuthorization starts the listener first, then overrides \* redirect_uri. The rule covers the first connect and a later 401. -\* Scope: registerClientIfNeeded and openBrowser are oracles. The listener starts -\* only inside those two calls, as in the code. A listener that dies between the +\* Scope: registration and authorization can each start the listener. +\* A listener that dies between the \* URL store and the open is out of scope; the next flow stores a fresh URL. \* A strict server that rejects a changed port is out of scope (issue follow-up). -\* Result: Fixed holds in 5 states. NoOverride fails at 4 states. NoEnsure fails -\* at 3 states. No additional failure was found. +\* Result: fixed holds in 14 states. NoOverride fails at 9 states, NoEnsure at 10, +\* and LostCachedClient at 2. The cached listener-bind regression passes in TypeScript. +\* Expect: fixed holds. Each missing redirect guard or cache assignment must fail. +\* Cost: one agent; reused the redirect model and added one cache-failure action. +\* Review ratchet: PR #2762 supplied findings #13, #36, #39, #43 and #44, added 5. \* Property test: src/services/mcp/__tests__/mcp-oauth-flow.property.spec.ts. CONSTANTS FixRedirectUri \* TRUE when redirectToAuthorization overrides redirect_uri CONSTANTS EnsureListener \* TRUE when redirectToAuthorization starts the listener first -CONSTANTS CachedClient \* TRUE when the client registration is cached and skips DCR +CONSTANTS PreserveCachedClient +VARIABLES cachedClientInfo, bindingFailure VARIABLES listenerPort \* port of the active callback listener; 0 when none VARIABLES sdkUrlPort \* redirect_uri port the SDK wrote into the URL @@ -27,9 +30,11 @@ VARIABLES urlStored \* redirectToAuthorization stored the URL for openBrows VARIABLES opened \* the URL was opened for the user VARIABLES badOpen \* latch: an open used a stale or zero port -vars == <> +vars == <> Init == + /\ cachedClientInfo = FALSE + /\ bindingFailure = FALSE /\ listenerPort = 0 /\ sdkUrlPort = 0 /\ finalUrlPort = 0 @@ -37,19 +42,21 @@ Init == /\ opened = FALSE /\ badOpen = FALSE -\* registerClientIfNeeded: a fresh DCR starts the listener; a cached client -\* returns early and starts nothing. +\* Both cached registration and fresh DCR can start the listener. RegisterClient == - /\ listenerPort' = IF CachedClient \/ listenerPort # 0 THEN listenerPort ELSE 1 + /\ UNCHANGED <> + /\ listenerPort' = 1 /\ UNCHANGED <> \* The SDK builds the URL from provider.redirectUrl before the listener starts. SdkBuildsUrl == + /\ UNCHANGED <> /\ sdkUrlPort' = listenerPort /\ UNCHANGED <> \* redirectToAuthorization: ensure the listener owns a real port, then set redirect_uri. Redirect == + /\ UNCHANGED <> /\ listenerPort' = IF EnsureListener /\ listenerPort = 0 THEN 1 ELSE listenerPort /\ finalUrlPort' = IF FixRedirectUri THEN listenerPort' ELSE sdkUrlPort /\ urlStored' = TRUE @@ -58,12 +65,21 @@ Redirect == \* The user confirmed the toast and the stored URL is opened. A stale or zero \* port at open time is a bad open. OpenBrowser == + /\ UNCHANGED <> /\ urlStored /\ opened' = TRUE /\ badOpen' = (badOpen \/ finalUrlPort # listenerPort \/ finalUrlPort = 0) /\ UNCHANGED <> +CachedBindFailure == + /\ cachedClientInfo' = PreserveCachedClient + /\ bindingFailure' = TRUE + /\ UNCHANGED <> + +CachedRegistrationRetained == bindingFailure => cachedClientInfo + Next == + \/ CachedBindFailure \/ RegisterClient \/ SdkBuildsUrl \/ Redirect diff --git a/docs/architecture/tla/McpOAuthRetry.DiscoveryLoop.cfg b/docs/architecture/tla/McpOAuthRetry.DiscoveryLoop.cfg new file mode 100644 index 00000000000..9dd78ce22f5 --- /dev/null +++ b/docs/architecture/tla/McpOAuthRetry.DiscoveryLoop.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANT GuardDiscovery = FALSE +CONSTANT ResetOnInitialize = FALSE +INVARIANTS Bounded DiscoveryBounded diff --git a/docs/architecture/tla/McpOAuthRetry.ResetOnInitialize.cfg b/docs/architecture/tla/McpOAuthRetry.ResetOnInitialize.cfg new file mode 100644 index 00000000000..0243b9f34e3 --- /dev/null +++ b/docs/architecture/tla/McpOAuthRetry.ResetOnInitialize.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANT GuardDiscovery = TRUE +CONSTANT ResetOnInitialize = TRUE +INVARIANTS Bounded DiscoveryBounded diff --git a/docs/architecture/tla/McpOAuthRetry.cfg b/docs/architecture/tla/McpOAuthRetry.cfg new file mode 100644 index 00000000000..a67b63c242c --- /dev/null +++ b/docs/architecture/tla/McpOAuthRetry.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANT GuardDiscovery = TRUE +CONSTANT ResetOnInitialize = FALSE +INVARIANTS Bounded DiscoveryBounded diff --git a/docs/architecture/tla/McpOAuthRetry.tla b/docs/architecture/tla/McpOAuthRetry.tla new file mode 100644 index 00000000000..d8e5ab8061d --- /dev/null +++ b/docs/architecture/tla/McpOAuthRetry.tla @@ -0,0 +1,44 @@ +---- MODULE McpOAuthRetry ---- +EXTENDS Naturals +\* Source: McpHub._initiateOAuthFlow receives a rejected saved token. +\* Sink: reconnectOAuthConnection sends another initialize request. +\* Failure: initialize success resets the bound before an authorized request succeeds. +\* Invariant: one unchanged token permits at most two automatic retries in this model. +\* Expect: fixed holds; ResetOnInitialize fails when stream authorization fails later. +\* Review ratchet: PR #2762 supplied findings #4, #14, #23, #24 and #25, added 5. +\* Cost: one agent, one bounded model and two sabotage configurations. +\* Result: fixed holds in 12 states. DiscoveryLoop fails at 9 states. +\* ResetOnInitialize fails at 13 states. The code retry regressions pass. +\* Finding #5: discovery retries require a prior skipped discovery, added 1. +CONSTANT ResetOnInitialize, GuardDiscovery +VARIABLES count, requests, initialized, skippedDiscovery, discoveryRetries +vars == <> +Init == /\ count = 0 /\ requests = 0 /\ initialized = FALSE + /\ skippedDiscovery = TRUE /\ discoveryRetries = 0 +Reject == + /\ UNCHANGED <> + /\ count < 2 + /\ requests < 3 + /\ count' = count + 1 + /\ requests' = requests + 1 + /\ initialized' = FALSE +Initialize == + /\ UNCHANGED <> + /\ ~initialized + /\ count' = IF ResetOnInitialize THEN 0 ELSE count + /\ initialized' = TRUE + /\ UNCHANGED requests +\* A changed access token starts a new retry budget. +NewToken == /\ count' = 0 /\ requests' = 0 /\ initialized' = FALSE + /\ UNCHANGED <> +NoMetadata == + /\ (skippedDiscovery \/ ~GuardDiscovery) + /\ discoveryRetries < 2 + /\ skippedDiscovery' = FALSE + /\ discoveryRetries' = discoveryRetries + 1 + /\ UNCHANGED <> +DiscoveryBounded == discoveryRetries <= 1 +Next == Reject \/ Initialize \/ NewToken \/ NoMetadata +Spec == Init /\ [][Next]_vars +Bounded == requests <= 2 +==== diff --git a/docs/architecture/tla/McpOAuthStatusHandoff.GenericDuringAuth.cfg b/docs/architecture/tla/McpOAuthStatusHandoff.GenericDuringAuth.cfg new file mode 100644 index 00000000000..2f7a4a7b6de --- /dev/null +++ b/docs/architecture/tla/McpOAuthStatusHandoff.GenericDuringAuth.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + GuardTransport = TRUE + GuardConnecting = FALSE + NotifyOnConnected = TRUE +INVARIANTS TypeOK PanelShowsConnected NoStaleTransportError AuthStillConnecting diff --git a/docs/architecture/tla/McpOAuthStatusHandoff.NoEarlyNotify.cfg b/docs/architecture/tla/McpOAuthStatusHandoff.NoEarlyNotify.cfg index eb40d3361e7..1809b21dd4a 100644 --- a/docs/architecture/tla/McpOAuthStatusHandoff.NoEarlyNotify.cfg +++ b/docs/architecture/tla/McpOAuthStatusHandoff.NoEarlyNotify.cfg @@ -2,5 +2,7 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANTS + GuardTransport = TRUE + GuardConnecting = TRUE NotifyOnConnected = FALSE -INVARIANTS TypeOK PanelShowsConnected +INVARIANTS TypeOK PanelShowsConnected NoStaleTransportError AuthStillConnecting diff --git a/docs/architecture/tla/McpOAuthStatusHandoff.StaleTransport.cfg b/docs/architecture/tla/McpOAuthStatusHandoff.StaleTransport.cfg new file mode 100644 index 00000000000..2dcb12b433e --- /dev/null +++ b/docs/architecture/tla/McpOAuthStatusHandoff.StaleTransport.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + GuardTransport = FALSE + GuardConnecting = TRUE + NotifyOnConnected = TRUE +INVARIANTS TypeOK PanelShowsConnected NoStaleTransportError AuthStillConnecting diff --git a/docs/architecture/tla/McpOAuthStatusHandoff.cfg b/docs/architecture/tla/McpOAuthStatusHandoff.cfg index d5eb42498c0..66238f85f18 100644 --- a/docs/architecture/tla/McpOAuthStatusHandoff.cfg +++ b/docs/architecture/tla/McpOAuthStatusHandoff.cfg @@ -1,5 +1,7 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANTS + GuardTransport = TRUE + GuardConnecting = TRUE NotifyOnConnected = TRUE -INVARIANTS TypeOK PanelShowsConnected +INVARIANTS TypeOK PanelShowsConnected NoStaleTransportError AuthStillConnecting diff --git a/docs/architecture/tla/McpOAuthStatusHandoff.tla b/docs/architecture/tla/McpOAuthStatusHandoff.tla index 7b4853f6696..b062ee54660 100644 --- a/docs/architecture/tla/McpOAuthStatusHandoff.tla +++ b/docs/architecture/tla/McpOAuthStatusHandoff.tla @@ -10,13 +10,23 @@ EXTENDS Naturals \* panel already shows "connected", even while list requests are pending. \* Fix rule: notifyWebviewOfServerChanges runs when the status changes, and runs \* again when the lists arrive. -\* Scope: one server, one connect, and up to two list requests. Reconnects, -\* 401 flows, and transport errors are outside this model. +\* Scope: one server, one connect, and up to two list requests. +\* 401 errors and generic HTTP errors use a separate stream-status oracle. \* Expect: Fixed holds. NoEarlyNotify fails. -\* Result: Fixed holds in 4 states. NoEarlyNotify fails at 2 states +\* Result: Fixed holds in 12 states. NoEarlyNotify fails at 3 states \* (PanelShowsConnected). No additional failure was found. +\* Cost: one agent; header correction only. +\* Review ratchet: PR #2762 supplied finding #44, added 1. \* Property test: src/services/mcp/__tests__/mcp-oauth-flow.property.spec.ts. +\* Review ratchet: PR #2762 follow-ups B and C. Added 2, covered 0, gap 0. +\* Source: HTTP transport.onerror. Sink: the current connection status and error. +\* Expect: stale transport errors do nothing; generic errors preserve an OAuth connect. +\* Cost: one agent; two SDK inputs and focused transport regression tests. +\* Transport result: StaleTransport and GenericDuringAuth each fail at 3 states. +\* Replay: both stale error types and a generic error during connect fail before the fix. +\* Runtime sabotage: each HTTP guard and the stdio correction fail their regression tests. +CONSTANTS GuardTransport, GuardConnecting CONSTANTS NotifyOnConnected \* TRUE when the status change itself updates the panel VARIABLES status \* connection status the hub holds for the server @@ -24,9 +34,11 @@ VARIABLES panelStatus \* status the panel last received VARIABLES pendingLists \* list requests not finished yet (0 to 2) VARIABLES listsArrived \* the list results were fetched -vars == <> +VARIABLES streamStatus, staleError, interruptedAuth +vars == <> Init == + /\ streamStatus = "connecting" /\ staleError = FALSE /\ interruptedAuth = FALSE /\ status = "connecting" /\ panelStatus = "connecting" /\ pendingLists = 0 @@ -35,6 +47,7 @@ Init == \* client.connect succeeded. The fix updates the panel in the same step; the \* old code only fetched the lists here. ConnectOk == + /\ UNCHANGED <> /\ status' = "connected" /\ pendingLists' = 2 /\ listsArrived' = FALSE @@ -43,19 +56,43 @@ ConnectOk == \* A list request finished. Only after all of them does the old code update the \* panel; the fix updates again when the lists arrive. ListDone == + /\ UNCHANGED <> /\ pendingLists >= 1 /\ pendingLists' = pendingLists - 1 /\ panelStatus' = IF pendingLists = 1 THEN "connected" ELSE panelStatus /\ listsArrived' = (pendingLists = 1) /\ UNCHANGED status +StreamConnect == + /\ streamStatus = "connecting" + /\ streamStatus' = "connected" + /\ UNCHANGED <> +\* The transport owner and error kind are inputs from the SDK. +HttpError == + \E sameTransport \in BOOLEAN, unauthorized \in BOOLEAN : + LET allowed == (sameTransport \/ ~GuardTransport) + reauth == unauthorized /\ streamStatus = "connected" + generic == ~unauthorized /\ (streamStatus # "connecting" \/ ~GuardConnecting) + IN /\ streamStatus' = IF ~allowed THEN streamStatus + ELSE IF reauth THEN "connecting" + ELSE IF generic THEN "disconnected" ELSE streamStatus + /\ staleError' = (staleError \/ (allowed /\ ~sameTransport)) + /\ interruptedAuth' = (interruptedAuth \/ (allowed /\ generic /\ streamStatus = "connecting")) + /\ UNCHANGED <> +NoStaleTransportError == ~staleError +AuthStillConnecting == ~interruptedAuth + Next == + \/ StreamConnect + \/ HttpError \/ ConnectOk \/ ListDone Spec == Init /\ [][Next]_vars TypeOK == + /\ streamStatus \in {"connecting", "connected", "disconnected"} + /\ staleError \in BOOLEAN /\ interruptedAuth \in BOOLEAN /\ status \in {"connecting", "connected"} /\ panelStatus \in {"connecting", "connected"} /\ pendingLists \in 0 .. 2 diff --git a/src/eslint-suppressions.json b/src/eslint-suppressions.json index e07b00bd6a9..a1d6f7a7bce 100644 --- a/src/eslint-suppressions.json +++ b/src/eslint-suppressions.json @@ -1231,7 +1231,7 @@ }, "services/mcp/__tests__/McpHub.spec.ts": { "@typescript-eslint/no-explicit-any": { - "count": 150 + "count": 143 } }, "services/mcp/__tests__/McpOAuthClientProvider.spec.ts": { diff --git a/src/services/mcp/McpHub.ts b/src/services/mcp/McpHub.ts index e5141c50188..0a8aaf237ed 100644 --- a/src/services/mcp/McpHub.ts +++ b/src/services/mcp/McpHub.ts @@ -45,6 +45,7 @@ import { TOKEN_EXPIRY_BUFFER_MS, } from "./constants" import { SecretStorageService } from "./SecretStorageService" +import { McpOAuthFlow, type McpOAuthFlowOutcome } from "./McpOAuthFlow" import { McpOAuthClientProvider } from "./McpOAuthClientProvider" import { arePathsEqual, getWorkspacePath } from "../../utils/path" import { injectVariables } from "../../utils/config" @@ -70,17 +71,6 @@ export type DisconnectedMcpConnection = { export type McpConnection = ConnectedMcpConnection | DisconnectedMcpConnection -/** - * A registered OAuth flow watcher: the cross-window token subscription, its - * flow timeout, and the shared removal path that also ends the flow. - */ -interface McpOAuthWatcher { - unsubscribe: () => void - abortHandle: NodeJS.Timeout - /** Ends the flow this watcher belongs to. Idempotent; never removes another flow's entry. */ - endFlow: () => void -} - // Enum for disable reasons export enum DisableReason { MCP_DISABLED = "mcpDisabled", @@ -218,9 +208,9 @@ export class McpHub { private sanitizedNameRegistry: Map = new Map() private initializationPromise: Promise private secretStorage?: SecretStorageService - private reauthPromises: Map> = new Map() - private _oauthWatchers: Map = new Map() - /** Tracks automatic reconnects that reuse a saved token the server rejected, per server URL. */ + private readonly oauthFlows = new Map() + private readonly connectionRemovals = new Map() + /** Tracks rejected-token retries by server, source, URL, and configured OAuth client. */ private oauthTokenRetries: Map = new Map() constructor(provider: ClineProvider, secretStorage?: SecretStorageService) { @@ -692,18 +682,18 @@ export class McpHub { } /** - * Creates a placeholder connection for disabled servers or when MCP is globally disabled + * Creates a disconnected row for a disabled or stopped server. * @param name The server name * @param config The server configuration * @param source The source of the server (global or project) - * @param reason The reason for creating a placeholder (mcpDisabled or serverDisabled) + * @param reason The optional reason for disabling the server * @returns A placeholder DisconnectedMcpConnection object */ private createPlaceholderConnection( name: string, config: z.infer, source: "global" | "project", - reason: DisableReason, + reason?: DisableReason, ): DisconnectedMcpConnection { return { type: "disconnected", @@ -738,9 +728,19 @@ export class McpHub { name: string, config: z.infer, source: "global" | "project" = "global", + preservedFlow?: McpOAuthFlow, ): Promise { - // Remove existing connection if it exists with the same source - await this.deleteConnection(name, source) + // A later removal also cancels setup before a connection exists. + const removal = preservedFlow + ? this.deleteConnection(name, source, preservedFlow) + : this.deleteConnection(name, source) + const revision = this.connectionRemovals.get(`${name}:${source}`) + const isCurrentAttempt = () => + !this.isDisposed && + preservedFlow?.phase !== "ended" && + this.connectionRemovals.get(`${name}:${source}`) === revision + await removal + if (!isCurrentAttempt()) return // Register the sanitized name for O(1) lookup const sanitizedName = sanitizeMcpName(name) @@ -748,6 +748,7 @@ export class McpHub { // Check if MCP is globally enabled const mcpEnabled = await this.isMcpEnabled() + if (!isCurrentAttempt()) return if (!mcpEnabled) { // Still create a connection object to track the server, but don't actually connect const connection = this.createPlaceholderConnection(name, config, source, DisableReason.MCP_DISABLED) @@ -779,6 +780,7 @@ export class McpHub { ) let transport: StdioClientTransport | SSEClientTransport | StreamableHTTPClientTransport + let skippedOAuthDiscovery = false let streamableHttpAuthProvider: McpOAuthClientProvider | undefined // Inject variables to the config (environment, magic variables,...) @@ -879,6 +881,7 @@ export class McpHub { const hasOAuthData = await this.secretStorage.hasOAuthData(configInjected.url, oauthClientId) const knownNonOAuth = McpOAuthClientProvider.isKnownNonOAuth(configInjected.url) const skipDiscovery = !oauthClientId && !hasOAuthData && knownNonOAuth + skippedOAuthDiscovery = skipDiscovery const authProvider = await McpOAuthClientProvider.create(configInjected.url, this.secretStorage, name, { skipDiscovery, @@ -909,57 +912,42 @@ export class McpHub { // Set up Streamable HTTP specific error handling transport.onerror = async (error) => { - console.error(`Transport error for "${name}" (streamable-http):`, error) const connection = this.findConnection(name, source) - if (connection && connection.type === "connected") { - if (error instanceof UnauthorizedError && authProvider) { - // If we're already in the OAuth / polling flow, ignore transport - // retries that surface another 401 — the poll or _completeOAuthFlow - // will reconnect from scratch once tokens arrive. - if (connection.server.status === "connecting") { - return - } - - // Mid-session re-auth triggered by a tool call (401) - connection.server.status = "connecting" - - // Key the re-auth flow by the connection itself, not the server - // name. A key shared across connections lets an old flow swallow - // the 401 of a newer connection and leave it connecting forever. - const reauthKey = connection - let reauthPromise = this.reauthPromises.get(reauthKey) - if (!reauthPromise) { - reauthPromise = this._initiateOAuthFlow( - name, - source, - JSON.parse(connection.server.config), - authProvider, - transport as StreamableHTTPClientTransport, - connection as ConnectedMcpConnection, - ) - .catch((err) => { - console.error(`OAuth flow failed for "${name}":`, err) - }) - .finally(() => { - this.reauthPromises.delete(reauthKey) - }) - this.reauthPromises.set(reauthKey, reauthPromise) - } - return - } - - connection.server.status = "disconnected" - this.appendErrorMessage(connection, error instanceof Error ? error.message : `${error}`) - } else if (connection) { - connection.server.status = "disconnected" - this.appendErrorMessage(connection, error instanceof Error ? error.message : `${error}`) + if ( + !connection || + connection.type !== "connected" || + connection.transport !== transport || + !this.isCurrentOAuthConnection(connection) + ) + return + console.error(`Transport error for "${name}" (streamable-http):`, error) + if (error instanceof UnauthorizedError) { + if (connection.server.status === "connecting") return + connection.server.status = "connecting" + void this._initiateOAuthFlow( + name, + source, + JSON.parse(connection.server.config), + authProvider, + transport as StreamableHTTPClientTransport, + connection, + ) + return } + if (connection.server.status === "connecting") return + connection.server.status = "disconnected" + this.appendErrorMessage(connection, error instanceof Error ? error.message : `${error}`) await this.notifyWebviewOfServerChanges() } transport.onclose = async () => { const connection = this.findConnection(name, source) - if (connection) { + if ( + connection && + connection.type === "connected" && + connection.transport === transport && + this.isCurrentOAuthConnection(connection) + ) { // If OAuth is in progress, don't overwrite "connecting" with "disconnected". // The transport will close/retry while we await the browser flow or poll; // the reconnect path (deleteConnection + connectToServer) handles cleanup. @@ -1042,6 +1030,12 @@ export class McpHub { transport, authProvider: streamableHttpAuthProvider, } + if (!isCurrentAttempt()) { + await transport.close() + await client.close() + await pendingAuthProvider?.close() + return + } this.connections.push(connection) pendingAuthProvider = undefined @@ -1057,10 +1051,9 @@ export class McpHub { // tear down and reconnect with full discovery now that we know // this is an OAuth server. The reconnect will do discovery since // the negative cache was cleared and no SecretStorage data exists yet. - if (!streamableHttpAuthProvider.hasMetadata) { + if (!streamableHttpAuthProvider.hasMetadata && skippedOAuthDiscovery) { await streamableHttpAuthProvider.close() - await this.deleteConnection(name, source) - void this.connectToServer(name, config, source) + await this.reconnectOAuthConnection(connection, configInjected) return } @@ -1072,7 +1065,7 @@ export class McpHub { void this._initiateOAuthFlow( name, source, - config, + configInjected, streamableHttpAuthProvider, transport as StreamableHTTPClientTransport, connection, @@ -1089,30 +1082,30 @@ export class McpHub { // We keep the authProvider on the connection so it can handle mid-session 401s. await streamableHttpAuthProvider?.close() + if (!isCurrentAttempt() || !this.isCurrentOAuthConnection(connection)) return connection.server.status = "connected" connection.server.error = "" connection.server.instructions = client.getInstructions() - // A successful connect also resets the rejected-token retry bound. - if (configInjected.type === "streamable-http" && configInjected.url) { - this.oauthTokenRetries.delete(configInjected.url) - } - // The list requests below can each take up to the request timeout. Update // the panel now so the server shows connected immediately, then update it // again when the tool, resource, and template lists arrive. - await this.notifyWebviewOfServerChanges() + await this.notifyWebviewOfServerChanges().catch((error: unknown) => { + console.error("[McpHub] Failed to update the MCP panel:", error) + }) // Initial fetch of tools and resources connection.server.tools = await this.fetchToolsList(name, source) connection.server.resources = await this.fetchResourcesList(name, source) connection.server.resourceTemplates = await this.fetchResourceTemplatesList(name, source) - await this.notifyWebviewOfServerChanges() + await this.notifyWebviewOfServerChanges().catch((error: unknown) => { + console.error("[McpHub] Failed to update the MCP panel:", error) + }) } catch (error) { await pendingAuthProvider?.close() // Update status with error const connection = this.findConnection(name, source) - if (connection) { + if (connection && isCurrentAttempt()) { connection.server.status = "disconnected" this.appendErrorMessage(connection, error instanceof Error ? error.message : `${error}`) } @@ -1120,96 +1113,193 @@ export class McpHub { } } - /** - * Background task: waits for the user to complete the OAuth browser flow, - * exchanges the auth code for tokens, then reconnects from scratch. - * - * After the SDK throws UnauthorizedError the transport is left in a - * "started" state (_abortController is set), so we cannot simply call - * client.connect() on it again — the SDK would throw "already started". - * The clean solution is to delete the broken connection and let - * connectToServer() create fresh client/transport objects. The new - * provider will find the token in SecretStorage and connect without - * triggering another OAuth round-trip. - * - * This runs detached from the initialization path so `waitUntilReady()` - * and the rest of the extension are not blocked by the user's browser session. - */ - private async _initiateOAuthFlow( + private isCurrentOAuthConnection(connection: ConnectedMcpConnection): boolean { + return ( + !this.isDisposed && + !connection.server.disabled && + this.findConnection(connection.server.name, connection.server.source) === connection + ) + } + + private stopOAuthReconnect( + connection: ConnectedMcpConnection, + config: z.infer, + revision: number | undefined, + reason: unknown, + ): void { + const { name } = connection.server + const source = connection.server.source ?? "global" + const key = `${name}:${source}` + if (this.connectionRemovals.get(key) !== revision) return + const current = this.findConnection(name, source) + if ( + current && + (current.type !== "connected" || current.server.status !== "connecting" || this.oauthFlows.has(current)) + ) + return + // Detach first, then publish the error row before resource cleanup can yield. + const removal = this.deleteConnection(name, source) + if (reason === "cancelled" || reason === "timed-out") { + const stopped = this.createPlaceholderConnection(name, config, source) + this.appendErrorMessage( + stopped, + t(reason === "cancelled" ? "mcp:oauth.flow.cancelled" : "mcp:oauth.flow.timedOut"), + ) + this.connections.push(stopped) + this.sanitizedNameRegistry.set(sanitizeMcpName(name), name) + void this.notifyWebviewOfServerChanges().catch((error: unknown) => + console.error("[McpHub] Failed to update the MCP panel:", error), + ) + } + void removal.catch((error: unknown) => console.error("[McpHub] OAuth reconnect cleanup failed:", error)) + } + + private async reconnectOAuthConnection( + connection: ConnectedMcpConnection, + config: z.infer, + flow = this.oauthFlows.get(connection), + ): Promise { + const isFlowActive = () => flow?.phase !== "ended" + const canContinue = () => isFlowActive() && this.isCurrentOAuthConnection(connection) + if (!canContinue()) return false + flow?.beginReconnect() + await connection.authProvider?.close() + if (!canContinue()) return false + const { name } = connection.server + const source = connection.server.source ?? "global" + const validatedConfig = this.validateServerConfig(config, name) + const key = `${name}:${source}` + const removal = flow ? this.deleteConnection(name, source, flow) : this.deleteConnection(name, source) + const revision = this.connectionRemovals.get(key) + await removal + if ( + this.isDisposed || + !isFlowActive() || + connection.server.disabled || + this.connectionRemovals.get(key) !== revision + ) + return false + if (this.findConnection(name, source)) return false + const reconnect = this.connectToServer(name, validatedConfig, source, flow) + const reconnectRevision = this.connectionRemovals.get(key) + if (flow) { + const abortSetup = () => + this.stopOAuthReconnect(connection, validatedConfig, reconnectRevision, flow.signal.reason) + flow.signal.addEventListener("abort", abortSetup, { once: true }) + flow.addCleanup(() => flow.signal.removeEventListener("abort", abortSetup)) + if (flow.signal.aborted) abortSetup() + } + await reconnect + const replacement = this.findConnection(name, source) + await this.notifyWebviewOfServerChanges() + return ( + replacement?.type === "connected" && + replacement !== connection && + isFlowActive() && + replacement.server.status === "connected" && + this.isCurrentOAuthConnection(replacement) + ) + } + + private createOAuthFlow(connection: ConnectedMcpConnection, authProvider: McpOAuthClientProvider): McpOAuthFlow { + const replaced = [...this.oauthFlows].filter( + ([owner]) => + owner.server.name === connection.server.name && owner.server.source === connection.server.source, + ) + const flow = new McpOAuthFlow() + this.oauthFlows.set(connection, flow) + for (const [, active] of replaced) active.finish("removed") + flow.addCleanup(() => { + if (this.oauthFlows.get(connection) === flow) this.oauthFlows.delete(connection) + void authProvider + .close() + .catch((error: unknown) => console.error("[McpHub] OAuth provider cleanup failed:", error)) + }) + return flow + } + + /** Starts or joins the OAuth attempt owned by this connection. */ + private _initiateOAuthFlow( name: string, source: "global" | "project", config: z.infer, authProvider: McpOAuthClientProvider, transport: StreamableHTTPClientTransport, connection: ConnectedMcpConnection, + ): Promise { + const existing = this.oauthFlows.get(connection) + if (existing) return existing.promise + if (!this.isCurrentOAuthConnection(connection)) return Promise.resolve("removed") + const flow = this.createOAuthFlow(connection, authProvider) + void this.performOAuthFlow(name, source, config, authProvider, transport, connection, flow) + .catch(async (error: unknown) => { + console.error(`[McpHub] OAuth flow failed for "${name}":`, error) + await this._surfaceOAuthReconnectFailure( + connection, + error instanceof Error ? error.message : String(error), + ) + flow.finish("failed") + }) + .finally(() => flow.finish("failed")) + return flow.promise + } + + private async performOAuthFlow( + name: string, + source: "global" | "project", + config: z.infer, + authProvider: McpOAuthClientProvider, + transport: StreamableHTTPClientTransport, + connection: ConnectedMcpConnection, + flow: McpOAuthFlow, ): Promise { const serverUrl = "url" in config ? config.url : undefined const oauthClientId = config.type === "streamable-http" ? config.oauth?.clientId : undefined if (!serverUrl || !this.secretStorage) { + flow.finish("failed") return } - - // Register the cross-window token watcher BEFORE the initial token read so we - // don't miss a write that lands in the gap between the read and the subscription. - // After the read we immediately unsubscribe; the watcher inside _runOAuthFlow - // will set up its own long-lived subscription for the duration of the flow. - // Note: onDidChange fires on both writes AND deletes — the re-read below is - // authoritative; we only reconnect if it returns a valid (non-expired) token. let tokenChangedDuringRead = false - const unsubscribeCrossWindow = this.secretStorage.onDidChange( - serverUrl, - () => { - tokenChangedDuringRead = true - }, - oauthClientId, + const unsubscribe = flow.addCleanup( + this.secretStorage.onDidChange( + serverUrl, + () => { + tokenChangedDuringRead = true + }, + oauthClientId, + ), ) - - // Check if another window already saved valid tokens. - // Re-read after registering the watcher in case a write landed in the gap. - const existing = await this.secretStorage.getOAuthData(serverUrl, oauthClientId) - if (this.isDisposed) { - unsubscribeCrossWindow() - await authProvider.close() + let tokenToUse: Awaited> + try { + tokenToUse = await this.secretStorage.getOAuthData(serverUrl, oauthClientId) + if (flow.phase !== "ended" && !tokenToUse && tokenChangedDuringRead) { + tokenToUse = await this.secretStorage.getOAuthData(serverUrl, oauthClientId) + } + } finally { + unsubscribe() + } + if (flow.phase === "ended" || !this.isCurrentOAuthConnection(connection)) { + flow.finish("removed") return } - // If the first read missed but the watcher fired during it, re-read — a write - // may have landed between subscription and read completion. - const tokenToUse = - existing ?? - (tokenChangedDuringRead ? await this.secretStorage.getOAuthData(serverUrl, oauthClientId) : undefined) - unsubscribeCrossWindow() - - if (!this.isDisposed && tokenToUse && Date.now() < tokenToUse.expires_at - TOKEN_EXPIRY_BUFFER_MS) { - // The server just rejected this saved token. Reconnect after a delay, a - // bounded number of times. Without the bound, an always-rejecting server - // turns this path into an unlimited reconnect loop. + if (tokenToUse && Date.now() < tokenToUse.expires_at - TOKEN_EXPIRY_BUFFER_MS) { const tokenKey = tokenToUse.tokens?.access_token - const retryState = this.oauthTokenRetries.get(serverUrl) + const retryKey = JSON.stringify([name, source, serverUrl, oauthClientId]) + const retryState = this.oauthTokenRetries.get(retryKey) const attempt = retryState && retryState.tokenKey === tokenKey ? retryState.count + 1 : 1 if (attempt > OAUTH_TOKEN_RETRY_MAX_ATTEMPTS) { - // A new token resets the count; the same rejected token does not get - // another automatic retry. End with a visible error instead. - this.oauthTokenRetries.delete(serverUrl) - await this._surfaceOAuthReconnectFailure(name, source, t("mcp:oauth.flow.retriesExhausted", { name })) + console.warn(`[McpHub] OAuth token retries exhausted for "${name}" (${source})`) + await this._surfaceOAuthReconnectFailure(connection, t("mcp:oauth.flow.retriesExhausted", { name })) + flow.finish("failed") return } - this.oauthTokenRetries.set(serverUrl, { tokenKey, count: attempt }) + this.oauthTokenRetries.set(retryKey, { tokenKey, count: attempt }) + console.info(`[McpHub] OAuth token retry ${attempt} for "${name}" (${source})`) await delay(Math.min(OAUTH_TOKEN_RETRY_BASE_DELAY_MS * 2 ** (attempt - 1), OAUTH_TOKEN_RETRY_MAX_DELAY_MS)) - await authProvider.close() - await this.deleteConnection(name, source) - try { - await this.connectToServer(name, config, source) - await this.notifyWebviewOfServerChanges() - } catch (error) { - // A reconnect that throws must not propagate out of this detached flow: - // connectToServer already surfaced the error on the server status. - console.error(`[McpHub] OAuth reconnect failed for "${name}":`, error) - } + const connected = await this.reconnectOAuthConnection(connection, config, flow) + flow.finish(connected ? "connected" : "failed") return } - - // Persistent progress notification gives the user a visible Cancel button - // for the duration of the flow (even if they switch away from VS Code). await vscode.window.withProgress( { location: vscode.ProgressLocation.Notification, @@ -1228,26 +1318,18 @@ export class McpHub { progress, cancellationToken, oauthClientId, + flow, ), ) } - /** - * Ends a reconnect episode with a visible error: the server status becomes - * disconnected and the message is recorded, so the panel shows why the - * sign-in did not finish. - */ - private async _surfaceOAuthReconnectFailure( - name: string, - source: "global" | "project", - message: string, - ): Promise { - const conn = this.findConnection(name, source) - if (conn && conn.server.status !== "connected") { - conn.server.status = "disconnected" - this.appendErrorMessage(conn, message) - await this.notifyWebviewOfServerChanges() - } + private async _surfaceOAuthReconnectFailure(connection: ConnectedMcpConnection, message: string): Promise { + if (!this.isCurrentOAuthConnection(connection) || connection.server.status === "connected") return + connection.server.status = "disconnected" + this.appendErrorMessage(connection, message) + await this.notifyWebviewOfServerChanges().catch((error: unknown) => + console.error("[McpHub] Failed to update the MCP panel:", error), + ) } private _runOAuthFlow( @@ -1261,142 +1343,72 @@ export class McpHub { progress: vscode.Progress<{ message?: string; increment?: number }>, cancellationToken: vscode.CancellationToken, oauthClientId?: string, + existingFlow?: McpOAuthFlow, ): Promise { - const watcherKey = `${name}:${source}` - - // Cancel any existing watcher for this connection before starting a new one. - // The shared removal path also ends the replaced flow, so it cannot stay - // pending after its watcher is gone. - this._endOAuthWatcher(watcherKey) - - return new Promise((resolve) => { - let disposed = false - // A const holder keeps the TDZ safety: the cancellation callback can fire - // synchronously during registration, before the assignment completes. It - // then reads undefined and cleanup() runs without a disposable, which is - // correct. - const cancellation = { disposable: undefined as vscode.Disposable | undefined } - - const cleanup = (disposable?: vscode.Disposable) => { - if (disposed) return - disposed = true - clearTimeout(timeoutHandle) - unsubscribe() - disposable?.dispose() - // An ended flow must not remove a newer flow's watcher for this key. - if (this._oauthWatchers.get(watcherKey) === watcher) { - this._oauthWatchers.delete(watcherKey) - } - } - - // --- Cross-window token watcher --- - const onTokensChanged = async () => { - if (disposed || this.isDisposed) return - // Don't reconnect if the server is already connected (e.g. a token refresh - // from another window fired after _completeOAuthFlow already succeeded). - const conn = this.findConnection(name, source) - if (!conn || conn.server.status === "connected") { - cleanup(cancellation.disposable) - return - } - try { - const data = await this.secretStorage?.getOAuthData(serverUrl, oauthClientId) - // Re-check after the async yield — cancellation or completion may have - // fired while getOAuthData was in flight. - if (disposed || this.isDisposed) return - if (data && Date.now() < data.expires_at - TOKEN_EXPIRY_BUFFER_MS) { - cleanup(cancellation.disposable) - await authProvider.close() - await this.deleteConnection(name, source) - const validatedConfig = this.validateServerConfig(config, name) - await this.connectToServer(name, validatedConfig, source) - await this.notifyWebviewOfServerChanges() - resolve() - } - } catch (err) { - // A reconnect that throws must not leave this flow pending: end the - // flow and surface the error on the server status. - console.error(`[McpHub] OAuth token watcher failed for "${name}":`, err) - cleanup(cancellation.disposable) - void authProvider.close() - const conn = this.findConnection(name, source) - if (conn && conn.server.status !== "connected") { - conn.server.status = "disconnected" - this.appendErrorMessage(conn, err instanceof Error ? err.message : `${err}`) - void this.notifyWebviewOfServerChanges() - } - resolve() - } - } - - const unsubscribe = this.secretStorage!.onDidChange( + if (!this.isCurrentOAuthConnection(connection)) return Promise.resolve() + const flow = existingFlow ?? this.createOAuthFlow(connection, authProvider) + const fail = async (message: string, outcome: "failed" | "cancelled" | "timed-out") => { + if (flow.phase === "ended") return + const surfaced = this._surfaceOAuthReconnectFailure(connection, message) + flow.finish(outcome) + await surfaced + } + const run = (work: () => Promise) => { + if (!flow.claim()) return + void work().then( + (connected) => flow.finish(connected ? "connected" : "failed"), + (error: unknown) => fail(error instanceof Error ? error.message : String(error), "failed"), + ) + } + flow.addCleanup( + this.secretStorage!.onDidChange( serverUrl, () => { - void onTokensChanged() + if (flow.phase !== "waiting") return + void this.secretStorage!.getOAuthData(serverUrl, oauthClientId).then( + (data) => { + if (data && Date.now() < data.expires_at - TOKEN_EXPIRY_BUFFER_MS) { + run(() => this.reconnectOAuthConnection(connection, config, flow)) + } + }, + (error: unknown) => fail(error instanceof Error ? error.message : String(error), "failed"), + ) }, oauthClientId, - ) - - // --- Timeout --- - const timeoutHandle = setTimeout(() => { - if (disposed) return - cleanup(cancellation.disposable) - void authProvider.close() - const conn = this.findConnection(name, source) - if (conn && conn.server.status === "connecting") { - conn.server.status = "disconnected" - this.appendErrorMessage(conn, t("mcp:oauth.flow.timedOut")) - void this.notifyWebviewOfServerChanges() - } - resolve() - }, OAUTH_FLOW_TIMEOUT_MS) - - // Register in _oauthWatchers so deleteConnection() and dispose() can clean up. - // This must happen BEFORE installing the cancellation callback below: if the - // token is already cancelled at registration time, VS Code fires the callback - // synchronously inside onCancellationRequested(...), and cleanup() must find - // the watcher entry in the map in order to delete it. Registering after the - // callback would leave an orphan entry that survives disposal. - const watcher: McpOAuthWatcher = { - unsubscribe, - abortHandle: timeoutHandle, - // Shared removal path: an external removal (deleteConnection, flow - // replacement, dispose) ends this flow instead of leaving it pending. - endFlow: () => { - if (disposed) return - cleanup(cancellation.disposable) - resolve() - }, - } - this._oauthWatchers.set(watcherKey, watcher) - - // --- Cancellation (progress bar's Cancel button) --- - cancellation.disposable = cancellationToken.onCancellationRequested(() => { - if (disposed) return - // Don't pass cancellation.disposable here: if the token was already - // cancelled at registration time, VS Code fires this callback - // synchronously inside onCancellationRequested(...) — before the - // assignment completes, so the holder still holds undefined. VS Code - // also disposes its own listener once the token transitions to - // cancelled, so explicit disposal from inside the callback would be - // redundant anyway. - cleanup() - void authProvider.close() - const conn = this.findConnection(name, source) - if (conn && conn.server.status !== "connected") { - conn.server.status = "disconnected" - this.appendErrorMessage(conn, t("mcp:oauth.flow.cancelled")) - void this.notifyWebviewOfServerChanges() - } - resolve() - }) - - // In test mode, skip user interaction and proceed directly to complete the OAuth flow. - if (process.env.MCP_OAUTH_TEST_MODE === "true") { - void (async () => { - cleanup(cancellation.disposable) - try { - await this._completeOAuthFlow( + ), + ) + flow.setWaitingTimeout(() => { + void fail(t("mcp:oauth.flow.timedOut"), "timed-out") + }, OAUTH_FLOW_TIMEOUT_MS) + const cancellation = cancellationToken.onCancellationRequested(() => { + void fail(t("mcp:oauth.flow.cancelled"), "cancelled") + }) + flow.addCleanup(() => cancellation.dispose()) + if (cancellationToken.isCancellationRequested) { + void fail(t("mcp:oauth.flow.cancelled"), "cancelled") + } + if (process.env.MCP_OAUTH_TEST_MODE === "true") { + run(() => this._completeOAuthFlow(authProvider, transport, connection, name, source, cancellationToken)) + } else { + const authenticateLabel = t("mcp:oauth.flow.authenticateButton") + void Promise.resolve( + vscode.window.showInformationMessage( + t("mcp:oauth.flow.clickAuthenticate", { name }), + authenticateLabel, + ), + ).then( + (choice) => { + if (flow.phase !== "waiting") return + if (choice !== authenticateLabel) { + progress.report({ message: t("mcp:oauth.flow.dismissedHint") }) + return + } + run(async () => { + const tokens = await this.secretStorage!.getOAuthData(serverUrl, oauthClientId) + if (flow.phase === "ended") return false + if (tokens && Date.now() < tokens.expires_at - TOKEN_EXPIRY_BUFFER_MS) + return this.reconnectOAuthConnection(connection, config, flow) + return this._completeOAuthFlow( authProvider, transport, connection, @@ -1404,68 +1416,12 @@ export class McpHub { source, cancellationToken, ) - } catch { - // _completeOAuthFlow handles its own error state - } - resolve() - })() - return - } - - // Non-modal toast — fires once. If dismissed without clicking Authenticate, - // the flow stays alive via the persistent progress bar (Cancel to abort). - const authenticateLabel = t("mcp:oauth.flow.authenticateButton") - void (async () => { - const choice = await vscode.window.showInformationMessage( - t("mcp:oauth.flow.clickAuthenticate", { name }), - authenticateLabel, - ) - - if (disposed) return - - if (choice !== authenticateLabel) { - progress.report({ message: t("mcp:oauth.flow.dismissedHint") }) - return - } - - // Guard: another window may have authed while the toast was open - const tokens = await this.secretStorage!.getOAuthData(serverUrl, oauthClientId) - if (disposed) return - if (tokens && Date.now() < tokens.expires_at - TOKEN_EXPIRY_BUFFER_MS) { - cleanup(cancellation.disposable) - try { - await authProvider.close() - await this.deleteConnection(name, source) - const validatedFastPathConfig = this.validateServerConfig(config, name) - await this.connectToServer(name, validatedFastPathConfig, source) - await this.notifyWebviewOfServerChanges() - } catch (error) { - // A reconnect that throws must not leave this flow pending: end the - // flow and surface the error on the server status. - await authProvider.close().catch(() => {}) - const conn = this.findConnection(name, source) - if (conn && conn.server.status !== "connected") { - conn.server.status = "disconnected" - this.appendErrorMessage(conn, error instanceof Error ? error.message : `${error}`) - void this.notifyWebviewOfServerChanges() - } - } - resolve() - return - } - - // Clean up before exchanging tokens — this sets disposed=true so the - // cross-window token watcher doesn't race to reconnect when SecretStorage - // fires onDidChange during token exchange inside _completeOAuthFlow. - cleanup(cancellation.disposable) - try { - await this._completeOAuthFlow(authProvider, transport, connection, name, source, cancellationToken) - } catch { - // _completeOAuthFlow handles its own error state - } - resolve() - })() - }) + }) + }, + (error: unknown) => fail(error instanceof Error ? error.message : String(error), "failed"), + ) + } + return flow.promise.then(() => {}) } private async _completeOAuthFlow( @@ -1475,58 +1431,44 @@ export class McpHub { name: string, source: "global" | "project", cancellationToken: vscode.CancellationToken, - ): Promise { - const config = JSON.parse(connection.server.config) - - // Build a promise that rejects when the progress bar Cancel is pressed, - // so we can race it against waitForAuthCode() which blocks indefinitely. - const cancelledError = new Error(t("mcp:oauth.flow.cancelled")) + ): Promise { + const flow = this.oauthFlows.get(connection) + const canContinue = () => + flow?.phase !== "ended" && + !cancellationToken.isCancellationRequested && + this.isCurrentOAuthConnection(connection) + if (!canContinue()) return false let cancelListener: vscode.Disposable | undefined - const cancellationPromise = new Promise((_, reject) => { - if (cancellationToken.isCancellationRequested) { - reject(cancelledError) - return - } - cancelListener = cancellationToken.onCancellationRequested(() => reject(cancelledError)) + const cancelled = new Promise((_, reject) => { + cancelListener = cancellationToken.onCancellationRequested(() => + reject(new Error(t("mcp:oauth.flow.cancelled"))), + ) }) - try { - // Open the browser now that the user has confirmed the toast. - // redirectToAuthorization() was already called by the SDK (which stored - // the URL in _pendingAuthorizationUrl), but deliberately did not open it. - await authProvider.openBrowser() - - const code = await Promise.race([authProvider.waitForAuthCode(), cancellationPromise]) - - // Exchange auth code for tokens using the pre-fetched token_endpoint - // directly. The SDK's transport.finishAuth() re-runs discovery internally - // and hits the same broken URL for path-prefixed issuers (see - // utils/oauth.ts for upstream issue links). + const authorization = async () => { + await authProvider.openBrowser() + if (!canContinue()) return undefined + return authProvider.waitForAuthCode() + } + const code = await Promise.race([authorization(), cancelled]) + if (!canContinue() || !code) return false await authProvider.exchangeCodeForTokens(code) - await authProvider.close() - - // Recover the validated server config stored on the connection so we - // can pass it directly to connectToServer without re-reading the file. - const validatedConfig = this.validateServerConfig(config, name) - - // Remove the broken connection (closes the old transport/client), - // then reconnect. The new McpOAuthClientProvider will find the token - // in SecretStorage and connect without another OAuth round-trip. - await this.deleteConnection(name, source) - await this.connectToServer(name, validatedConfig, source) - - await this.notifyWebviewOfServerChanges() - void vscode.window.showInformationMessage(t("mcp:oauth.flow.connected", { name })) + if (!canContinue()) return false + const connected = await this.reconnectOAuthConnection( + connection, + JSON.parse(connection.server.config), + flow, + ) + if (connected && flow?.phase !== "ended") + void vscode.window.showInformationMessage(t("mcp:oauth.flow.connected", { name })) + return connected } catch (error) { - await authProvider.close() - const conn = this.findConnection(name, source) - if (conn) { - conn.server.status = "disconnected" - this.appendErrorMessage(conn, error instanceof Error ? error.message : `${error}`) - } - await this.notifyWebviewOfServerChanges() + if (flow?.phase === "ended") return false + await this._surfaceOAuthReconnectFailure(connection, error instanceof Error ? error.message : String(error)) + return false } finally { cancelListener?.dispose() + if (!flow) await authProvider.close() } } @@ -1706,63 +1648,37 @@ export class McpHub { } } - /** - * Shared removal path for an OAuth watcher: ends the flow the watcher - * belongs to. deleteConnection(), flow replacement in _runOAuthFlow(), and - * dispose() must all go through this so a removed watcher never leaves its - * flow pending. The flow's own cleanup unsubscribes and clears the timeout, - * so each listener still runs exactly once. - * - * @returns true when a watcher was registered under this key. - */ - private _endOAuthWatcher(watcherKey: string): boolean { - const watcher = this._oauthWatchers.get(watcherKey) - if (!watcher) return false - // Remove first so the ended flow's cleanup cannot see this entry again, - // and so it can never remove a newer flow's watcher under this key. - this._oauthWatchers.delete(watcherKey) - watcher.endFlow() - return true - } - - async deleteConnection(name: string, source?: "global" | "project"): Promise { - // Cancel any active OAuth flow for this connection. The shared path also - // ends the flow, so tool calls waiting on it are released immediately. - this._endOAuthWatcher(`${name}:${source}`) - - // Clean up file watchers for this server + async deleteConnection(name: string, source?: "global" | "project", preservedFlow?: McpOAuthFlow): Promise { + for (const [connection, flow] of this.oauthFlows) { + if ( + connection.server.name === name && + (!source || connection.server.source === source) && + flow !== preservedFlow + ) + flow.finish("removed") + } this.removeFileWatchersForServer(name) - - // If source is provided, only delete connections from that source - const connections = source - ? this.connections.filter((conn) => conn.server.name === name && conn.server.source === source) - : this.connections.filter((conn) => conn.server.name === name) - + const connections = this.connections.filter( + (connection) => connection.server.name === name && (!source || connection.server.source === source), + ) + for (const serverSource of source ? [source] : ["global", "project"]) { + const key = `${name}:${serverSource}` + this.connectionRemovals.set(key, (this.connectionRemovals.get(key) ?? 0) + 1) + } + // Detach before cleanup yields. Identity checks now reject every closing connection. + this.connections = this.connections.filter((connection) => !connections.includes(connection)) + if (!this.connections.some((connection) => connection.server.name === name)) + this.sanitizedNameRegistry.delete(sanitizeMcpName(name)) for (const connection of connections) { + if (connection.type !== "connected") continue try { - if (connection.type === "connected") { - await connection.transport.close() - await connection.client.close() - await connection.authProvider?.close() - } + await connection.transport.close() + await connection.client.close() + await connection.authProvider?.close() } catch (error) { console.error(`Failed to close transport or auth provider for ${name}:`, error) } } - - // Remove the connections from the array - this.connections = this.connections.filter((conn) => { - if (conn.server.name !== name) return true - if (source && conn.server.source !== source) return true - return false - }) - - // Remove from sanitized name registry if no more connections with this name exist - const remainingConnections = this.connections.filter((conn) => conn.server.name === name) - if (remainingConnections.length === 0) { - const sanitizedName = sanitizeMcpName(name) - this.sanitizedNameRegistry.delete(sanitizedName) - } } async updateServerConnections( @@ -2095,8 +2011,16 @@ export class McpHub { } const serverSource = connection.server.source || "global" - // Update the server config in the appropriate file - await this.updateServerConfig(serverName, { disabled }, serverSource) + // Block OAuth continuations while the disabled setting is saved. + const wasDisabled = connection.server.disabled + if (disabled) connection.server.disabled = true + try { + await this.updateServerConfig(serverName, { disabled }, serverSource) + } catch (error) { + connection.server.disabled = wasDisabled + throw error + } + if (this.findConnection(serverName, serverSource) !== connection) return // Update the connection object if (connection) { @@ -2104,7 +2028,7 @@ export class McpHub { connection.server.disabled = disabled // If disabling a connected server, disconnect it - if (disabled && connection.server.status === "connected") { + if (disabled && connection.server.status !== "disconnected") { // Clean up file watchers when disabling this.removeFileWatchersForServer(serverName) await this.deleteConnection(serverName, serverSource) @@ -2427,32 +2351,26 @@ export class McpHub { // Mid-session re-auth triggered by a tool call (401) connection.server.status = "connecting" - // Key the re-auth flow by the connection itself, not the server name. - // A key shared across connections lets an old flow swallow the 401 of a - // newer connection, and a tool call would wait on the wrong flow. - const reauthKey = connection - let reauthPromise = this.reauthPromises.get(reauthKey) - - if (!reauthPromise) { - reauthPromise = this._initiateOAuthFlow( - serverName, - source || connection.server.source || "global", - JSON.parse(connection.server.config), - connection.authProvider, - connection.transport as StreamableHTTPClientTransport, - connection, - ).finally(() => { - this.reauthPromises.delete(reauthKey) - }) - this.reauthPromises.set(reauthKey, reauthPromise) - } - - await reauthPromise + const outcome = await this._initiateOAuthFlow( + serverName, + source ?? connection.server.source ?? "global", + JSON.parse(connection.server.config), + connection.authProvider, + connection.transport as StreamableHTTPClientTransport, + connection, + ) // After re-auth completes, the connection has been replaced. // We need to find the new connection and retry the tool call. - const newConnection = this.findConnection(serverName, source) - if (!newConnection || newConnection.type !== "connected") { + const newConnection = this.findConnection(serverName, source ?? connection.server.source) + if ( + outcome !== "connected" || + !newConnection || + newConnection === connection || + newConnection.type !== "connected" || + newConnection.server.status !== "connected" || + !this.isCurrentOAuthConnection(newConnection) + ) { throw new Error(`Failed to reconnect to server ${serverName} after OAuth`) } @@ -2685,12 +2603,7 @@ export class McpHub { this.isProgrammaticUpdate = false - // End all active OAuth flows and in-flight reauth promises through the - // shared removal path, so nothing stays pending after disposal. - for (const watcherKey of [...this._oauthWatchers.keys()]) { - this._endOAuthWatcher(watcherKey) - } - this.reauthPromises.clear() + for (const flow of this.oauthFlows.values()) flow.finish("removed") this.oauthTokenRetries.clear() this.removeAllFileWatchers() diff --git a/src/services/mcp/McpOAuthClientProvider.ts b/src/services/mcp/McpOAuthClientProvider.ts index be79d744076..e1c4bc5d6d6 100644 --- a/src/services/mcp/McpOAuthClientProvider.ts +++ b/src/services/mcp/McpOAuthClientProvider.ts @@ -347,6 +347,8 @@ export class McpOAuthClientProvider implements OAuthClientProvider { // through DCR, so start the listener here too. redirectUrl then carries // the active port instead of 0, and redirectToAuthorization() keeps the // authorization URL's redirect_uri in sync with that port. + // Preserve the cached client even if the callback listener cannot bind. + this._clientInfo = cachedData.client_info await this._ensureCallbackServer() // Use the full DCR response, override redirect_uris with the // current port (which may have changed between sessions). @@ -458,11 +460,8 @@ export class McpOAuthClientProvider implements OAuthClientProvider { // openBrowser(), which McpHub calls only after the user confirms the toast. await this._ensureCallbackServer() - // The SDK built this URL before the listener started, so it can carry - // port 0 (a cached client returns early from registerClientIfNeeded() - // and never starts the listener there). Override redirect_uri now that - // the listener owns its final port. This covers the first connect and - // a later 401. + // The listener can restart after the SDK builds this URL. Use its active port. + // Cached registration also starts the listener before authorization. authorizationUrl.searchParams.set("redirect_uri", this.redirectUrl) // Workaround for SDK metadata discovery bug (see utils/oauth.ts for issue links). diff --git a/src/services/mcp/McpOAuthFlow.ts b/src/services/mcp/McpOAuthFlow.ts new file mode 100644 index 00000000000..367afbfa4cb --- /dev/null +++ b/src/services/mcp/McpOAuthFlow.ts @@ -0,0 +1,83 @@ +export type McpOAuthFlowOutcome = "connected" | "cancelled" | "timed-out" | "removed" | "failed" + +type McpOAuthFlowPhase = "waiting" | "authenticating" | "reconnecting" | "ended" + +/** Owns one OAuth attempt, including its listeners and completion promise. */ +export class McpOAuthFlow { + private currentPhase: McpOAuthFlowPhase = "waiting" + private waitingTimeout?: ReturnType + get phase(): McpOAuthFlowPhase { + return this.currentPhase + } + readonly promise: Promise + private readonly cancellation = new AbortController() + get signal(): AbortSignal { + return this.cancellation.signal + } + private resolve!: (outcome: McpOAuthFlowOutcome) => void + private readonly cleanups: Array<() => void> = [] + + constructor() { + this.promise = new Promise((resolve) => { + this.resolve = resolve + }) + } + + addCleanup(cleanup: () => void): () => void { + let active = true + const dispose = () => { + if (!active) return + active = false + const index = this.cleanups.indexOf(dispose) + if (index !== -1) this.cleanups.splice(index, 1) + cleanup() + } + if (this.phase === "ended") dispose() + else this.cleanups.push(dispose) + return dispose + } + + setWaitingTimeout(onTimeout: () => void, milliseconds: number): void { + this.clearWaitingTimeout() + if (this.phase !== "waiting") return + this.waitingTimeout = setTimeout(() => { + this.waitingTimeout = undefined + if (this.phase === "waiting") onTimeout() + }, milliseconds) + } + + private clearWaitingTimeout(): void { + clearTimeout(this.waitingTimeout) + this.waitingTimeout = undefined + } + + private transitionTo(phase: Exclude): boolean { + if (this.phase === "ended") return false + this.clearWaitingTimeout() + this.currentPhase = phase + return true + } + + beginReconnect(): void { + this.transitionTo("reconnecting") + } + + claim(): boolean { + if (this.phase !== "waiting") return false + return this.transitionTo("authenticating") + } + + finish(outcome: McpOAuthFlowOutcome): void { + if (!this.transitionTo("ended")) return + if (outcome === "cancelled" || outcome === "timed-out" || outcome === "removed") + this.cancellation.abort(outcome) + for (const cleanup of this.cleanups.splice(0).reverse()) { + try { + cleanup() + } catch (error) { + console.error("[McpHub] OAuth flow cleanup failed:", error) + } + } + this.resolve(outcome) + } +} diff --git a/src/services/mcp/__tests__/McpHub.spec.ts b/src/services/mcp/__tests__/McpHub.spec.ts index d7b6ab36238..66c61180226 100644 --- a/src/services/mcp/__tests__/McpHub.spec.ts +++ b/src/services/mcp/__tests__/McpHub.spec.ts @@ -11,6 +11,7 @@ import type { SecretStorageService } from "../SecretStorageService" import type { McpHub as McpHubType, McpConnection, ConnectedMcpConnection, DisconnectedMcpConnection } from "../McpHub" import { ServerConfigSchema, McpHub } from "../McpHub" +import { McpOAuthFlow } from "../McpOAuthFlow" import { McpOAuthClientProvider } from "../McpOAuthClientProvider" import { OAUTH_FLOW_TIMEOUT_MS, OAUTH_TOKEN_RETRY_MAX_ATTEMPTS } from "../constants" import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js" @@ -570,10 +571,11 @@ describe("McpHub", () => { typeof vi.fn > let resolveProvider!: (provider: McpOAuthClientProvider) => void - vi.mocked(McpOAuthClientProvider.create).mockReturnValueOnce( - new Promise((resolve) => { - resolveProvider = resolve - }), + vi.mocked(McpOAuthClientProvider.create).mockImplementationOnce( + () => + new Promise((resolve) => { + resolveProvider = resolve + }), ) const mockAuthProvider = { registerClientIfNeeded: vi.fn(), @@ -594,14 +596,17 @@ describe("McpHub", () => { }), ) + vi.mocked(StreamableHTTPClientTransport).mockClear() + vi.mocked(fs.access).mockRejectedValue(new Error("no project config")) const hub = new McpHub(mockProvider as ClineProvider, secretStorage) - await Promise.resolve() + await vi.waitFor(() => expect(resolveProvider).toBeTypeOf("function")) await hub.dispose() resolveProvider(mockAuthProvider) await hub.waitUntilReady() expect(mockAuthProvider.close).toHaveBeenCalledTimes(1) expect(StreamableHTTPClientTransport).not.toHaveBeenCalled() + vi.mocked(fs.access).mockResolvedValue(undefined) }) }) @@ -2901,10 +2906,15 @@ describe("McpHub", () => { close: vi.fn().mockResolvedValue(undefined), } - mockTransport = {} + mockTransport = { close: vi.fn().mockResolvedValue(undefined) } mockConnection = { + client: { close: vi.fn().mockResolvedValue(undefined) }, + transport: mockTransport, + authProvider: mockAuthProvider, + type: "connected", server: { + source, status: "connecting", config: JSON.stringify(config), name: serverName, @@ -2917,10 +2927,13 @@ describe("McpHub", () => { } ;(mcpHub as any).secretStorage = mockSecretStorage - vi.spyOn(mcpHub as any, "deleteConnection").mockResolvedValue(undefined) - vi.spyOn(mcpHub as any, "connectToServer").mockResolvedValue(undefined) + mcpHub.connections = [mockConnection] + vi.spyOn(mcpHub, "deleteConnection") + vi.spyOn(mcpHub as any, "connectToServer").mockImplementation(async () => { + mcpHub.connections = [{ ...mockConnection, server: { ...mockConnection.server, status: "connected" } }] + }) vi.spyOn(mcpHub as any, "notifyWebviewOfServerChanges").mockResolvedValue(undefined) - vi.spyOn(mcpHub as any, "findConnection").mockReturnValue(mockConnection) + vi.spyOn(mcpHub as any, "findConnection") vi.spyOn(mcpHub as any, "validateServerConfig").mockReturnValue(config) vi.spyOn(mcpHub as any, "appendErrorMessage").mockReturnValue(undefined) }) @@ -3009,7 +3022,7 @@ describe("McpHub", () => { ) expect(mockAuthProvider.close).toHaveBeenCalled() - expect((mcpHub as any).deleteConnection).toHaveBeenCalledWith(serverName, source) + expect((mcpHub as any).deleteConnection).toHaveBeenCalledWith(serverName, source, expect.any(McpOAuthFlow)) expect((mcpHub as any).connectToServer).toHaveBeenCalled() }) @@ -3029,7 +3042,7 @@ describe("McpHub", () => { expect(vsc.window.withProgress).not.toHaveBeenCalled() expect(mockAuthProvider.close).toHaveBeenCalled() - expect((mcpHub as any).deleteConnection).toHaveBeenCalledWith(serverName, source) + expect((mcpHub as any).deleteConnection).toHaveBeenCalledWith(serverName, source, expect.any(McpOAuthFlow)) expect((mcpHub as any).connectToServer).toHaveBeenCalled() }) @@ -3102,20 +3115,18 @@ describe("McpHub", () => { mockTransport, mockConnection, ), - ).resolves.toBeUndefined() + ).resolves.toBe("cancelled") expect(mockConnection.server.status).toBe("disconnected") expect((mcpHub as any).appendErrorMessage).toHaveBeenCalled() expect(mockAuthProvider.close).toHaveBeenCalled() - // Pin the watcher-after-cleanup race: when the cancellation callback fires - // synchronously during onCancellationRequested(...) registration, cleanup() - // runs before the _oauthWatchers.set() that would have added the entry. + // A listener returned after synchronous cancellation must be disposed immediately. // If the registration happens AFTER the callback is installed, the entry // is added after disposal and remains orphaned in the map. Registering the // watcher BEFORE installing the callback ensures cleanup() finds and // deletes it cleanly. - expect((mcpHub as any)._oauthWatchers.has(`${serverName}:${source}`)).toBe(false) + expect((mcpHub as any).oauthFlows.has(mockConnection)).toBe(false) }) it("should disconnect and flag error when OAuth flow times out", async () => { @@ -3141,6 +3152,43 @@ describe("McpHub", () => { expect(mockAuthProvider.close).toHaveBeenCalled() }) + it("clears the approval timer when Authenticate is clicked late", async () => { + vi.useFakeTimers() + let approve!: (choice: string) => void + let code!: (value: string) => void + vsc.window.showInformationMessage.mockImplementationOnce( + () => + new Promise((resolve) => { + approve = resolve + }), + ) + mockAuthProvider.waitForAuthCode.mockImplementationOnce( + () => + new Promise((resolve) => { + code = resolve + }), + ) + const result = mcpHub["_initiateOAuthFlow"]( + serverName, + source, + config, + mockAuthProvider, + mockTransport, + mockConnection, + ) + try { + await vi.advanceTimersByTimeAsync(OAUTH_FLOW_TIMEOUT_MS - 1000) + approve(t("mcp:oauth.flow.authenticateButton")) + await vi.advanceTimersByTimeAsync(0) + await vi.advanceTimersByTimeAsync(1001) + expect(mcpHub["oauthFlows"].get(mockConnection)?.phase).toBe("authenticating") + expect(mockConnection.server.status).toBe("connecting") + } finally { + code("late-code") + await result + } + }) + it("should dispose the cancellation listener when the OAuth flow times out", async () => { vi.useFakeTimers() const mockDispose = vi.fn() @@ -3192,7 +3240,7 @@ describe("McpHub", () => { expect(completeOAuthSpy).not.toHaveBeenCalled() expect(mockAuthProvider.close).toHaveBeenCalled() - expect((mcpHub as any).deleteConnection).toHaveBeenCalledWith(serverName, source) + expect((mcpHub as any).deleteConnection).toHaveBeenCalledWith(serverName, source, expect.any(McpOAuthFlow)) expect((mcpHub as any).connectToServer).toHaveBeenCalled() }) @@ -3209,7 +3257,7 @@ describe("McpHub", () => { mockTransport, mockConnection, ), - ).resolves.toBeUndefined() + ).resolves.toBe("failed") }) it("should record the callback error and disconnect when waitForAuthCode rejects", async () => { @@ -3415,19 +3463,15 @@ describe("McpHub", () => { await flowPromise expect(mockAuthProvider.close).toHaveBeenCalled() - expect((mcpHub as any).deleteConnection).toHaveBeenCalledWith(serverName, source) + expect((mcpHub as any).deleteConnection).toHaveBeenCalledWith(serverName, source, expect.any(McpOAuthFlow)) expect((mcpHub as any).connectToServer).toHaveBeenCalled() expect(vsc.window.withProgress).not.toHaveBeenCalled() }) - it("should cancel the previous watcher when called again for the same server", async () => { + it("joins repeated OAuth requests on the same connection", async () => { vi.useFakeTimers() - vsc.window.showInformationMessage.mockImplementation(() => { - return new Promise(() => {}) - }) - - // Start first flow (intentionally not awaited — the second call orphans it) - ;(mcpHub as any)._initiateOAuthFlow( + vsc.window.showInformationMessage.mockImplementation(() => new Promise(() => {})) + const first = mcpHub["_initiateOAuthFlow"]( serverName, source, config, @@ -3435,15 +3479,10 @@ describe("McpHub", () => { mockTransport, mockConnection, ) - - // Flush microtasks: getOAuthData resolves, then withProgress fires synchronously - // (registering the watcher) — no tick-counting needed. await vi.advanceTimersByTimeAsync(0) - expect((mcpHub as any)._oauthWatchers.size).toBe(1) - const firstEntry = (mcpHub as any)._oauthWatchers.get(`${serverName}:${source}`) - - // Start second flow for the same server — should tear down the first watcher - const secondFlow = (mcpHub as any)._initiateOAuthFlow( + const flow = mcpHub["oauthFlows"].get(mockConnection) + const subscriptions = mockSecretStorage.onDidChange.mock.calls.length + const second = mcpHub["_initiateOAuthFlow"]( serverName, source, config, @@ -3451,24 +3490,17 @@ describe("McpHub", () => { mockTransport, mockConnection, ) - await vi.advanceTimersByTimeAsync(0) - // Still exactly one watcher for this server key - expect((mcpHub as any)._oauthWatchers.size).toBe(1) - // The first watcher's unsubscribe must have been called before replacement - expect(firstEntry.unsubscribe).toHaveBeenCalledOnce() - // Watcher entry was replaced (second flow's entry, not first) - const secondEntry = (mcpHub as any)._oauthWatchers.get(`${serverName}:${source}`) - expect(secondEntry).not.toBe(firstEntry) - - // Advance past timeout so the second flow resolves + expect(mcpHub["oauthFlows"].get(mockConnection)).toBe(flow) + expect(mockSecretStorage.onDidChange).toHaveBeenCalledTimes(subscriptions) await vi.advanceTimersByTimeAsync(OAUTH_FLOW_TIMEOUT_MS) - await secondFlow + await Promise.all([first, second]) + expect(mcpHub["oauthFlows"].size).toBe(0) }) - it("keeps the newer flow's watcher when the replaced flow's toast resolves later", async () => { + it("keeps a replacement flow when an old toast resolves", async () => { vi.useFakeTimers() - let resolveFirstToast: (choice?: string) => void + let resolveFirstToast!: (choice?: string) => void vsc.window.showInformationMessage.mockImplementationOnce( () => new Promise((resolve) => { @@ -3476,50 +3508,42 @@ describe("McpHub", () => { }), ) vsc.window.showInformationMessage.mockImplementation(() => new Promise(() => {})) - - const hub = mcpHub as unknown as { - _oauthWatchers: Map - _initiateOAuthFlow: ( - name: string, - source: "global" | "project", - config: unknown, - authProvider: unknown, - transport: unknown, - connection: unknown, - ) => Promise - } - const watcherKey = `${serverName}:${source}` - - const firstFlow = hub._initiateOAuthFlow(serverName, source, config, mockAuthProvider, {}, mockConnection) + const first = mcpHub["_initiateOAuthFlow"]( + serverName, + source, + config, + mockAuthProvider, + mockTransport, + mockConnection, + ) await vi.advanceTimersByTimeAsync(0) - const firstEntry = hub._oauthWatchers.get(watcherKey) - - const secondFlow = hub._initiateOAuthFlow(serverName, source, config, mockAuthProvider, {}, mockConnection) + const replacement = { ...mockConnection, server: { ...mockConnection.server } } + vi.mocked(mcpHub["findConnection"]).mockReturnValue(replacement) + const second = mcpHub["_initiateOAuthFlow"]( + serverName, + source, + config, + mockAuthProvider, + mockTransport, + replacement, + ) await vi.advanceTimersByTimeAsync(0) - const secondEntry = hub._oauthWatchers.get(watcherKey) - expect(secondEntry).toBeDefined() - expect(secondEntry).not.toBe(firstEntry) - - // The stale toast resolves with Authenticate. The replaced flow is already - // disposed, so it must neither reconnect nor touch the newer flow's watcher. - resolveFirstToast!(t("mcp:oauth.flow.authenticateButton")) + const currentFlow = mcpHub["oauthFlows"].get(replacement) + resolveFirstToast(t("mcp:oauth.flow.authenticateButton")) await vi.advanceTimersByTimeAsync(0) - await firstFlow - - // The newer flow still owns the watcher: its unsubscribe never ran. - expect(secondEntry?.unsubscribe).not.toHaveBeenCalled() - expect(hub._oauthWatchers.get(watcherKey)).toBe(secondEntry) - - // The newer flow still ends through its own timeout. + await first + expect(currentFlow?.phase).toBe("waiting") + expect(mcpHub["oauthFlows"].get(replacement)).toBe(currentFlow) + expect(mcpHub["connectToServer"]).not.toHaveBeenCalled() await vi.advanceTimersByTimeAsync(OAUTH_FLOW_TIMEOUT_MS) - await secondFlow - expect(hub._oauthWatchers.size).toBe(0) + await second + expect(mcpHub["oauthFlows"].size).toBe(0) }) it("ends the flow and surfaces the error when the token-watcher reconnect throws", async () => { vi.useFakeTimers() const hub = mcpHub as unknown as { - _oauthWatchers: Map + oauthFlows: Map _initiateOAuthFlow: ( name: string, source: "global" | "project", @@ -3533,7 +3557,15 @@ describe("McpHub", () => { } const closeMock = vi.fn().mockResolvedValue(undefined) mockAuthProvider.close = closeMock - hub.connectToServer.mockRejectedValue(new Error("reconnect failed")) + hub.connectToServer.mockImplementation(async () => { + mcpHub.connections = [ + { + ...mockConnection, + server: { ...mockConnection.server, status: "disconnected", error: "reconnect failed" }, + }, + ] + throw new Error("reconnect failed") + }) // Two subscriptions happen: the cross-window pre-read watcher in // _initiateOAuthFlow stays silent; the flow watcher delivers valid tokens. let subscriptions = 0 @@ -3550,10 +3582,11 @@ describe("McpHub", () => { // Must resolve through the catch path instead of staying pending forever. await hub._initiateOAuthFlow(serverName, source, config, mockAuthProvider, {}, mockConnection) - expect(mockConnection.server.status).toBe("disconnected") - expect(hub.appendErrorMessage).toHaveBeenCalledWith(mockConnection, "reconnect failed") + expect(mcpHub.connections[0]?.server.status).toBe("disconnected") + expect(mcpHub.connections[0]?.server.error).toBe("reconnect failed") + expect(hub.appendErrorMessage).not.toHaveBeenCalledWith(mockConnection, "reconnect failed") expect(closeMock).toHaveBeenCalled() - expect(hub._oauthWatchers.size).toBe(0) + expect(hub.oauthFlows.size).toBe(0) }) it("ends the flow and surfaces the error when the Authenticate fast-path reconnect throws", async () => { @@ -3562,7 +3595,7 @@ describe("McpHub", () => { .mockResolvedValueOnce(undefined) // no tokens before the flow starts .mockResolvedValue({ expires_at: Date.now() + 10 * 60 * 1000 }) // tokens at click time const hub = mcpHub as unknown as { - _oauthWatchers: Map + oauthFlows: Map _initiateOAuthFlow: ( name: string, source: "global" | "project", @@ -3574,13 +3607,22 @@ describe("McpHub", () => { appendErrorMessage: Mock & ((connection: unknown, message: string) => void) connectToServer: Mock & ((...args: unknown[]) => Promise) } - hub.connectToServer.mockRejectedValue(new Error("fast reconnect failed")) + hub.connectToServer.mockImplementation(async () => { + mcpHub.connections = [ + { + ...mockConnection, + server: { ...mockConnection.server, status: "disconnected", error: "fast reconnect failed" }, + }, + ] + throw new Error("fast reconnect failed") + }) await hub._initiateOAuthFlow(serverName, source, config, mockAuthProvider, {}, mockConnection) - expect(mockConnection.server.status).toBe("disconnected") - expect(hub.appendErrorMessage).toHaveBeenCalledWith(mockConnection, "fast reconnect failed") - expect(hub._oauthWatchers.size).toBe(0) + expect(mcpHub.connections[0]?.server.status).toBe("disconnected") + expect(mcpHub.connections[0]?.server.error).toBe("fast reconnect failed") + expect(hub.appendErrorMessage).not.toHaveBeenCalledWith(mockConnection, "fast reconnect failed") + expect(hub.oauthFlows.size).toBe(0) }) it("does not wait for an ended flow when a tool call hits a 401", async () => { @@ -3602,7 +3644,7 @@ describe("McpHub", () => { vi.mocked(mcpHub["deleteConnection"]).mockRestore() const hub = mcpHub as unknown as { - _oauthWatchers: Map + oauthFlows: Map callTool: typeof mcpHub.callTool deleteConnection: (name: string, source?: "global" | "project") => Promise } @@ -3610,7 +3652,7 @@ describe("McpHub", () => { const callPromise = mcpHub.callTool(serverName, "some-tool", {}, source) await vi.advanceTimersByTimeAsync(0) // The 401 started a real OAuth flow and the tool call is waiting on it. - expect(hub._oauthWatchers.size).toBe(1) + expect(hub.oauthFlows.size).toBe(1) expect(requestMock).toHaveBeenCalledTimes(1) // Deleting the connection ends the flow through the shared removal path. @@ -3623,7 +3665,7 @@ describe("McpHub", () => { // The tool call must fail fast, not wait for the 5-minute flow timeout. await callAssertion - expect(hub._oauthWatchers.size).toBe(0) + expect(hub.oauthFlows.size).toBe(0) }) }) @@ -3637,7 +3679,10 @@ describe("McpHub", () => { * SecretStorage never expires, so each 401 drives the automatic reconnect * path exactly like the issue's fake-server reproduction did. */ - async function setupRejectingServer(rejectCount: number): Promise<{ connectCount: () => number }> { + async function setupRejectingServer( + rejectCount: number, + hasMetadata = true, + ): Promise<{ connectCount: () => number }> { let connectCount = 0 const connect = vi.fn(async () => { connectCount += 1 @@ -3659,7 +3704,7 @@ describe("McpHub", () => { } as unknown as Client }) const authProvider = { - hasMetadata: true, + hasMetadata, registerClientIfNeeded: vi.fn().mockResolvedValue(undefined), close: vi.fn().mockResolvedValue(undefined), } @@ -3714,8 +3759,8 @@ describe("McpHub", () => { } }) - it("bounds the reconnect attempts and ends with a visible error for an always-rejecting server", async () => { - const { connectCount } = await setupRejectingServer(Number.POSITIVE_INFINITY) + it.each([true, false])("bounds rejected-token retries after discovery (metadata=%s)", async (hasMetadata) => { + const { connectCount } = await setupRejectingServer(Number.POSITIVE_INFINITY, hasMetadata) const hub = await createHubWithSavedToken() try { await vi.waitFor(() => { @@ -3734,6 +3779,134 @@ describe("McpHub", () => { } }) + it("records stdio errors while the process is connecting", async () => { + await setupRejectingServer(0) + const hub = await createHubWithSavedToken() + const stdio = await import("@modelcontextprotocol/sdk/client/stdio.js") + vi.mocked(stdio.StdioClientTransport).mockImplementation(function () { + // The transport double supplies process startup, close, and the absent stderr stream. + return { + start: vi.fn().mockResolvedValue(undefined), + close: vi.fn().mockResolvedValue(undefined), + stderr: null, + } as unknown as InstanceType + }) + try { + await hub["connectToServer"]( + "stdio-errors", + ServerConfigSchema.parse({ type: "stdio", command: "node" }), + "global", + ) + const connection = hub.connections.find((entry) => entry.server.name === "stdio-errors") + if (!connection || connection.type !== "connected") throw new Error("Missing stdio connection") + connection.server.status = "connecting" + await connection.transport.onerror?.(new Error("stdio startup failed")) + expect(connection.server.status).toBe("disconnected") + expect(connection.server.error).toContain("stdio startup failed") + } finally { + await hub.dispose() + } + }) + + it.each(["401", "generic"])("ignores a %s error from an old HTTP transport", async (kind) => { + await setupRejectingServer(0) + const hub = await createHubWithSavedToken() + try { + const old = hub.connections[0] + if (!old || old.type !== "connected") throw new Error("Missing old connection") + await hub["connectToServer"]( + serverName, + hub["validateServerConfig"](JSON.parse(old.server.config), serverName), + "global", + ) + const replacement = hub.connections[0] + const before = structuredClone(replacement?.server) + const error = kind === "401" ? new UnauthorizedError() : new Error("late HTTP failure") + await old.transport.onerror?.(error) + expect(replacement?.server).toEqual(before) + expect(hub["oauthFlows"].size).toBe(0) + } finally { + await hub.dispose() + } + }) + + it.each(["connecting", "connected"] as const)( + "handles a current generic HTTP error while %s", + async (status) => { + await setupRejectingServer(0) + const hub = await createHubWithSavedToken() + try { + const connection = hub.connections[0] + if (!connection || connection.type !== "connected") throw new Error("Missing connection") + connection.server.status = status + await connection.transport.onerror?.(new Error("current HTTP failure")) + expect(connection.server.status).toBe(status === "connecting" ? "connecting" : "disconnected") + if (status === "connecting") expect(connection.server.error).not.toContain("current HTTP failure") + else expect(connection.server.error).toContain("current HTTP failure") + } finally { + await hub.dispose() + } + }, + ) + + it("starts a new transport re-auth flow for a replacement connection", async () => { + await setupRejectingServer(0) + const hub = await createHubWithSavedToken() + const releases: Array<() => void> = [] + const initiate = vi.fn<(typeof hub)["performOAuthFlow"]>( + () => new Promise((resolve) => releases.push(resolve)), + ) + hub["performOAuthFlow"] = initiate + try { + const first = hub.connections[0] + if (!first || first.type !== "connected") throw new Error("Missing first connection") + first.transport.onerror?.(new UnauthorizedError()) + await hub["connectToServer"]( + serverName, + hub["validateServerConfig"](JSON.parse(first.server.config), serverName), + "global", + ) + const second = hub.connections[0] + if (!second || second.type !== "connected") throw new Error("Missing replacement connection") + expect(second).not.toBe(first) + second.transport.onerror?.(new UnauthorizedError()) + expect(initiate).toHaveBeenCalledTimes(2) + expect(hub["oauthFlows"].size).toBe(1) + } finally { + for (const release of releases) release() + await Promise.all([...hub["oauthFlows"].values()].map((flow) => flow.promise)) + await hub.dispose() + } + }) + + it("does not reset the rejected-token budget when initialize succeeds", async () => { + const { connectCount } = await setupRejectingServer(0) + const hub = await createHubWithSavedToken() + try { + for (let attempt = 0; attempt <= OAUTH_TOKEN_RETRY_MAX_ATTEMPTS; attempt++) { + const connection = hub.connections.find((entry) => entry.server.name === serverName) + if (!connection || connection.type !== "connected" || !connection.authProvider) + throw new Error("Missing connection") + connection.server.status = "connecting" + await hub["_initiateOAuthFlow"]( + serverName, + "global", + hub["validateServerConfig"](JSON.parse(connection.server.config), serverName), + connection.authProvider, + connection.transport as StreamableHTTPClientTransport, + connection, + ) + } + expect(connectCount()).toBe(1 + OAUTH_TOKEN_RETRY_MAX_ATTEMPTS) + expect(hub.connections[0]?.server.status).toBe("disconnected") + expect(hub.connections[0]?.server.error).toBe( + t("mcp:oauth.flow.retriesExhausted", { name: serverName }), + ) + } finally { + await hub.dispose() + } + }) + it("delays each automatic reconnect of the same rejected token", async () => { await setupRejectingServer(Number.POSITIVE_INFINITY) const hub = await createHubWithSavedToken() diff --git a/src/services/mcp/__tests__/McpOAuthClientProvider.spec.ts b/src/services/mcp/__tests__/McpOAuthClientProvider.spec.ts index 6ff1de39ed5..8d3ae5d3c50 100644 --- a/src/services/mcp/__tests__/McpOAuthClientProvider.spec.ts +++ b/src/services/mcp/__tests__/McpOAuthClientProvider.spec.ts @@ -1794,6 +1794,22 @@ describe("McpOAuthClientProvider", () => { await provider.close() }) + it("keeps cached registration when the callback listener cannot bind", async () => { + mockOAuthDiscovery() + const storage = createMockSecretStorage() + await storage.saveOAuthData("https://example.com/mcp", { + tokens: { access_token: "saved", token_type: "Bearer" }, + expires_at: Date.now() + 600_000, + issuer: "https://auth.example.com", + client_info: { client_id: "cached-client", redirect_uris: ["http://127.0.0.1:9999/callback"] }, + }) + const provider = await McpOAuthClientProvider.create("https://example.com/mcp", storage) + vi.mocked(startCallbackServer).mockRejectedValueOnce(new Error("listener bind failed")) + await expect(provider.registerClientIfNeeded()).rejects.toThrow("listener bind failed") + expect((await provider.clientInformation())?.client_id).toBe("cached-client") + await provider.close() + }) + it("should reuse cached client_info even when callback server port has changed", async () => { setupCallbackServerMock() const secretStorage = createMockSecretStorage() diff --git a/src/services/mcp/__tests__/McpOAuthFlow.spec.ts b/src/services/mcp/__tests__/McpOAuthFlow.spec.ts new file mode 100644 index 00000000000..a5f6045116b --- /dev/null +++ b/src/services/mcp/__tests__/McpOAuthFlow.spec.ts @@ -0,0 +1,107 @@ +import { McpOAuthFlow, type McpOAuthFlowOutcome } from "../McpOAuthFlow" + +// Invariants: McpOAuthFlowEnd.OneContinuation and NoOrphanFlow. +describe("McpOAuthFlow ownership", () => { + it.each(["connected", "cancelled", "timed-out", "removed", "failed"])( + "one claimant and one completion survive %s", + async (outcome) => { + const flow = new McpOAuthFlow() + const cleanup = vi.fn() + flow.addCleanup(cleanup) + expect(flow.claim()).toBe(true) + expect(flow.claim()).toBe(false) + flow.finish(outcome) + flow.finish("failed") + expect(flow.phase).toBe("ended") + expect(flow.signal.aborted).toBe(["cancelled", "timed-out", "removed"].includes(outcome)) + expect(await flow.promise).toBe(outcome) + expect(cleanup).toHaveBeenCalledOnce() + }, + ) + + // Invariant: McpOAuthFlowEnd.TimerOnlyWhileWaiting also applies to terminal exits. + it.each(["connected", "cancelled", "timed-out", "removed", "failed"])( + "terminal transition %s clears the approval timer and stays ended", + async (outcome) => { + vi.useFakeTimers() + const flow = new McpOAuthFlow() + const expired = vi.fn() + try { + flow.setWaitingTimeout(expired, 300_000) + flow.finish(outcome) + expect(vi.getTimerCount()).toBe(0) + flow.beginReconnect() + expect(flow.claim()).toBe(false) + expect(flow.phase).toBe("ended") + await vi.advanceTimersByTimeAsync(300_000) + expect(expired).not.toHaveBeenCalled() + expect(await flow.promise).toBe(outcome) + } finally { + flow.finish("removed") + vi.useRealTimers() + } + }, + ) + + it.each(["browser", "reconnect"])("approval timer ends before %s work starts", async (step) => { + vi.useFakeTimers() + const flow = new McpOAuthFlow() + const expired = vi.fn() + try { + flow.setWaitingTimeout(expired, 300_000) + await vi.advanceTimersByTimeAsync(299_999) + if (step === "browser") expect(flow.claim()).toBe(true) + else flow.beginReconnect() + expect(vi.getTimerCount()).toBe(0) + await vi.advanceTimersByTimeAsync(300_000) + expect(expired).not.toHaveBeenCalled() + expect(flow.phase).toBe(step === "browser" ? "authenticating" : "reconnecting") + } finally { + flow.finish("removed") + vi.useRealTimers() + } + }) + + it("approval still times out while waiting for the user", async () => { + vi.useFakeTimers() + const flow = new McpOAuthFlow() + try { + flow.setWaitingTimeout(() => flow.finish("timed-out"), 300_000) + await vi.advanceTimersByTimeAsync(300_000) + expect(await flow.promise).toBe("timed-out") + expect(flow.signal.reason).toBe("timed-out") + expect(vi.getTimerCount()).toBe(0) + } finally { + flow.finish("removed") + vi.useRealTimers() + } + }) + + it("disposes a listener returned after synchronous cancellation", async () => { + const flow = new McpOAuthFlow() + const dispose = vi.fn() + // A cancellation registration can invoke its callback before returning its disposable. + flow.finish("cancelled") + flow.addCleanup(dispose) + expect(dispose).toHaveBeenCalledOnce() + expect(await flow.promise).toBe("cancelled") + }) + + it("releases remaining resources and the waiter when a cleanup throws", async () => { + const flow = new McpOAuthFlow() + const cleanup = vi.fn() + const log = vi.spyOn(console, "error").mockImplementation(() => {}) + try { + flow.addCleanup(cleanup) + flow.addCleanup(() => { + throw new Error("listener cleanup failed") + }) + flow.finish("removed") + expect(await flow.promise).toBe("removed") + expect(cleanup).toHaveBeenCalledOnce() + expect(log).toHaveBeenCalledWith("[McpHub] OAuth flow cleanup failed:", expect.any(Error)) + } finally { + log.mockRestore() + } + }) +}) diff --git a/src/services/mcp/__tests__/mcp-oauth-flow.property.spec.ts b/src/services/mcp/__tests__/mcp-oauth-flow.property.spec.ts index 7b2cabddc1a..77e515cba1e 100644 --- a/src/services/mcp/__tests__/mcp-oauth-flow.property.spec.ts +++ b/src/services/mcp/__tests__/mcp-oauth-flow.property.spec.ts @@ -10,10 +10,14 @@ import type { ClineProvider } from "../../../core/webview/ClineProvider" import type { SecretStorageService, StoredMcpOAuthData } from "../SecretStorageService" import type { CallbackResult } from "../utils/callbackServer" -import { McpHub } from "../McpHub" +import delay from "delay" +import type { McpOAuthFlowOutcome } from "../McpOAuthFlow" +import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js" + +import { McpHub, type ConnectedMcpConnection } from "../McpHub" import { McpOAuthClientProvider } from "../McpOAuthClientProvider" -// The module mock above stands in for the McpHub tests. The redirect property +// The provider mock stands in for the McpHub tests. The redirect property // drives the real provider implementation, so it imports the actual module. async function realProvider() { const actual = await vi.importActual("../McpOAuthClientProvider") @@ -187,7 +191,8 @@ const mockFetch = vi.fn() const originalFetch = global.fetch global.fetch = mockFetch -vi.mock("@modelcontextprotocol/sdk/client/auth.js", () => ({ +vi.mock("@modelcontextprotocol/sdk/client/auth.js", async (importOriginal) => ({ + ...(await importOriginal()), discoverOAuthProtectedResourceMetadata: vi.fn().mockResolvedValue({ resource: "", authorization_servers: ["https://auth.example.com"], @@ -236,7 +241,7 @@ const oauthConfig = { type: "streamable-http", url: serverUrl } type TestConnection = { type: "connected" - server: { name: string; config: string; status: string; source?: string } + server: { name: string; config: string; status: string; source?: string; error?: string } client: { request: Mock; close: Mock } transport: { close: Mock } authProvider?: unknown @@ -251,6 +256,7 @@ type FlowHandle = { } type FlowHub = { + callTool: McpHub["callTool"] waitUntilReady: () => Promise _runOAuthFlow: ( name: string, @@ -269,7 +275,7 @@ type FlowHub = { findConnection: Mock validateServerConfig: Mock appendErrorMessage: Mock - _oauthWatchers: Map + oauthFlows: Map connections: TestConnection[] secretStorage: SecretStorageService dispose: () => Promise @@ -286,14 +292,13 @@ async function createFlowHub(): Promise { hub.findConnection = vi.fn(() => hub.connections[0]) hub.validateServerConfig = vi.fn().mockReturnValue(oauthConfig) hub.appendErrorMessage = vi.fn().mockImplementation((connection: TestConnection, message: string) => { - connection.server.status = "disconnected" - void message + connection.server.error = message }) return hub } /** Starts one real _runOAuthFlow with a toast that never resolves. */ -function startFlow(hub: FlowHub): FlowHandle { +function startFlow(hub: FlowHub, tool = false): FlowHandle { const connection: TestConnection = { type: "connected", server: { name: serverName, config: JSON.stringify(oauthConfig), status: "connecting", source: "global" }, @@ -306,18 +311,27 @@ function startFlow(hub: FlowHub): FlowHandle { isCancellationRequested: false, onCancellationRequested: vi.fn(() => ({ dispose: vi.fn() })), } - const flowPromise = hub._runOAuthFlow( - serverName, - "global", - oauthConfig, - serverUrl, - authProvider, - {}, - connection, - { report: vi.fn() }, - cancellationToken, - undefined, - ) + if (tool) { + connection.authProvider = authProvider + connection.client.request.mockRejectedValue(new UnauthorizedError()) + } + const flowPromise = tool + ? hub.callTool(serverName, "tool", {}, "global").then( + () => {}, + () => {}, + ) + : hub._runOAuthFlow( + serverName, + "global", + oauthConfig, + serverUrl, + authProvider, + {}, + connection, + { report: vi.fn() }, + cancellationToken, + undefined, + ) const handle: FlowHandle = { connection, authProvider, @@ -344,6 +358,237 @@ describe("MCP OAuth flow property tests", () => { McpOAuthClientProvider.clearNonOAuthCache() }) + // Invariants: McpConnectionOwnership.NoStaleAccess and ReplacementRetained. + it.each([false, true])("closing registry property: detach before cleanup (replacement=%s)", async (replace) => { + const hub = new McpHub(mockProvider) + await hub.waitUntilReady() + let release!: () => void + const held = new Promise((resolve) => { + release = resolve + }) + const connection: ConnectedMcpConnection = { + type: "connected", + server: { name: serverName, source: "global", config: JSON.stringify(oauthConfig), status: "connected" }, + // These SDK doubles supply only resource cleanup for the removal test. + client: { close: vi.fn().mockResolvedValue(undefined) } as unknown as Client, + transport: { close: vi.fn(() => held) } as unknown as StreamableHTTPClientTransport, + } + hub.connections = [connection] + const removal = hub.deleteConnection(serverName, "global") + try { + expect(hub.connections).not.toContain(connection) + expect(hub["isCurrentOAuthConnection"](connection)).toBe(false) + if (replace) { + const replacement = { ...connection, server: { ...connection.server } } + hub.connections = [replacement] + release() + await removal + expect(hub.connections).toEqual([replacement]) + } + } finally { + release() + await removal + hub.connections = [] + await hub.dispose() + } + }) + + it("ownership property: removal during the panel update cannot report reconnect success", async () => { + const hub = new McpHub(mockProvider) + await hub.waitUntilReady() + let release!: () => void + const held = new Promise((resolve) => { + release = resolve + }) + const original: ConnectedMcpConnection = { + type: "connected", + server: { name: serverName, source: "global", status: "connecting", config: JSON.stringify(oauthConfig) }, + // Only resource cleanup runs on these SDK doubles. + client: { close: vi.fn().mockResolvedValue(undefined) } as unknown as Client, + transport: { close: vi.fn().mockResolvedValue(undefined) } as unknown as StreamableHTTPClientTransport, + } + const replacement: ConnectedMcpConnection = { ...original, server: { ...original.server, status: "connected" } } + hub.connections = [original] + hub["connectToServer"] = vi.fn(async () => { + hub.connections = [replacement] + }) + hub["notifyWebviewOfServerChanges"] = vi.fn(() => held) + const reconnect = hub["reconnectOAuthConnection"]( + original, + hub["validateServerConfig"](oauthConfig, serverName), + ) + try { + await flushPromises() + expect(hub.connections).toEqual([replacement]) + await hub.deleteConnection(serverName, "global") + release() + expect(await reconnect).toBe(false) + } finally { + release() + await reconnect + await hub.dispose() + } + }) + + // Invariant: McpOAuthFlowEnd.NoStaleWrite, PR #2762 findings #1, #2, #3 and #8. + it.each( + ["token-read", "backoff", "browser", "exchange", "close"].flatMap((phase) => + ["accept", "delete", "disable", "replace", "dispose"].map((action) => ({ phase, action })), + ), + )("ownership property: $action during $phase", async ({ phase, action }) => { + const hub = new McpHub(mockProvider) + await hub.waitUntilReady() + let release!: () => void + const held = new Promise((resolve) => { + release = resolve + }) + const saved = { tokens: { access_token: "saved", token_type: "Bearer" }, expires_at: Date.now() + 600_000 } + const storage = createTestSecretStorage(phase === "backoff" ? saved : undefined) + hub["secretStorage"] = storage + const auth = { + openBrowser: vi.fn().mockResolvedValue(undefined), + waitForAuthCode: vi.fn().mockResolvedValue("code"), + exchangeCodeForTokens: vi.fn().mockResolvedValue(undefined), + close: vi.fn().mockResolvedValue(undefined), + } + // The provider double supplies the four methods used by the flow. + const provider = auth as unknown as McpOAuthClientProvider + const connection: ConnectedMcpConnection = { + type: "connected", + server: { name: serverName, source: "global", config: JSON.stringify(oauthConfig), status: "connecting" }, + // These SDK doubles only provide resource cleanup for this ownership test. + client: { close: vi.fn().mockResolvedValue(undefined) } as unknown as Client, + transport: { close: vi.fn().mockResolvedValue(undefined) } as unknown as StreamableHTTPClientTransport, + authProvider: provider, + } + hub.connections = [connection] + const methods = { + connect: hub["connectToServer"].bind(hub), + notify: hub["notifyWebviewOfServerChanges"].bind(hub), + } + const connect = vi.fn(methods.connect).mockResolvedValue(undefined) + hub["connectToServer"] = connect + hub["notifyWebviewOfServerChanges"] = vi.fn(methods.notify).mockResolvedValue(undefined) + const cancellation = { + isCancellationRequested: false, + onCancellationRequested: vi.fn(() => ({ dispose: vi.fn() })), + } + if (phase === "token-read") + vi.mocked(storage.getOAuthData).mockImplementationOnce(async () => { + await held + return saved + }) + if (phase === "backoff") vi.mocked(delay).mockImplementationOnce(() => held) + if (phase === "browser") auth.openBrowser.mockImplementationOnce(() => held) + if (phase === "exchange") auth.exchangeCodeForTokens.mockImplementationOnce(() => held) + if (phase === "close") auth.close.mockImplementationOnce(() => held) + const flow = + phase === "token-read" || phase === "backoff" + ? hub["_initiateOAuthFlow"]( + serverName, + "global", + hub["validateServerConfig"](oauthConfig, serverName), + provider, + connection.transport as StreamableHTTPClientTransport, + connection, + ) + : hub["_completeOAuthFlow"]( + provider, + connection.transport as StreamableHTTPClientTransport, + connection, + serverName, + "global", + cancellation, + ) + await flushPromises() + expect(connect).not.toHaveBeenCalled() + if (action === "delete") await hub.deleteConnection(serverName, "global") + if (action === "disable") connection.server.disabled = true + if (action === "replace") hub.connections = [{ ...connection, server: { ...connection.server } }] + if (action === "dispose") await hub.dispose() + const expected = hub.connections[0] + release() + await flow + expect(connect).toHaveBeenCalledTimes(action === "accept" ? 1 : 0) + if (action === "replace" || action === "disable") expect(hub.connections[0]).toBe(expected) + await hub.dispose() + }) + + // Invariant: McpOAuthFlowEnd.ToolRequiresSuccess. + it.each(["connected", "cancelled", "removed", "failed", "timed-out"])( + "tool retry property: OAuth outcome %s controls the retry", + async (outcome) => { + const hub = new McpHub(mockProvider) + await hub.waitUntilReady() + const retry = vi.fn().mockResolvedValue({ content: [] }) + const connection = (request: Mock): ConnectedMcpConnection => ({ + type: "connected", + server: { + name: serverName, + source: "global", + status: "connected", + config: JSON.stringify(oauthConfig), + }, + // The SDK doubles provide only the request and cleanup operations used here. + client: { request, close: vi.fn().mockResolvedValue(undefined) } as unknown as Client, + transport: { close: vi.fn().mockResolvedValue(undefined) } as unknown as StreamableHTTPClientTransport, + authProvider: { close: vi.fn().mockResolvedValue(undefined) } as unknown as McpOAuthClientProvider, + }) + const original = connection(vi.fn().mockRejectedValue(new UnauthorizedError())) + const replacement = connection(retry) + hub.connections = [original] + hub["_initiateOAuthFlow"] = vi.fn(async () => { + hub.connections = [replacement] + return outcome + }) + const call = hub.callTool(serverName, "tool", {}, "global") + if (outcome === "connected") { + await expect(call).resolves.toEqual({ content: [] }) + expect(retry).toHaveBeenCalledOnce() + } else { + await expect(call).rejects.toThrow("Failed to reconnect") + expect(retry).not.toHaveBeenCalled() + } + await hub.dispose() + }, + ) + + it("a replacement tool connection starts its own re-auth flow", async () => { + const hub = new McpHub(mockProvider) + await hub.waitUntilReady() + const releases: Array<() => void> = [] + const initiate = vi.fn<(typeof hub)["performOAuthFlow"]>( + () => new Promise((resolve) => releases.push(resolve)), + ) + hub["performOAuthFlow"] = initiate + const makeConnection = (): ConnectedMcpConnection => ({ + type: "connected", + server: { name: serverName, source: "global", config: JSON.stringify(oauthConfig), status: "connected" }, + // Only request and close are used by this tool-call scenario. + client: { + request: vi.fn().mockRejectedValue(new UnauthorizedError()), + close: vi.fn().mockResolvedValue(undefined), + } as unknown as Client, + transport: { close: vi.fn().mockResolvedValue(undefined) } as unknown as StreamableHTTPClientTransport, + authProvider: { close: vi.fn().mockResolvedValue(undefined) } as unknown as McpOAuthClientProvider, + }) + const first = makeConnection() + hub.connections = [first] + const firstCall = hub.callTool(serverName, "tool", {}, "global").catch((error: unknown) => error) + await flushPromises() + const replacement = makeConnection() + hub.connections = [replacement] + const secondCall = hub.callTool(serverName, "tool", {}, "global").catch((error: unknown) => error) + await flushPromises() + expect(initiate).toHaveBeenCalledTimes(2) + expect(hub["oauthFlows"].size).toBe(1) + for (const release of releases) release() + expect(await firstCall).toBeInstanceOf(Error) + expect(await secondCall).toBeInstanceOf(Error) + expect(hub["oauthFlows"].size).toBe(0) + await hub.dispose() + }) + // Invariant: McpOAuthRedirectUrl.NoBadOpen. it("redirect property: every opened URL carries the active listener port and never port 0", async () => { const random = makeRandom(20261127) @@ -365,6 +610,8 @@ describe("MCP OAuth flow property tests", () => { queueListener(0) const RealProvider = await realProvider() const provider = await RealProvider.create("https://example.com/mcp", secretStorage) + await provider.registerClientIfNeeded() + if (cached) expect((await provider.clientInformation())?.client_id).toBe("cached-client") // A later 401 round re-auths through a replacement listener. const rounds = 1 + Math.floor(random() * 2) @@ -412,7 +659,7 @@ describe("MCP OAuth flow property tests", () => { toolWaiting = true } // Starting a flow replaces any existing watcher through the shared path. - flows.push(startFlow(hub)) + flows.push(startFlow(hub, action === "tool")) } else if (action === "delete") { await hub.deleteConnection(serverName, "global") } else { @@ -427,10 +674,10 @@ describe("MCP OAuth flow property tests", () => { const unresolved = flows.filter((flow) => !flow.resolved) expect(unresolved.length).toBeLessThanOrEqual(1) // NoOrphanFlow: a pending flow still owns the watcher. - expect(unresolved.length === 1).toBe(hub._oauthWatchers.size === 1) + expect(unresolved.length === 1).toBe(hub.oauthFlows.size === 1) // ToolNotOrphaned: a tool wait is live on a flow or was released by its end. if (toolWaiting) { - expect(hub._oauthWatchers.size === 1 || unresolved.length === 0).toBe(true) + expect(hub.oauthFlows.size === 1 || unresolved.length === 0).toBe(true) } } @@ -445,33 +692,29 @@ describe("MCP OAuth flow property tests", () => { }) // Invariant: McpOAuthFlowEnd.NoErrorLeak. - it("error-leak property: a reconnect error in the token watcher ends the flow", async () => { - const random = makeRandom(987654321) - const histories = 8 - - for (let history = 0; history < histories; history++) { + it.each(["invalid OAuth config", "missing OAuth endpoint", "OAuth reconnect rejected"])( + "error-leak property: %s ends the flow and preserves the error", + async (message) => { const hub = await createFlowHub() const flow = startFlow(hub) - await flushPromises() - expect(hub._oauthWatchers.size).toBe(1) - - // The token watcher fires and the reconnect it triggers throws. - const secretStorage = hub.secretStorage - ;(secretStorage.getOAuthData as Mock).mockResolvedValue({ - expires_at: Date.now() + 10 * 60 * 1000, + hub.validateServerConfig.mockImplementationOnce(() => { + throw new Error(message) }) - const watcherCallbacks = (secretStorage.onDidChange as Mock).mock.calls.map((call) => call[1] as () => void) - expect(watcherCallbacks.length).toBe(1) - watcherCallbacks[0]() - await flushPromises() - await flushPromises() - void random - + vi.mocked(hub.secretStorage.getOAuthData).mockResolvedValue({ + tokens: { access_token: "token", token_type: "Bearer" }, + expires_at: Date.now() + 600_000, + }) + const callbacks = vi.mocked(hub.secretStorage.onDidChange).mock.calls + callbacks[0][1]() + await flow.promise expect(flow.resolved).toBe(true) - expect(hub._oauthWatchers.size).toBe(0) + expect(flow.connection.server.status).toBe("disconnected") + expect(flow.connection.server.error).toBe(message) + expect(flow.authProvider.close).toHaveBeenCalled() + expect(hub.oauthFlows.size).toBe(0) await hub.dispose() - } - }) + }, + ) // Invariant: McpOAuthStatusHandoff.PanelShowsConnected. it("status-handoff property: the panel shows connected before slow lists finish, then updates again", async () => { diff --git a/src/services/mcp/__tests__/mcp-oauth-ownership.integration.spec.ts b/src/services/mcp/__tests__/mcp-oauth-ownership.integration.spec.ts new file mode 100644 index 00000000000..5d907e5de8e --- /dev/null +++ b/src/services/mcp/__tests__/mcp-oauth-ownership.integration.spec.ts @@ -0,0 +1,272 @@ +import nock from "nock" +import { createServer, type ServerResponse } from "node:http" +import { mkdtemp, rm, writeFile } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join } from "node:path" +import * as vscode from "vscode" +import type { ClineProvider } from "../../../core/webview/ClineProvider" +import type { SecretStorageService, StoredMcpOAuthData } from "../SecretStorageService" +import { t } from "../../../i18n" +import { McpHub } from "../McpHub" + +vi.mock("vscode", () => ({ + workspace: { + createFileSystemWatcher: vi.fn(() => ({ + onDidChange: vi.fn(), + onDidCreate: vi.fn(), + onDidDelete: vi.fn(), + dispose: vi.fn(), + })), + onDidSaveTextDocument: vi.fn(), + onDidChangeWorkspaceFolders: vi.fn(), + workspaceFolders: [], + }, + window: { showErrorMessage: vi.fn(), showInformationMessage: vi.fn(), showWarningMessage: vi.fn() }, + env: { openExternal: vi.fn() }, + Uri: { parse: (url: string) => ({ toString: () => url }) }, + Disposable: { from: vi.fn() }, + ProgressLocation: { Notification: 15 }, +})) +vi.mock("../../../core/webview/ClineProvider") +vi.mock("chokidar", () => ({ default: { watch: vi.fn(() => ({ on: vi.fn().mockReturnThis(), close: vi.fn() })) } })) + +function deferred() { + let resolve!: () => void + const promise = new Promise((done) => { + resolve = done + }) + return { promise, resolve } +} + +// Invariant: McpOAuthFlowEnd.NoStaleWrite. The hub, OAuth provider, SDK, and callback listener are real. +describe("OAuth ownership through the HTTP boundary", () => { + beforeEach(() => nock.enableNetConnect(/^(127\.0\.0\.1|localhost)(:|$)/)) + afterEach(() => nock.disableNetConnect()) + it.each( + ["browser", "exchange", "reconnect"].flatMap((phase) => + [ + "accept", + "delete", + "disable", + "dispose", + "cancel", + ...(phase === "reconnect" ? ["timeout", "cancel-delete"] : []), + ].map((action) => ({ phase, action })), + ), + )( + "$action during $phase does not restore a removed or disabled server", + async ({ phase, action }) => { + const directory = await mkdtemp(join(tmpdir(), "mcp-ownership-")) + const entered = deferred() + const release = deferred() + let initializeRequests = 0 + let base = "" + const send = (response: ServerResponse, data: unknown, status = 200) => { + response.writeHead(status, { "Content-Type": "application/json" }) + response.end(JSON.stringify(data)) + } + const server = createServer((request, response) => { + void (async () => { + if (request.url?.includes("oauth-protected-resource")) { + send(response, { resource: `${base}/mcp`, authorization_servers: [base] }) + } else if (request.url?.includes(".well-known")) { + send(response, { + issuer: base, + authorization_endpoint: `${base}/authorize`, + token_endpoint: `${base}/token`, + response_types_supported: ["code"], + grant_types_supported: ["authorization_code"], + code_challenge_methods_supported: ["S256"], + token_endpoint_auth_methods_supported: ["none"], + }) + } else if (request.url === "/token") { + if (phase === "exchange") { + entered.resolve() + await release.promise + } + send(response, { access_token: "accepted", token_type: "Bearer", expires_in: 3600 }) + } else if (request.method === "DELETE") { + response.writeHead(200).end() + } else if (request.method === "GET") { + response.writeHead(405).end() + } else { + let body = "" + for await (const chunk of request) body += String(chunk) + const message = JSON.parse(body) as { id?: number; method: string } + if (message.method === "initialize") initializeRequests++ + if (request.headers.authorization !== "Bearer accepted") { + response.setHeader( + "WWW-Authenticate", + `Bearer resource_metadata="${base}/.well-known/oauth-protected-resource"`, + ) + send(response, { error: "unauthorized" }, 401) + } else if (message.id === undefined) { + response.writeHead(202).end() + } else { + if (phase === "reconnect" && message.method === "initialize") { + entered.resolve() + await release.promise + } + const result = + message.method === "initialize" + ? { + protocolVersion: "2025-03-26", + capabilities: { tools: {}, resources: {} }, + serverInfo: { name: "local", version: "1" }, + } + : { tools: [], resources: [], resourceTemplates: [] } + send(response, { jsonrpc: "2.0", id: message.id, result }) + } + } + })().catch((error: unknown) => { + send(response, { error: String(error) }, 500) + }) + }) + await new Promise((resolve) => { + server.listen(0, "127.0.0.1", resolve) + }) + const address = server.address() + if (!address || typeof address === "string") throw new Error("Missing server address") + base = `http://127.0.0.1:${address.port}` + const config = { type: "streamable-http", url: `${base}/mcp`, oauth: { clientId: "static-client" } } + await writeFile(join(directory, "mcp_settings.json"), JSON.stringify({ mcpServers: { local: config } })) + const values = new Map() + const listeners = new Set<() => void>() + // The store double supplies only the OAuth storage API used by the real provider. + const storage = { + hasOAuthData: async (url: string) => values.has(url), + getOAuthData: async (url: string) => values.get(url), + saveOAuthData: async (url: string, data: StoredMcpOAuthData) => { + values.set(url, data) + for (const listener of listeners) listener() + }, + deleteOAuthData: async (url: string) => { + values.delete(url) + }, + onDidChange: (_url: string, listener: () => void) => { + listeners.add(listener) + return () => { + listeners.delete(listener) + } + }, + } as unknown as SecretStorageService + const panelRows: Array> = [] + // The extension double supplies settings, panel updates, and the extension version. + const provider = { + ensureSettingsDirectoryExists: async () => directory, + postMessageToWebview: vi.fn( + (message: { + type: string + mcpServers?: Array<{ name: string; status: string; error?: string }> + }) => { + if (message.type === "mcpServers" && message.mcpServers) + panelRows.push(structuredClone(message.mcpServers)) + }, + ), + getState: async () => ({ mcpEnabled: true }), + context: { extension: { packageJSON: { version: "1" } } }, + } as unknown as ClineProvider + vi.mocked(vscode.env.openExternal).mockImplementation(async (uri) => { + if (phase === "browser") { + entered.resolve() + await release.promise + } + const url = new URL(uri.toString()) + const callback = new URL(url.searchParams.get("redirect_uri")!) + callback.searchParams.set("code", "authorization-code") + callback.searchParams.set("state", url.searchParams.get("state")!) + await fetch(callback) + return true + }) + const previous = process.env.MCP_OAUTH_TEST_MODE + process.env.MCP_OAUTH_TEST_MODE = "true" + // Test mode skips the notification UI but keeps the full OAuth and HTTP flow. + const cancellationListeners = new Set<() => void>() + const cancellationToken = { + isCancellationRequested: false, + onCancellationRequested: (listener: () => void) => { + cancellationListeners.add(listener) + return { + dispose: () => { + cancellationListeners.delete(listener) + }, + } + }, + } + const progress = vi.fn((_options: unknown, task: (progress: unknown, token: unknown) => unknown) => + task({ report: vi.fn() }, cancellationToken), + ) + Object.assign(vscode.window, { withProgress: progress }) + const hub = new McpHub(provider, storage) + const completions: Promise[] = [] + const complete = hub["_completeOAuthFlow"].bind(hub) + hub["_completeOAuthFlow"] = (...args) => { + const completion = complete(...args) + completions.push(completion) + return completion + } + try { + await hub.waitUntilReady() + await entered.promise + const before = initializeRequests + if (action === "delete") await hub.deleteConnection("local", "global") + if (action === "disable") await hub.toggleServerDisabled("local", true, "global") + if (action === "dispose") await hub.dispose() + if (action === "cancel" || action === "cancel-delete") { + cancellationToken.isCancellationRequested = true + for (const listener of cancellationListeners) listener() + } + if (action === "cancel-delete") await hub.deleteConnection("local", "global") + if (action === "timeout") { + const flow = [...hub["oauthFlows"].values()][0] + if (!flow) throw new Error("Missing reconnect flow") + flow.finish("timed-out") + } + release.resolve() + await vi.waitFor(() => expect(hub["oauthFlows"].size).toBe(0)) + // The flow can finish after its watcher was removed by the external action. + await Promise.all(progress.mock.results.map((result) => result.value)) + await Promise.all(completions) + if (action === "accept") { + expect(hub.connections[0]?.server.status).toBe("connected") + if (phase === "reconnect") expect(initializeRequests).toBe(before) + else expect(initializeRequests).toBeGreaterThan(before) + } else { + expect(initializeRequests).toBe(before) + if (action === "disable") expect(hub.connections[0]?.server.disabled).toBe(true) + else if (action === "cancel" || action === "timeout") { + expect(hub.connections).toHaveLength(1) + expect(hub.connections[0]?.server.status).toBe("disconnected") + expect(hub.connections[0]?.server.disabled).not.toBe(true) + expect(hub.connections[0]?.server.error).toBe( + t(action === "cancel" ? "mcp:oauth.flow.cancelled" : "mcp:oauth.flow.timedOut"), + ) + await vi.waitFor(() => + expect(panelRows.at(-1)?.[0]).toMatchObject({ + name: "local", + status: "disconnected", + error: hub.connections[0]?.server.error, + }), + ) + if (phase === "reconnect") { + cancellationToken.isCancellationRequested = false + await hub.restartConnection("local", "global") + await vi.waitFor(() => expect(hub.connections[0]?.server.status).toBe("connected")) + } + } else expect(hub.connections).toHaveLength(0) + } + } finally { + release.resolve() + await hub.dispose() + if (previous === undefined) delete process.env.MCP_OAUTH_TEST_MODE + else process.env.MCP_OAUTH_TEST_MODE = previous + server.closeAllConnections() + await new Promise((resolve) => { + server.close(() => resolve()) + }) + await rm(directory, { recursive: true, force: true }) + } + }, + 15000, + ) +}) From 852856e2402125f7b714a341b9dd16e31f735970 Mon Sep 17 00:00:00 2001 From: Elliott de Launay Date: Sat, 28 Nov 2026 22:58:03 +0000 Subject: [PATCH 3/3] fix: close MCP OAuth review gaps and simplify flow ownership --- ...pConnectionOwnership.DeleteReplacement.cfg | 1 - .../tla/McpConnectionOwnership.LateDetach.cfg | 1 - .../tla/McpConnectionOwnership.LateSetup.cfg | 1 - ...McpConnectionOwnership.LostRecoveryRow.cfg | 1 - .../tla/McpConnectionOwnership.cfg | 1 - .../tla/McpConnectionOwnership.tla | 13 +- ...mer.cfg => McpOAuthFlowEnd.ClaimTimer.cfg} | 1 - .../tla/McpOAuthFlowEnd.DeleteLeak.cfg | 1 - .../tla/McpOAuthFlowEnd.DisposeLeak.cfg | 1 - .../tla/McpOAuthFlowEnd.DoubleClaim.cfg | 1 - .../tla/McpOAuthFlowEnd.ErrorLeak.cfg | 1 - .../tla/McpOAuthFlowEnd.FinishTimer.cfg | 1 - .../tla/McpOAuthFlowEnd.IgnoreOutcome.cfg | 1 - .../tla/McpOAuthFlowEnd.ReconnectTimer.cfg | 14 - .../tla/McpOAuthFlowEnd.ReplaceLeak.cfg | 1 - .../tla/McpOAuthFlowEnd.StaleContinuation.cfg | 1 - docs/architecture/tla/McpOAuthFlowEnd.cfg | 1 - docs/architecture/tla/McpOAuthFlowEnd.tla | 47 +- .../tla/McpOAuthPanelSettle.DropRow.cfg | 7 + .../tla/McpOAuthPanelSettle.LateFinish.cfg | 7 + .../tla/McpOAuthPanelSettle.SilentFail.cfg | 7 + docs/architecture/tla/McpOAuthPanelSettle.cfg | 7 + docs/architecture/tla/McpOAuthPanelSettle.tla | 57 ++ .../McpOAuthRedirectUrl.LostCachedClient.cfg | 7 - .../tla/McpOAuthRedirectUrl.NoEnsure.cfg | 3 +- .../tla/McpOAuthRedirectUrl.NoOverride.cfg | 3 +- docs/architecture/tla/McpOAuthRedirectUrl.cfg | 3 +- docs/architecture/tla/McpOAuthRedirectUrl.tla | 27 +- .../McpOAuthRefreshToken.DropOnTransient.cfg | 7 + ...McpOAuthRefreshToken.DropUnknownIssuer.cfg | 7 + .../tla/McpOAuthRefreshToken.SdkRefresh.cfg | 7 + .../architecture/tla/McpOAuthRefreshToken.cfg | 7 + .../architecture/tla/McpOAuthRefreshToken.tla | 44 ++ .../tla/McpOAuthRetry.DiscoveryLoop.cfg | 3 +- .../tla/McpOAuthRetry.NoResetOnSuccess.cfg | 6 + .../tla/McpOAuthRetry.ResetOnInitialize.cfg | 3 +- docs/architecture/tla/McpOAuthRetry.cfg | 3 +- docs/architecture/tla/McpOAuthRetry.tla | 34 +- .../tla/McpOAuthStatusHandoff.tla | 3 +- .../tla/McpServerToggle.NoResume.cfg | 7 + .../tla/McpServerToggle.UnguardedRestart.cfg | 7 + .../tla/McpServerToggle.Unordered.cfg | 7 + docs/architecture/tla/McpServerToggle.cfg | 7 + docs/architecture/tla/McpServerToggle.tla | 86 +++ src/core/tools/UseMcpToolTool.ts | 5 +- .../tools/__tests__/useMcpToolTool.spec.ts | 16 +- src/i18n/locales/zh-CN/mcp.json | 2 +- src/i18n/locales/zh-TW/mcp.json | 2 +- src/services/mcp/McpHub.ts | 467 ++++++------ src/services/mcp/McpOAuthClientProvider.ts | 33 +- src/services/mcp/McpOAuthFlow.ts | 34 +- src/services/mcp/__tests__/McpHub.spec.ts | 279 ++++--- .../__tests__/McpOAuthClientProvider.spec.ts | 96 ++- .../mcp/__tests__/McpOAuthFlow.spec.ts | 12 +- .../__tests__/mcp-oauth-flow.property.spec.ts | 92 +-- .../mcp-oauth-ownership.integration.spec.ts | 699 +++++++++++++----- .../mcp-server-toggle.integration.spec.ts | 149 ++++ .../__tests__/callbackServer.listener.spec.ts | 15 + src/services/mcp/utils/callbackServer.ts | 7 +- 59 files changed, 1593 insertions(+), 770 deletions(-) rename docs/architecture/tla/{McpOAuthFlowEnd.BrowserTimer.cfg => McpOAuthFlowEnd.ClaimTimer.cfg} (94%) delete mode 100644 docs/architecture/tla/McpOAuthFlowEnd.ReconnectTimer.cfg create mode 100644 docs/architecture/tla/McpOAuthPanelSettle.DropRow.cfg create mode 100644 docs/architecture/tla/McpOAuthPanelSettle.LateFinish.cfg create mode 100644 docs/architecture/tla/McpOAuthPanelSettle.SilentFail.cfg create mode 100644 docs/architecture/tla/McpOAuthPanelSettle.cfg create mode 100644 docs/architecture/tla/McpOAuthPanelSettle.tla delete mode 100644 docs/architecture/tla/McpOAuthRedirectUrl.LostCachedClient.cfg create mode 100644 docs/architecture/tla/McpOAuthRefreshToken.DropOnTransient.cfg create mode 100644 docs/architecture/tla/McpOAuthRefreshToken.DropUnknownIssuer.cfg create mode 100644 docs/architecture/tla/McpOAuthRefreshToken.SdkRefresh.cfg create mode 100644 docs/architecture/tla/McpOAuthRefreshToken.cfg create mode 100644 docs/architecture/tla/McpOAuthRefreshToken.tla create mode 100644 docs/architecture/tla/McpOAuthRetry.NoResetOnSuccess.cfg create mode 100644 docs/architecture/tla/McpServerToggle.NoResume.cfg create mode 100644 docs/architecture/tla/McpServerToggle.UnguardedRestart.cfg create mode 100644 docs/architecture/tla/McpServerToggle.Unordered.cfg create mode 100644 docs/architecture/tla/McpServerToggle.cfg create mode 100644 docs/architecture/tla/McpServerToggle.tla create mode 100644 src/services/mcp/__tests__/mcp-server-toggle.integration.spec.ts diff --git a/docs/architecture/tla/McpConnectionOwnership.DeleteReplacement.cfg b/docs/architecture/tla/McpConnectionOwnership.DeleteReplacement.cfg index 8a0e8ac8701..3c9c9b979ad 100644 --- a/docs/architecture/tla/McpConnectionOwnership.DeleteReplacement.cfg +++ b/docs/architecture/tla/McpConnectionOwnership.DeleteReplacement.cfg @@ -4,6 +4,5 @@ CONSTANTS KeepStoppedRow = TRUE GuardSetup = TRUE DetachBeforeClose = TRUE - CheckClosing = FALSE PreserveReplacement = FALSE INVARIANTS TypeOK NoStaleAccess ReplacementRetained NoLateSetup RecoveryVisible diff --git a/docs/architecture/tla/McpConnectionOwnership.LateDetach.cfg b/docs/architecture/tla/McpConnectionOwnership.LateDetach.cfg index 12ffc49a02a..fa475cb18db 100644 --- a/docs/architecture/tla/McpConnectionOwnership.LateDetach.cfg +++ b/docs/architecture/tla/McpConnectionOwnership.LateDetach.cfg @@ -4,6 +4,5 @@ CONSTANTS KeepStoppedRow = TRUE GuardSetup = TRUE DetachBeforeClose = FALSE - CheckClosing = FALSE PreserveReplacement = TRUE INVARIANTS TypeOK NoStaleAccess ReplacementRetained NoLateSetup RecoveryVisible diff --git a/docs/architecture/tla/McpConnectionOwnership.LateSetup.cfg b/docs/architecture/tla/McpConnectionOwnership.LateSetup.cfg index 818a2f0fe10..e646e011fad 100644 --- a/docs/architecture/tla/McpConnectionOwnership.LateSetup.cfg +++ b/docs/architecture/tla/McpConnectionOwnership.LateSetup.cfg @@ -4,6 +4,5 @@ CONSTANTS KeepStoppedRow = TRUE GuardSetup = FALSE DetachBeforeClose = TRUE - CheckClosing = FALSE PreserveReplacement = TRUE INVARIANTS TypeOK NoStaleAccess ReplacementRetained NoLateSetup RecoveryVisible diff --git a/docs/architecture/tla/McpConnectionOwnership.LostRecoveryRow.cfg b/docs/architecture/tla/McpConnectionOwnership.LostRecoveryRow.cfg index a295965c45c..edf7b96db5e 100644 --- a/docs/architecture/tla/McpConnectionOwnership.LostRecoveryRow.cfg +++ b/docs/architecture/tla/McpConnectionOwnership.LostRecoveryRow.cfg @@ -4,6 +4,5 @@ CONSTANTS KeepStoppedRow = FALSE GuardSetup = TRUE DetachBeforeClose = TRUE - CheckClosing = FALSE PreserveReplacement = TRUE INVARIANTS TypeOK NoStaleAccess ReplacementRetained NoLateSetup RecoveryVisible diff --git a/docs/architecture/tla/McpConnectionOwnership.cfg b/docs/architecture/tla/McpConnectionOwnership.cfg index b3c822dac12..3061a6e73aa 100644 --- a/docs/architecture/tla/McpConnectionOwnership.cfg +++ b/docs/architecture/tla/McpConnectionOwnership.cfg @@ -4,6 +4,5 @@ CONSTANTS KeepStoppedRow = TRUE GuardSetup = TRUE DetachBeforeClose = TRUE - CheckClosing = FALSE PreserveReplacement = TRUE INVARIANTS TypeOK NoStaleAccess ReplacementRetained NoLateSetup RecoveryVisible diff --git a/docs/architecture/tla/McpConnectionOwnership.tla b/docs/architecture/tla/McpConnectionOwnership.tla index f1ee6ea188f..aec4c5a110d 100644 --- a/docs/architecture/tla/McpConnectionOwnership.tla +++ b/docs/architecture/tla/McpConnectionOwnership.tla @@ -19,14 +19,17 @@ EXTENDS Naturals \* Runtime sabotage: removing recovery fails the cancel and timeout cases. A later delete still wins. \* Gap: the model does not describe SDK resource cleanup or browser behavior. \* Simplification: McpHub.stopOAuthReconnect performs StopReconnect as one synchronous operation. -\* Source: an abort callback supplies the owner, revision, validated config, and reason. -\* Sink: cleanup starts, and a cancel or timeout retains the error row before any await. +\* Source: a cancel cleanup on the flow supplies the server name, source, revision, and config. +\* Sink: cleanup starts, and a cancel retains the error row before any await. \* Expect: existing RecoveryVisible and ReplacementRetained still hold. No new defect is expected. \* Cost: one agent; function extraction with no extra model state or dependencies. \* Simplification result: fixed holds in 28 states and all four failure variants still fail. \* Null result: all 17 HTTP cases pass after extraction. No new runtime defect was found. \* Runtime sabotage: removing the extracted recovery step fails cancel and timeout cases. -CONSTANTS DetachBeforeClose, CheckClosing, PreserveReplacement, GuardSetup, KeepStoppedRow +\* The second PR #2762 review (#21, #52) removed the timeout reconnect path and the unused CheckClosing. +\* Simplification: stopOAuthReconnect runs only for a cancel, as a flow cleanup. Model unchanged. +\* Gap: the rediscovery reconnect has no flow. The integration spec covers its removal check. +CONSTANTS DetachBeforeClose, PreserveReplacement, GuardSetup, KeepStoppedRow \* registered = 3 is a disconnected row with an error and an enabled retry action. VARIABLES registered, closing, staleAccess, replacementLost, permit, setup, latePublish, recoveryRequired vars == <> @@ -40,7 +43,7 @@ BeginClose == /\ registered' = IF DetachBeforeClose THEN 0 ELSE registered /\ UNCHANGED <> ContinueOld == - /\ staleAccess' = (staleAccess \/ (registered = 1 /\ closing = 1 /\ ~CheckClosing)) + /\ staleAccess' = (staleAccess \/ (registered = 1 /\ closing = 1)) /\ UNCHANGED <> PublishReplacement == /\ closing = 1 /\ registered # 2 @@ -60,7 +63,7 @@ PublishSetup == /\ setup' = FALSE /\ latePublish' = (~permit /\ ~GuardSetup) /\ UNCHANGED <> -\* Cancel or a callback timeout stops reconnect, but retains an error row. +\* A cancellation stops reconnect, but retains an error row. The timer cannot fire during a reconnect. StopReconnect == /\ registered = 2 /\ registered' = IF KeepStoppedRow THEN 3 ELSE 0 diff --git a/docs/architecture/tla/McpOAuthFlowEnd.BrowserTimer.cfg b/docs/architecture/tla/McpOAuthFlowEnd.ClaimTimer.cfg similarity index 94% rename from docs/architecture/tla/McpOAuthFlowEnd.BrowserTimer.cfg rename to docs/architecture/tla/McpOAuthFlowEnd.ClaimTimer.cfg index 0ba3c3f1e3e..4022995490d 100644 --- a/docs/architecture/tla/McpOAuthFlowEnd.BrowserTimer.cfg +++ b/docs/architecture/tla/McpOAuthFlowEnd.ClaimTimer.cfg @@ -3,7 +3,6 @@ CHECK_DEADLOCK FALSE CONSTANTS StopOnFinish = TRUE StopOnClaim = FALSE - StopOnReconnect = TRUE CheckOutcome = TRUE ClaimOnce = TRUE GuardContinuation = TRUE diff --git a/docs/architecture/tla/McpOAuthFlowEnd.DeleteLeak.cfg b/docs/architecture/tla/McpOAuthFlowEnd.DeleteLeak.cfg index 4828a6e4572..58969f1b950 100644 --- a/docs/architecture/tla/McpOAuthFlowEnd.DeleteLeak.cfg +++ b/docs/architecture/tla/McpOAuthFlowEnd.DeleteLeak.cfg @@ -4,7 +4,6 @@ CHECK_DEADLOCK FALSE CONSTANTS StopOnFinish = TRUE StopOnClaim = TRUE - StopOnReconnect = TRUE CheckOutcome = TRUE ClaimOnce = TRUE GuardContinuation = TRUE diff --git a/docs/architecture/tla/McpOAuthFlowEnd.DisposeLeak.cfg b/docs/architecture/tla/McpOAuthFlowEnd.DisposeLeak.cfg index 900f0fa98a3..5bd59e2f1e4 100644 --- a/docs/architecture/tla/McpOAuthFlowEnd.DisposeLeak.cfg +++ b/docs/architecture/tla/McpOAuthFlowEnd.DisposeLeak.cfg @@ -4,7 +4,6 @@ CHECK_DEADLOCK FALSE CONSTANTS StopOnFinish = TRUE StopOnClaim = TRUE - StopOnReconnect = TRUE CheckOutcome = TRUE ClaimOnce = TRUE GuardContinuation = TRUE diff --git a/docs/architecture/tla/McpOAuthFlowEnd.DoubleClaim.cfg b/docs/architecture/tla/McpOAuthFlowEnd.DoubleClaim.cfg index a490c2526a8..2123ac5577c 100644 --- a/docs/architecture/tla/McpOAuthFlowEnd.DoubleClaim.cfg +++ b/docs/architecture/tla/McpOAuthFlowEnd.DoubleClaim.cfg @@ -3,7 +3,6 @@ CHECK_DEADLOCK FALSE CONSTANTS StopOnFinish = TRUE StopOnClaim = TRUE - StopOnReconnect = TRUE CheckOutcome = TRUE ClaimOnce = FALSE GuardContinuation = TRUE diff --git a/docs/architecture/tla/McpOAuthFlowEnd.ErrorLeak.cfg b/docs/architecture/tla/McpOAuthFlowEnd.ErrorLeak.cfg index 2557d67d0f3..2ea53b1dbe2 100644 --- a/docs/architecture/tla/McpOAuthFlowEnd.ErrorLeak.cfg +++ b/docs/architecture/tla/McpOAuthFlowEnd.ErrorLeak.cfg @@ -4,7 +4,6 @@ CHECK_DEADLOCK FALSE CONSTANTS StopOnFinish = TRUE StopOnClaim = TRUE - StopOnReconnect = TRUE CheckOutcome = TRUE ClaimOnce = TRUE GuardContinuation = TRUE diff --git a/docs/architecture/tla/McpOAuthFlowEnd.FinishTimer.cfg b/docs/architecture/tla/McpOAuthFlowEnd.FinishTimer.cfg index 556ee674edc..5b4d52c7661 100644 --- a/docs/architecture/tla/McpOAuthFlowEnd.FinishTimer.cfg +++ b/docs/architecture/tla/McpOAuthFlowEnd.FinishTimer.cfg @@ -3,7 +3,6 @@ CHECK_DEADLOCK FALSE CONSTANTS StopOnFinish = FALSE StopOnClaim = TRUE - StopOnReconnect = TRUE CheckOutcome = TRUE ClaimOnce = TRUE GuardContinuation = TRUE diff --git a/docs/architecture/tla/McpOAuthFlowEnd.IgnoreOutcome.cfg b/docs/architecture/tla/McpOAuthFlowEnd.IgnoreOutcome.cfg index f280703b746..18710457cb4 100644 --- a/docs/architecture/tla/McpOAuthFlowEnd.IgnoreOutcome.cfg +++ b/docs/architecture/tla/McpOAuthFlowEnd.IgnoreOutcome.cfg @@ -3,7 +3,6 @@ CHECK_DEADLOCK FALSE CONSTANTS StopOnFinish = TRUE StopOnClaim = TRUE - StopOnReconnect = TRUE CheckOutcome = FALSE ClaimOnce = TRUE GuardContinuation = TRUE diff --git a/docs/architecture/tla/McpOAuthFlowEnd.ReconnectTimer.cfg b/docs/architecture/tla/McpOAuthFlowEnd.ReconnectTimer.cfg deleted file mode 100644 index 30d142e8f36..00000000000 --- a/docs/architecture/tla/McpOAuthFlowEnd.ReconnectTimer.cfg +++ /dev/null @@ -1,14 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - StopOnFinish = TRUE - StopOnClaim = TRUE - StopOnReconnect = FALSE - CheckOutcome = TRUE - ClaimOnce = TRUE - GuardContinuation = TRUE - ReplaceEndsFlow = TRUE - DeleteEndsFlow = TRUE - DisposeEndsFlows = TRUE - ErrorEndsFlow = TRUE -INVARIANTS TypeOK NoDuplicateFlow NoOrphanFlow ToolNotOrphaned NoErrorLeak NoStaleWrite OneContinuation ToolRequiresSuccess TimerOnlyWhileWaiting diff --git a/docs/architecture/tla/McpOAuthFlowEnd.ReplaceLeak.cfg b/docs/architecture/tla/McpOAuthFlowEnd.ReplaceLeak.cfg index 294ab5088fc..cdc40634178 100644 --- a/docs/architecture/tla/McpOAuthFlowEnd.ReplaceLeak.cfg +++ b/docs/architecture/tla/McpOAuthFlowEnd.ReplaceLeak.cfg @@ -4,7 +4,6 @@ CHECK_DEADLOCK FALSE CONSTANTS StopOnFinish = TRUE StopOnClaim = TRUE - StopOnReconnect = TRUE CheckOutcome = TRUE ClaimOnce = TRUE GuardContinuation = TRUE diff --git a/docs/architecture/tla/McpOAuthFlowEnd.StaleContinuation.cfg b/docs/architecture/tla/McpOAuthFlowEnd.StaleContinuation.cfg index a7ea5f8b0e6..ade484bfb3c 100644 --- a/docs/architecture/tla/McpOAuthFlowEnd.StaleContinuation.cfg +++ b/docs/architecture/tla/McpOAuthFlowEnd.StaleContinuation.cfg @@ -3,7 +3,6 @@ CHECK_DEADLOCK FALSE CONSTANTS StopOnFinish = TRUE StopOnClaim = TRUE - StopOnReconnect = TRUE CheckOutcome = TRUE ClaimOnce = TRUE GuardContinuation = FALSE diff --git a/docs/architecture/tla/McpOAuthFlowEnd.cfg b/docs/architecture/tla/McpOAuthFlowEnd.cfg index f1be329bccf..135a4c8688c 100644 --- a/docs/architecture/tla/McpOAuthFlowEnd.cfg +++ b/docs/architecture/tla/McpOAuthFlowEnd.cfg @@ -3,7 +3,6 @@ CHECK_DEADLOCK FALSE CONSTANTS StopOnFinish = TRUE StopOnClaim = TRUE - StopOnReconnect = TRUE CheckOutcome = TRUE ClaimOnce = TRUE GuardContinuation = TRUE diff --git a/docs/architecture/tla/McpOAuthFlowEnd.tla b/docs/architecture/tla/McpOAuthFlowEnd.tla index 61d773d6d16..9233dfe9e8f 100644 --- a/docs/architecture/tla/McpOAuthFlowEnd.tla +++ b/docs/architecture/tla/McpOAuthFlowEnd.tla @@ -1,25 +1,22 @@ ---- MODULE McpOAuthFlowEnd ---- EXTENDS Naturals -\* Source: McpHub.createOAuthFlow registers one entry in oauthFlows. -\* McpOAuthFlow owns the completion promise. deleteConnection(), flow replacement in createOAuthFlow(), -\* dispose(), and the token-watcher error path remove or replace that entry. +\* Source: McpHub.createOAuthFlow registers one McpOAuthFlow in oauthFlows. deleteConnection(), +\* flow replacement, dispose(), and a reconnect error end it through McpOAuthFlow.finish. \* Sink: McpHub.callTool awaits the re-auth promise, and the flow promise resolves \* through McpOAuthFlow.finish. -\* Failure: a removed watcher leaves its flow pending, so the notification stays +\* Failure: a removed flow stays pending, so the notification stays \* open and tool calls that wait on the flow stay blocked (issue 2761). -\* Failure: an old flow removes the watcher of a newer flow, so the newer flow +\* Failure: an old flow removes a newer flow, so the newer flow \* can never time out or resolve. \* Failure: a reconnect that throws in the token watcher leaves the flow pending. \* Invariants: NoDuplicateFlow, NoOrphanFlow, ToolNotOrphaned, NoErrorLeak. -\* Fix rule: every watcher removal goes through one shared path that also ends -\* the flow, and a reconnect error ends the flow with a visible error. -\* Scope: timeouts, cancellation, and the toast paths end the flow inside the -\* flow itself; the model folds them into FlowEnds. Secret storage is an oracle. -\* Scope: at most two flows and one watcher per key. One tool call waits at a time. +\* Fix rule: every removal ends the flow through one shared path, and a reconnect error ends the flow with a visible error. +\* Scope: FlowEnds folds the cancel and toast paths. The timer actions model the approval timer. +\* Secret storage is an oracle. +\* Scope: at most two flows and one registered flow per key. One tool call waits at a time. \* Expect: Fixed holds. ReplaceLeak, DeleteLeak, DisposeLeak and ErrorLeak each fail. -\* Result: Fixed holds in 672 states. ReplaceLeak fails at 80 states (NoDuplicateFlow). -\* DeleteLeak fails at 80 states (NoOrphanFlow). DisposeLeak fails at 80 states -\* (NoOrphanFlow). ErrorLeak fails at 80 states (NoErrorLeak). +\* Result: Fixed holds in 504 states. ReplaceLeak, DeleteLeak, DisposeLeak, and ErrorLeak fail at 69. +\* DoubleClaim fails at 60, IgnoreOutcome at 40, StaleContinuation at 64, ClaimTimer at 3, FinishTimer at 2. \* Property test: src/services/mcp/__tests__/mcp-oauth-flow.property.spec.ts. \* Review ratchet: PR #2762, supplied review findings #1, #2, #3, #8 and #29. @@ -36,28 +33,28 @@ EXTENDS Naturals \* Scope: the claim and outcome oracles each describe one flow episode. \* Sources: https://stately.ai/docs/invoke and https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal \* Cost: one agent; shared flow object and synchronous registry removal. -\* Result: DoubleClaim fails in 71 states; IgnoreOutcome in 51; StaleContinuation in 75. \* Findings: one terminal outcome also closes review #10. No new legacy runtime defect was found. \* Runtime sabotage: claim and outcome guards fail five and four tests when removed. \* Replay: synchronous removal fails before the refactor. The new HTTP cancellation cases pass. \* Covered: NoStaleWrite also requires a current-connection check after the panel update. \* Review ratchet: PR #2762 follow-ups A and D. Added 2 timer rules, covered 0, gap 0. \* Failure: the approval timer cuts short browser authentication or reconnect setup. -\* Expect: TimerOnlyWhileWaiting fails when claim or reconnect keeps the timer armed. +\* Expect: TimerOnlyWhileWaiting fails when a claim keeps the timer armed. \* Cost: one agent; two timer transitions and fake-time properties. -\* Timer result: BrowserTimer fails at 3 states; ReconnectTimer fails at 4. \* Replay: a late Authenticate click fails before the fix; waiting, browser, and reconnect tests pass. \* Runtime sabotage: removing either timer cleanup fails its phase test. \* Simplification: McpOAuthFlow.transitionTo owns the timer exit action for every phase change. \* Failure: a terminal transition leaves the approval timer armed. -\* Invariant: TimerOnlyWhileWaiting includes ended flows as well as browser and reconnect work. +\* Invariant: TimerOnlyWhileWaiting includes ended flows as well as claimed work. \* Expect: no new runtime defect. FinishTimer sabotage must fail; the existing guards must still hold. \* Cost: one agent; one timer transition and terminal-outcome property cases. -\* Simplification result: fixed holds in 672 states; FinishTimer fails at 2 states. \* Null result: terminal timer properties passed before and after extraction. No new runtime defect was found. \* Runtime sabotage: removing shared timer cleanup or the terminal guard fails the phase tests. +\* The second PR #2762 review (#48) found stale watcher text in this header. Added 0, covered 0. +\* Simplification: browser and reconnect work had the same timer effect, so one claim replaces both. +\* No new defect was found. CONSTANTS StopOnFinish -CONSTANTS StopOnClaim, StopOnReconnect +CONSTANTS StopOnClaim CONSTANTS CheckOutcome CONSTANTS ClaimOnce CONSTANTS GuardContinuation @@ -204,12 +201,9 @@ ChangeTimerPhase(nextPhase, stopTimer) == /\ timerPhase' = nextPhase /\ timerArmed' = IF stopTimer THEN FALSE ELSE timerArmed /\ UNCHANGED <> -ClaimBrowser == +ClaimTimer == /\ timerPhase = "waiting" - /\ ChangeTimerPhase("browser", StopOnClaim) -StartReconnect == - /\ timerPhase \in {"waiting", "browser"} - /\ ChangeTimerPhase("reconnecting", StopOnReconnect) + /\ ChangeTimerPhase("claimed", StopOnClaim) FinishTimer == /\ timerPhase # "ended" /\ ChangeTimerPhase("ended", StopOnFinish) @@ -217,8 +211,7 @@ TimerOnlyWhileWaiting == timerArmed => timerPhase = "waiting" Next == \/ FinishTimer - \/ ClaimBrowser - \/ StartReconnect + \/ ClaimTimer \/ Settle \/ RetryTool \/ Claim @@ -234,7 +227,7 @@ Next == Spec == Init /\ [][Next]_vars TypeOK == - /\ timerPhase \in {"waiting", "browser", "reconnecting", "ended"} + /\ timerPhase \in {"waiting", "claimed", "ended"} /\ timerArmed \in BOOLEAN /\ claims \in 0..2 /\ flowResult \in {"waiting", "connected", "cancelled", "removed", "failed", "timed-out"} diff --git a/docs/architecture/tla/McpOAuthPanelSettle.DropRow.cfg b/docs/architecture/tla/McpOAuthPanelSettle.DropRow.cfg new file mode 100644 index 00000000000..b795861c462 --- /dev/null +++ b/docs/architecture/tla/McpOAuthPanelSettle.DropRow.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + NotifyOnFail = TRUE + KeepRow = FALSE + FinishBeforeNotify = TRUE +INVARIANTS TypeOK Settled PanelMatches RowKept diff --git a/docs/architecture/tla/McpOAuthPanelSettle.LateFinish.cfg b/docs/architecture/tla/McpOAuthPanelSettle.LateFinish.cfg new file mode 100644 index 00000000000..87e8855fe88 --- /dev/null +++ b/docs/architecture/tla/McpOAuthPanelSettle.LateFinish.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + NotifyOnFail = TRUE + KeepRow = TRUE + FinishBeforeNotify = FALSE +INVARIANTS TypeOK Settled PanelMatches RowKept diff --git a/docs/architecture/tla/McpOAuthPanelSettle.SilentFail.cfg b/docs/architecture/tla/McpOAuthPanelSettle.SilentFail.cfg new file mode 100644 index 00000000000..1462062a49b --- /dev/null +++ b/docs/architecture/tla/McpOAuthPanelSettle.SilentFail.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + NotifyOnFail = FALSE + KeepRow = TRUE + FinishBeforeNotify = TRUE +INVARIANTS TypeOK Settled PanelMatches RowKept diff --git a/docs/architecture/tla/McpOAuthPanelSettle.cfg b/docs/architecture/tla/McpOAuthPanelSettle.cfg new file mode 100644 index 00000000000..538f2fc2a35 --- /dev/null +++ b/docs/architecture/tla/McpOAuthPanelSettle.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + NotifyOnFail = TRUE + KeepRow = TRUE + FinishBeforeNotify = TRUE +INVARIANTS TypeOK Settled PanelMatches RowKept diff --git a/docs/architecture/tla/McpOAuthPanelSettle.tla b/docs/architecture/tla/McpOAuthPanelSettle.tla new file mode 100644 index 00000000000..3453b16ca85 --- /dev/null +++ b/docs/architecture/tla/McpOAuthPanelSettle.tla @@ -0,0 +1,57 @@ +---- MODULE McpOAuthPanelSettle ---- +\* Source: a 401 reaches McpHub._initiateOAuthFlow. performOAuthFlow retries or gives up. +\* Sink: the server row and the last list that notifyWebviewOfServerChanges posts. +\* Failure: a failed reconnect posts nothing, so the panel stays "connecting". +\* Failure: a reconnect that throws before the push removes the row. +\* Failure: a second 401 joins a flow that already surfaced its error, so no writer remains. +\* Invariants: Settled, PanelMatches, RowKept. +\* Scope: one server. The reconnect result and the failure point are oracles. +\* Expect: Fixed holds. SilentFail, DropRow, and LateFinish each fail. +\* Order: the PR #2762 review came before these invariants. Review ratchet: added 3. +\* Property test: src/services/mcp/__tests__/mcp-oauth-ownership.integration.spec.ts. +\* Result: Fixed holds in 4 states. SilentFail fails at 4, DropRow at 4, LateFinish at 7. +\* Replay: both reconnect failures and the late second 401 fail on the old code and pass on the fix. +\* Cost: one agent; three variables, no new dependency. +CONSTANTS NotifyOnFail, KeepRow, FinishBeforeNotify +VARIABLES row, panel, flow +vars == <> + +Init == row = "connected" /\ panel = "connected" /\ flow = "none" + +\* A 401 sets "connecting" and starts a flow, or joins the registered flow. +Reject == + /\ row # "none" + /\ row' = "connecting" + /\ flow' = IF flow = "none" THEN "running" ELSE flow + /\ UNCHANGED panel + +\* The retry limit surfaces an error. The old order ends the flow after the panel update. +Exhaust == + /\ flow = "running" + /\ row' = "disconnected" /\ panel' = "disconnected" + /\ flow' = IF FinishBeforeNotify THEN "none" ELSE "surfacing" + +FinishExhaust == flow = "surfacing" /\ flow' = "none" /\ UNCHANGED <> + +ReconnectOk == + /\ flow = "running" + /\ row' = "connected" /\ panel' = "connected" /\ flow' = "none" + +\* "pushed" is true when connectToServer added the new row before it failed. +ReconnectFail == + /\ flow = "running" + /\ \E pushed \in BOOLEAN : row' = IF pushed \/ KeepRow THEN "disconnected" ELSE "none" + /\ panel' = IF NotifyOnFail THEN row' ELSE "connecting" + /\ flow' = "none" + +Next == Reject \/ Exhaust \/ FinishExhaust \/ ReconnectOk \/ ReconnectFail +Spec == Init /\ [][Next]_vars + +TypeOK == + /\ row \in {"connected", "connecting", "disconnected", "none"} + /\ panel \in {"connected", "connecting", "disconnected", "none"} + /\ flow \in {"none", "running", "surfacing"} +Settled == flow = "none" => row # "connecting" +PanelMatches == flow = "none" => panel = row +RowKept == row # "none" +==== diff --git a/docs/architecture/tla/McpOAuthRedirectUrl.LostCachedClient.cfg b/docs/architecture/tla/McpOAuthRedirectUrl.LostCachedClient.cfg deleted file mode 100644 index b2686c9b261..00000000000 --- a/docs/architecture/tla/McpOAuthRedirectUrl.LostCachedClient.cfg +++ /dev/null @@ -1,7 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - FixRedirectUri = TRUE - EnsureListener = TRUE - PreserveCachedClient = FALSE -INVARIANTS TypeOK NoBadOpen CachedRegistrationRetained diff --git a/docs/architecture/tla/McpOAuthRedirectUrl.NoEnsure.cfg b/docs/architecture/tla/McpOAuthRedirectUrl.NoEnsure.cfg index e3122d576c6..2e8385ca0da 100644 --- a/docs/architecture/tla/McpOAuthRedirectUrl.NoEnsure.cfg +++ b/docs/architecture/tla/McpOAuthRedirectUrl.NoEnsure.cfg @@ -4,5 +4,4 @@ CHECK_DEADLOCK FALSE CONSTANTS FixRedirectUri = TRUE EnsureListener = FALSE - PreserveCachedClient = TRUE -INVARIANTS TypeOK NoBadOpen CachedRegistrationRetained +INVARIANTS TypeOK NoBadOpen diff --git a/docs/architecture/tla/McpOAuthRedirectUrl.NoOverride.cfg b/docs/architecture/tla/McpOAuthRedirectUrl.NoOverride.cfg index 3087d61079a..4630388c8fb 100644 --- a/docs/architecture/tla/McpOAuthRedirectUrl.NoOverride.cfg +++ b/docs/architecture/tla/McpOAuthRedirectUrl.NoOverride.cfg @@ -4,5 +4,4 @@ CHECK_DEADLOCK FALSE CONSTANTS FixRedirectUri = FALSE EnsureListener = TRUE - PreserveCachedClient = TRUE -INVARIANTS TypeOK NoBadOpen CachedRegistrationRetained +INVARIANTS TypeOK NoBadOpen diff --git a/docs/architecture/tla/McpOAuthRedirectUrl.cfg b/docs/architecture/tla/McpOAuthRedirectUrl.cfg index f4a408f8d5d..5c79ccd11ff 100644 --- a/docs/architecture/tla/McpOAuthRedirectUrl.cfg +++ b/docs/architecture/tla/McpOAuthRedirectUrl.cfg @@ -3,5 +3,4 @@ CHECK_DEADLOCK FALSE CONSTANTS FixRedirectUri = TRUE EnsureListener = TRUE - PreserveCachedClient = TRUE -INVARIANTS TypeOK NoBadOpen CachedRegistrationRetained +INVARIANTS TypeOK NoBadOpen diff --git a/docs/architecture/tla/McpOAuthRedirectUrl.tla b/docs/architecture/tla/McpOAuthRedirectUrl.tla index 4b3739e79c4..8b2de0e1af5 100644 --- a/docs/architecture/tla/McpOAuthRedirectUrl.tla +++ b/docs/architecture/tla/McpOAuthRedirectUrl.tla @@ -11,17 +11,16 @@ \* A listener that dies between the \* URL store and the open is out of scope; the next flow stores a fresh URL. \* A strict server that rejects a changed port is out of scope (issue follow-up). -\* Result: fixed holds in 14 states. NoOverride fails at 9 states, NoEnsure at 10, -\* and LostCachedClient at 2. The cached listener-bind regression passes in TypeScript. -\* Expect: fixed holds. Each missing redirect guard or cache assignment must fail. -\* Cost: one agent; reused the redirect model and added one cache-failure action. +\* Expect: fixed holds. Each missing redirect guard must fail. +\* Result: fixed holds. NoOverride and NoEnsure fail. +\* The second PR #2762 review (#51) removed a cached-registration invariant that was always true. +\* A TypeScript regression covers the cached listener-bind failure. +\* Cost: one agent; reused the redirect model. \* Review ratchet: PR #2762 supplied findings #13, #36, #39, #43 and #44, added 5. \* Property test: src/services/mcp/__tests__/mcp-oauth-flow.property.spec.ts. CONSTANTS FixRedirectUri \* TRUE when redirectToAuthorization overrides redirect_uri CONSTANTS EnsureListener \* TRUE when redirectToAuthorization starts the listener first -CONSTANTS PreserveCachedClient -VARIABLES cachedClientInfo, bindingFailure VARIABLES listenerPort \* port of the active callback listener; 0 when none VARIABLES sdkUrlPort \* redirect_uri port the SDK wrote into the URL @@ -30,11 +29,9 @@ VARIABLES urlStored \* redirectToAuthorization stored the URL for openBrows VARIABLES opened \* the URL was opened for the user VARIABLES badOpen \* latch: an open used a stale or zero port -vars == <> +vars == <> Init == - /\ cachedClientInfo = FALSE - /\ bindingFailure = FALSE /\ listenerPort = 0 /\ sdkUrlPort = 0 /\ finalUrlPort = 0 @@ -44,19 +41,16 @@ Init == \* Both cached registration and fresh DCR can start the listener. RegisterClient == - /\ UNCHANGED <> /\ listenerPort' = 1 /\ UNCHANGED <> \* The SDK builds the URL from provider.redirectUrl before the listener starts. SdkBuildsUrl == - /\ UNCHANGED <> /\ sdkUrlPort' = listenerPort /\ UNCHANGED <> \* redirectToAuthorization: ensure the listener owns a real port, then set redirect_uri. Redirect == - /\ UNCHANGED <> /\ listenerPort' = IF EnsureListener /\ listenerPort = 0 THEN 1 ELSE listenerPort /\ finalUrlPort' = IF FixRedirectUri THEN listenerPort' ELSE sdkUrlPort /\ urlStored' = TRUE @@ -65,21 +59,12 @@ Redirect == \* The user confirmed the toast and the stored URL is opened. A stale or zero \* port at open time is a bad open. OpenBrowser == - /\ UNCHANGED <> /\ urlStored /\ opened' = TRUE /\ badOpen' = (badOpen \/ finalUrlPort # listenerPort \/ finalUrlPort = 0) /\ UNCHANGED <> -CachedBindFailure == - /\ cachedClientInfo' = PreserveCachedClient - /\ bindingFailure' = TRUE - /\ UNCHANGED <> - -CachedRegistrationRetained == bindingFailure => cachedClientInfo - Next == - \/ CachedBindFailure \/ RegisterClient \/ SdkBuildsUrl \/ Redirect diff --git a/docs/architecture/tla/McpOAuthRefreshToken.DropOnTransient.cfg b/docs/architecture/tla/McpOAuthRefreshToken.DropOnTransient.cfg new file mode 100644 index 00000000000..8d6a6e080a9 --- /dev/null +++ b/docs/architecture/tla/McpOAuthRefreshToken.DropOnTransient.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + StripFromSdk = TRUE + KeepUnknownIssuer = TRUE + DropOnlyRejected = FALSE +INVARIANTS TypeOK NoLeak NoLostCredential diff --git a/docs/architecture/tla/McpOAuthRefreshToken.DropUnknownIssuer.cfg b/docs/architecture/tla/McpOAuthRefreshToken.DropUnknownIssuer.cfg new file mode 100644 index 00000000000..4dac79aa3b6 --- /dev/null +++ b/docs/architecture/tla/McpOAuthRefreshToken.DropUnknownIssuer.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + StripFromSdk = TRUE + KeepUnknownIssuer = FALSE + DropOnlyRejected = TRUE +INVARIANTS TypeOK NoLeak NoLostCredential diff --git a/docs/architecture/tla/McpOAuthRefreshToken.SdkRefresh.cfg b/docs/architecture/tla/McpOAuthRefreshToken.SdkRefresh.cfg new file mode 100644 index 00000000000..56480da7d01 --- /dev/null +++ b/docs/architecture/tla/McpOAuthRefreshToken.SdkRefresh.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + StripFromSdk = FALSE + KeepUnknownIssuer = TRUE + DropOnlyRejected = TRUE +INVARIANTS TypeOK NoLeak NoLostCredential diff --git a/docs/architecture/tla/McpOAuthRefreshToken.cfg b/docs/architecture/tla/McpOAuthRefreshToken.cfg new file mode 100644 index 00000000000..aaf1aebfe25 --- /dev/null +++ b/docs/architecture/tla/McpOAuthRefreshToken.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + StripFromSdk = TRUE + KeepUnknownIssuer = TRUE + DropOnlyRejected = TRUE +INVARIANTS TypeOK NoLeak NoLostCredential diff --git a/docs/architecture/tla/McpOAuthRefreshToken.tla b/docs/architecture/tla/McpOAuthRefreshToken.tla new file mode 100644 index 00000000000..07d8b672df3 --- /dev/null +++ b/docs/architecture/tla/McpOAuthRefreshToken.tla @@ -0,0 +1,44 @@ +---- MODULE McpOAuthRefreshToken ---- +\* Source: the refresh token in SecretStorage. McpOAuthClientProvider.tokens reads it. +\* Sink: a token request. The SDK auth() picks its server from server-controlled metadata. +\* Failure: the SDK posts the refresh token to a server that did not issue it. +\* Failure: a temporary discovery or refresh error deletes a usable refresh token. +\* Invariants: NoLeak, NoLostCredential. +\* Scope: one stored token. The live issuer and the refresh result are oracles. +\* Gap: a refresh in another window between the re-read and the delete. +\* Expect: Fixed holds. SdkRefresh, DropUnknownIssuer, and DropOnTransient each fail. +\* Order: the PR #2762 review came before these invariants. Review ratchet: added 2, gap 1. +\* Property test: src/services/mcp/__tests__/McpOAuthClientProvider.spec.ts. +\* Result: Fixed holds in 4 states. SdkRefresh fails at 3, DropUnknownIssuer at 4, DropOnTransient at 5. +\* Replay: with the refresh token, one SSE 401 caused 183 token requests in 500 ms. The fix causes none. +\* Cost: one agent; three variables, no new dependency. +CONSTANTS StripFromSdk, KeepUnknownIssuer, DropOnlyRejected +VARIABLES stored, sink, lost +vars == <> + +Init == stored = TRUE /\ sink = "none" /\ lost = FALSE + +\* The SDK reads the tokens after a 401 and refreshes at the server it discovered. +SdkRead == + /\ stored /\ ~StripFromSdk + /\ \E server \in {"issuer", "other"} : sink' = server + /\ UNCHANGED <> + +\* The provider refreshes an expired token. "unknown" means that discovery failed. +ProviderRefresh == + /\ stored + /\ \E live \in {"issuer", "other", "unknown"}, result \in {"ok", "rejected", "transient"} : + LET temporary == (live = "unknown" /\ ~KeepUnknownIssuer) + \/ (live = "issuer" /\ result = "transient" /\ ~DropOnlyRejected) + IN /\ sink' = IF live = "issuer" THEN "issuer" ELSE sink + /\ stored' = ~(live = "other" \/ temporary + \/ (live = "issuer" /\ result = "rejected")) + /\ lost' = (lost \/ temporary) + +Next == SdkRead \/ ProviderRefresh +Spec == Init /\ [][Next]_vars + +TypeOK == stored \in BOOLEAN /\ lost \in BOOLEAN /\ sink \in {"none", "issuer", "other"} +NoLeak == sink # "other" +NoLostCredential == ~lost +==== diff --git a/docs/architecture/tla/McpOAuthRetry.DiscoveryLoop.cfg b/docs/architecture/tla/McpOAuthRetry.DiscoveryLoop.cfg index 9dd78ce22f5..b309c579b01 100644 --- a/docs/architecture/tla/McpOAuthRetry.DiscoveryLoop.cfg +++ b/docs/architecture/tla/McpOAuthRetry.DiscoveryLoop.cfg @@ -2,4 +2,5 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANT GuardDiscovery = FALSE CONSTANT ResetOnInitialize = FALSE -INVARIANTS Bounded DiscoveryBounded +CONSTANT ResetOnSuccess = TRUE +INVARIANTS TypeOK Bounded Fresh DiscoveryBounded diff --git a/docs/architecture/tla/McpOAuthRetry.NoResetOnSuccess.cfg b/docs/architecture/tla/McpOAuthRetry.NoResetOnSuccess.cfg new file mode 100644 index 00000000000..68cdc6297c2 --- /dev/null +++ b/docs/architecture/tla/McpOAuthRetry.NoResetOnSuccess.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANT GuardDiscovery = TRUE +CONSTANT ResetOnInitialize = FALSE +CONSTANT ResetOnSuccess = FALSE +INVARIANTS TypeOK Bounded Fresh DiscoveryBounded diff --git a/docs/architecture/tla/McpOAuthRetry.ResetOnInitialize.cfg b/docs/architecture/tla/McpOAuthRetry.ResetOnInitialize.cfg index 0243b9f34e3..290f8360f2f 100644 --- a/docs/architecture/tla/McpOAuthRetry.ResetOnInitialize.cfg +++ b/docs/architecture/tla/McpOAuthRetry.ResetOnInitialize.cfg @@ -2,4 +2,5 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANT GuardDiscovery = TRUE CONSTANT ResetOnInitialize = TRUE -INVARIANTS Bounded DiscoveryBounded +CONSTANT ResetOnSuccess = TRUE +INVARIANTS TypeOK Bounded Fresh DiscoveryBounded diff --git a/docs/architecture/tla/McpOAuthRetry.cfg b/docs/architecture/tla/McpOAuthRetry.cfg index a67b63c242c..c0a354bba72 100644 --- a/docs/architecture/tla/McpOAuthRetry.cfg +++ b/docs/architecture/tla/McpOAuthRetry.cfg @@ -2,4 +2,5 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANT GuardDiscovery = TRUE CONSTANT ResetOnInitialize = FALSE -INVARIANTS Bounded DiscoveryBounded +CONSTANT ResetOnSuccess = TRUE +INVARIANTS TypeOK Bounded Fresh DiscoveryBounded diff --git a/docs/architecture/tla/McpOAuthRetry.tla b/docs/architecture/tla/McpOAuthRetry.tla index d8e5ab8061d..38a701230f7 100644 --- a/docs/architecture/tla/McpOAuthRetry.tla +++ b/docs/architecture/tla/McpOAuthRetry.tla @@ -1,16 +1,19 @@ ---- MODULE McpOAuthRetry ---- EXTENDS Naturals -\* Source: McpHub._initiateOAuthFlow receives a rejected saved token. +\* Source: McpHub.performOAuthFlow receives a rejected saved token. \* Sink: reconnectOAuthConnection sends another initialize request. \* Failure: initialize success resets the bound before an authorized request succeeds. -\* Invariant: one unchanged token permits at most two automatic retries in this model. -\* Expect: fixed holds; ResetOnInitialize fails when stream authorization fails later. -\* Review ratchet: PR #2762 supplied findings #4, #14, #23, #24 and #25, added 5. -\* Cost: one agent, one bounded model and two sabotage configurations. -\* Result: fixed holds in 12 states. DiscoveryLoop fails at 9 states. -\* ResetOnInitialize fails at 13 states. The code retry regressions pass. -\* Finding #5: discovery retries require a prior skipped discovery, added 1. -CONSTANT ResetOnInitialize, GuardDiscovery +\* Failure: rejections that successful requests separate still use up one bound (second PR #2762 review, #6). +\* Invariant: Bounded permits two retries without a success. The code constant permits three. +\* Invariant: Fresh counts only the retries since the last successful tool call. +\* Scope: one server and one token key. A changed token and a skipped discovery are events. +\* Property test: src/services/mcp/__tests__/McpHub.spec.ts. +\* Expect: Fixed holds. DiscoveryLoop, ResetOnInitialize, and NoResetOnSuccess each fail. +\* Review ratchet: PR #2762 supplied findings #4, #5, #14, #23, #24 and #25, added 6. +\* The second PR #2762 review supplied finding #6, added 1. +\* Cost: one agent, one bounded model and three sabotage configurations. +\* Result: fixed holds. The three variants fail. The code retry tests pass. +CONSTANT ResetOnInitialize, GuardDiscovery, ResetOnSuccess VARIABLES count, requests, initialized, skippedDiscovery, discoveryRetries vars == <> Init == /\ count = 0 /\ requests = 0 /\ initialized = FALSE @@ -28,6 +31,12 @@ Initialize == /\ count' = IF ResetOnInitialize THEN 0 ELSE count /\ initialized' = TRUE /\ UNCHANGED requests +\* A successful tool call shows that the server accepts the token. +Success == + /\ initialized /\ requests > 0 + /\ count' = IF ResetOnSuccess THEN 0 ELSE count + /\ requests' = 0 + /\ UNCHANGED <> \* A changed access token starts a new retry budget. NewToken == /\ count' = 0 /\ requests' = 0 /\ initialized' = FALSE /\ UNCHANGED <> @@ -37,8 +46,11 @@ NoMetadata == /\ skippedDiscovery' = FALSE /\ discoveryRetries' = discoveryRetries + 1 /\ UNCHANGED <> -DiscoveryBounded == discoveryRetries <= 1 -Next == Reject \/ Initialize \/ NewToken \/ NoMetadata +Next == Reject \/ Initialize \/ Success \/ NewToken \/ NoMetadata Spec == Init /\ [][Next]_vars +TypeOK == /\ count \in 0..2 /\ requests \in 0..3 /\ discoveryRetries \in 0..2 + /\ initialized \in BOOLEAN /\ skippedDiscovery \in BOOLEAN Bounded == requests <= 2 +Fresh == count <= requests +DiscoveryBounded == discoveryRetries <= 1 ==== diff --git a/docs/architecture/tla/McpOAuthStatusHandoff.tla b/docs/architecture/tla/McpOAuthStatusHandoff.tla index b062ee54660..c14d4b98d72 100644 --- a/docs/architecture/tla/McpOAuthStatusHandoff.tla +++ b/docs/architecture/tla/McpOAuthStatusHandoff.tla @@ -17,6 +17,7 @@ EXTENDS Naturals \* (PanelShowsConnected). No additional failure was found. \* Cost: one agent; header correction only. \* Review ratchet: PR #2762 supplied finding #44, added 1. +\* The second PR #2762 review supplied finding #49: the 401 guard now matches onerror, added 1. \* Property test: src/services/mcp/__tests__/mcp-oauth-flow.property.spec.ts. \* Review ratchet: PR #2762 follow-ups B and C. Added 2, covered 0, gap 0. @@ -71,7 +72,7 @@ StreamConnect == HttpError == \E sameTransport \in BOOLEAN, unauthorized \in BOOLEAN : LET allowed == (sameTransport \/ ~GuardTransport) - reauth == unauthorized /\ streamStatus = "connected" + reauth == unauthorized /\ streamStatus # "connecting" generic == ~unauthorized /\ (streamStatus # "connecting" \/ ~GuardConnecting) IN /\ streamStatus' = IF ~allowed THEN streamStatus ELSE IF reauth THEN "connecting" diff --git a/docs/architecture/tla/McpServerToggle.NoResume.cfg b/docs/architecture/tla/McpServerToggle.NoResume.cfg new file mode 100644 index 00000000000..3e6f8ec4aac --- /dev/null +++ b/docs/architecture/tla/McpServerToggle.NoResume.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Serialize = TRUE + Resume = FALSE + GuardRestart = TRUE +INVARIANTS TypeOK Consistent DisabledStays NotStuck diff --git a/docs/architecture/tla/McpServerToggle.UnguardedRestart.cfg b/docs/architecture/tla/McpServerToggle.UnguardedRestart.cfg new file mode 100644 index 00000000000..a5b8bf8805a --- /dev/null +++ b/docs/architecture/tla/McpServerToggle.UnguardedRestart.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Serialize = TRUE + Resume = TRUE + GuardRestart = FALSE +INVARIANTS TypeOK Consistent DisabledStays NotStuck diff --git a/docs/architecture/tla/McpServerToggle.Unordered.cfg b/docs/architecture/tla/McpServerToggle.Unordered.cfg new file mode 100644 index 00000000000..467ba2d2db2 --- /dev/null +++ b/docs/architecture/tla/McpServerToggle.Unordered.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Serialize = FALSE + Resume = TRUE + GuardRestart = TRUE +INVARIANTS TypeOK Consistent DisabledStays NotStuck diff --git a/docs/architecture/tla/McpServerToggle.cfg b/docs/architecture/tla/McpServerToggle.cfg new file mode 100644 index 00000000000..7645b366bdd --- /dev/null +++ b/docs/architecture/tla/McpServerToggle.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Serialize = TRUE + Resume = TRUE + GuardRestart = TRUE +INVARIANTS TypeOK Consistent DisabledStays NotStuck diff --git a/docs/architecture/tla/McpServerToggle.tla b/docs/architecture/tla/McpServerToggle.tla new file mode 100644 index 00000000000..dc89f5cc742 --- /dev/null +++ b/docs/architecture/tla/McpServerToggle.tla @@ -0,0 +1,86 @@ +---- MODULE McpServerToggle ---- +EXTENDS Naturals, Sequences +\* Source: McpHub.toggleServerDisabled requests a value. McpHub.restartConnection waits, then connects. +\* Sink: the settings file, the connection row, and its disabled flag. +\* Failure: two writes commit out of order, or two failed writes keep an unsaved value. +\* Failure: a failed disable stops a connect attempt and leaves the row "connecting". +\* Failure: a restart connects a server that was disabled during its delay. +\* Invariants: Consistent, DisabledStays, NotStuck. Each applies when no work is pending. +\* Scope: one server, two toggle requests, and one restart. The write result is an oracle. +\* Gap: another window or editor writes the settings file during a toggle or restart. +\* Gap: a disable during the restart cleanup finds no row. It fails with a visible error. +\* Gap: updateServerToolList and deleteServer still read the file outside the write lock. +\* Expect: Fixed holds. Unordered, NoResume, and UnguardedRestart each fail. +\* Order: the PR #2762 review came before these invariants. Review ratchet: added 4, gap 0. +\* Property test: src/services/mcp/__tests__/mcp-server-toggle.integration.spec.ts. +\* Result: Fixed holds in 114 states. Unordered, NoResume, and UnguardedRestart fail. +\* The first model failed: an older write did not apply its row. The queue now holds each full toggle. +\* Replay: all six toggle tests fail on the old code and pass on the fix. +\* Cost: one agent; one corrected model, three sabotage configurations. +CONSTANTS Serialize, Resume, GuardRestart +VARIABLES disk, flag, queue, sent, row, restart, removed +vars == <> + +Init == + /\ disk = FALSE /\ flag = FALSE /\ queue = <<>> /\ sent = 0 + /\ row = "connecting" /\ restart = "none" /\ removed = FALSE + +\* A serialized request blocks continuations only when it is first. Without the queue, each blocks at once. +Blocked == flag \/ (Serialize /\ queue # <<>> /\ Head(queue).value) + +Request(value) == + /\ sent < 2 /\ sent' = sent + 1 + /\ queue' = Append(queue, [value |-> value, before |-> flag]) + /\ flag' = IF Serialize THEN flag ELSE (flag \/ value) + /\ UNCHANGED <> + +Without(i) == [j \in 1..(Len(queue) - 1) |-> IF j < i THEN queue[j] ELSE queue[j + 1]] + +\* A failed write restores the flag. The queue makes the restored value equal to the saved value. +Commit(i, ok) == + LET request == queue[i] + IN /\ queue' = Without(i) + /\ disk' = IF ok THEN request.value ELSE disk + /\ flag' = IF ok THEN request.value ELSE IF Serialize THEN flag ELSE request.before + /\ removed' = (removed \/ (ok /\ request.value)) + /\ row' = IF ok /\ request.value THEN "disconnected" + ELSE IF ok /\ row = "disconnected" THEN "connecting" + ELSE IF ~ok /\ Resume /\ row = "abandoned" THEN "disconnected" + ELSE row + /\ UNCHANGED <> + +Write == \E ok \in BOOLEAN : + \E i \in 1..Len(queue) : (i = 1 \/ ~Serialize) /\ Commit(i, ok) + +\* A connect attempt stops at its next check when the server is blocked. +Setup == + /\ row = "connecting" + /\ row' = IF Blocked THEN "abandoned" ELSE "connected" + /\ UNCHANGED <> + +RestartBegin == + /\ restart = "none" /\ ~Blocked + /\ restart' = "delay" /\ removed' = FALSE /\ row' = "connecting" + /\ UNCHANGED <> + +\* The unguarded restart connects with the config that it read before the delay. +RestartResume == + /\ restart = "delay" /\ restart' = "done" + /\ IF GuardRestart /\ (removed \/ Blocked) + THEN UNCHANGED <> + ELSE flag' = FALSE /\ row' = "connecting" + /\ UNCHANGED <> + +Next == (\E value \in BOOLEAN : Request(value)) \/ Write \/ Setup \/ RestartBegin \/ RestartResume +Spec == Init /\ [][Next]_vars + +TypeOK == + /\ disk \in BOOLEAN /\ flag \in BOOLEAN /\ removed \in BOOLEAN + /\ sent \in 0..2 /\ Len(queue) <= 2 + /\ row \in {"connecting", "connected", "disconnected", "abandoned"} + /\ restart \in {"none", "delay", "done"} +Idle == queue = <<>> /\ restart # "delay" +Consistent == Idle => flag = disk +DisabledStays == (Idle /\ disk) => row \in {"disconnected", "abandoned"} +NotStuck == (Idle /\ ~disk) => row # "abandoned" +==== diff --git a/src/core/tools/UseMcpToolTool.ts b/src/core/tools/UseMcpToolTool.ts index 0bd53af3c23..bf95d59b4aa 100644 --- a/src/core/tools/UseMcpToolTool.ts +++ b/src/core/tools/UseMcpToolTool.ts @@ -353,7 +353,10 @@ export class UseMcpToolTool extends BaseTool<"use_mcp_tool"> { toolName, }) - const toolResult = await task.providerRef.deref()?.getMcpHub()?.callTool(serverName, toolName, parsedArguments) + const toolResult = await task.providerRef + .deref() + ?.getMcpHub() + ?.callTool(serverName, toolName, parsedArguments, undefined, () => task.abort) let toolResultPretty = "(No response)" let images: string[] = [] diff --git a/src/core/tools/__tests__/useMcpToolTool.spec.ts b/src/core/tools/__tests__/useMcpToolTool.spec.ts index 0aad69c1729..1ca230d918e 100644 --- a/src/core/tools/__tests__/useMcpToolTool.spec.ts +++ b/src/core/tools/__tests__/useMcpToolTool.spec.ts @@ -302,7 +302,13 @@ describe("useMcpToolTool", () => { expect(mockTask.consecutiveMistakeCount).toBe(0) expect(mockTask.recordToolError).not.toHaveBeenCalled() - expect(callToolMock).toHaveBeenCalledWith("test_server", "test_tool", { headless: true }) + expect(callToolMock).toHaveBeenCalledWith( + "test_server", + "test_tool", + { headless: true }, + undefined, + expect.any(Function), + ) expect(mockTask.say).toHaveBeenCalledWith("mcp_server_request_started") expect(mockTask.say).toHaveBeenCalledWith("mcp_server_response", "Browser session started", []) }) @@ -699,7 +705,13 @@ describe("useMcpToolTool", () => { expect(mockTask.say).toHaveBeenCalledWith("mcp_server_request_started") // The original tool name (with hyphens) should be passed to callTool - expect(callToolMock).toHaveBeenCalledWith("test-server", "get-user-profile", {}) + expect(callToolMock).toHaveBeenCalledWith( + "test-server", + "get-user-profile", + {}, + undefined, + expect.any(Function), + ) }) }) diff --git a/src/i18n/locales/zh-CN/mcp.json b/src/i18n/locales/zh-CN/mcp.json index 6cc8e0b67c8..40a8ded28fd 100644 --- a/src/i18n/locales/zh-CN/mcp.json +++ b/src/i18n/locales/zh-CN/mcp.json @@ -38,7 +38,7 @@ "authenticateButton": "验证身份", "cancelled": "OAuth 身份验证已取消", "timedOut": "OAuth 身份验证已超时", - "retriesExhausted": "{{name}} 的 OAuth 登录在多次重试后失败。请重新连接服务器以再次登录。", + "retriesExhausted": "\"{{name}}\" 的 OAuth 登录在多次重试后失败。请重新连接服务器以再次登录。", "connected": "OAuth 身份验证后,MCP 服务 \"{{name}}\" 已成功连接。" } } diff --git a/src/i18n/locales/zh-TW/mcp.json b/src/i18n/locales/zh-TW/mcp.json index 5246afa57da..b5283d7fe7e 100644 --- a/src/i18n/locales/zh-TW/mcp.json +++ b/src/i18n/locales/zh-TW/mcp.json @@ -38,7 +38,7 @@ "authenticateButton": "驗證身份", "cancelled": "OAuth 身份驗證已取消", "timedOut": "OAuth 身份驗證已逾時", - "retriesExhausted": "{{name}} 的 OAuth 登入在多次重試後失敗。請重新連接伺服器以再次登入。", + "retriesExhausted": "\"{{name}}\" 的 OAuth 登入在多次重試後失敗。請重新連接伺服器以再次登入。", "connected": "OAuth 身份驗證後,MCP 伺服器 \"{{name}}\" 已成功連線。" } } diff --git a/src/services/mcp/McpHub.ts b/src/services/mcp/McpHub.ts index 0a8aaf237ed..ede03be1d15 100644 --- a/src/services/mcp/McpHub.ts +++ b/src/services/mcp/McpHub.ts @@ -210,6 +210,7 @@ export class McpHub { private secretStorage?: SecretStorageService private readonly oauthFlows = new Map() private readonly connectionRemovals = new Map() + private readonly serverToggles = new Map>() /** Tracks rejected-token retries by server, source, URL, and configured OAuth client. */ private oauthTokenRetries: Map = new Map() @@ -731,9 +732,7 @@ export class McpHub { preservedFlow?: McpOAuthFlow, ): Promise { // A later removal also cancels setup before a connection exists. - const removal = preservedFlow - ? this.deleteConnection(name, source, preservedFlow) - : this.deleteConnection(name, source) + const removal = this.deleteConnection(name, source, preservedFlow) const revision = this.connectionRemovals.get(`${name}:${source}`) const isCurrentAttempt = () => !this.isDisposed && @@ -820,19 +819,17 @@ export class McpHub { // Set up stdio specific error handling transport.onerror = async (error) => { console.error(`Transport error for "${name}":`, error) - const connection = this.findConnection(name, source) - if (connection) { - connection.server.status = "disconnected" - this.appendErrorMessage(connection, error instanceof Error ? error.message : `${error}`) - } + const connection = this.findTransportConnection(name, source, transport) + if (!connection) return + connection.server.status = "disconnected" + this.appendErrorMessage(connection, error instanceof Error ? error.message : `${error}`) await this.notifyWebviewOfServerChanges() } transport.onclose = async () => { - const connection = this.findConnection(name, source) - if (connection) { - connection.server.status = "disconnected" - } + const connection = this.findTransportConnection(name, source, transport) + if (!connection) return + connection.server.status = "disconnected" await this.notifyWebviewOfServerChanges() } @@ -852,7 +849,7 @@ export class McpHub { } else { // Treat as error log console.error(`Server "${name}" stderr:`, output) - const connection = this.findConnection(name, source) + const connection = this.findTransportConnection(name, source, transport) if (connection) { this.appendErrorMessage(connection, output) if (connection.server.status === "disconnected") { @@ -929,7 +926,6 @@ export class McpHub { source, JSON.parse(connection.server.config), authProvider, - transport as StreamableHTTPClientTransport, connection, ) return @@ -941,21 +937,13 @@ export class McpHub { } transport.onclose = async () => { - const connection = this.findConnection(name, source) - if ( - connection && - connection.type === "connected" && - connection.transport === transport && - this.isCurrentOAuthConnection(connection) - ) { - // If OAuth is in progress, don't overwrite "connecting" with "disconnected". - // The transport will close/retry while we await the browser flow or poll; - // the reconnect path (deleteConnection + connectToServer) handles cleanup. - if (connection.server.status === "connecting") { - return - } - connection.server.status = "disconnected" - } + const connection = this.findTransportConnection(name, source, transport) + if (!connection || !this.isCurrentOAuthConnection(connection)) return + // If OAuth is in progress, don't overwrite "connecting" with "disconnected". + // The transport will close/retry while we await the browser flow or poll; + // the reconnect path (deleteConnection + connectToServer) handles cleanup. + if (connection.server.status === "connecting") return + connection.server.status = "disconnected" await this.notifyWebviewOfServerChanges() } @@ -989,19 +977,17 @@ export class McpHub { // Set up SSE specific error handling transport.onerror = async (error) => { console.error(`Transport error for "${name}":`, error) - const connection = this.findConnection(name, source) - if (connection) { - connection.server.status = "disconnected" - this.appendErrorMessage(connection, error instanceof Error ? error.message : `${error}`) - } + const connection = this.findTransportConnection(name, source, transport) + if (!connection) return + connection.server.status = "disconnected" + this.appendErrorMessage(connection, error instanceof Error ? error.message : `${error}`) await this.notifyWebviewOfServerChanges() } transport.onclose = async () => { - const connection = this.findConnection(name, source) - if (connection) { - connection.server.status = "disconnected" - } + const connection = this.findTransportConnection(name, source, transport) + if (!connection) return + connection.server.status = "disconnected" await this.notifyWebviewOfServerChanges() } } else { @@ -1062,14 +1048,7 @@ export class McpHub { // waitUntilReady() resolves immediately and the MCP panel can load. connection.server.status = "connecting" - void this._initiateOAuthFlow( - name, - source, - configInjected, - streamableHttpAuthProvider, - transport as StreamableHTTPClientTransport, - connection, - ) + void this._initiateOAuthFlow(name, source, configInjected, streamableHttpAuthProvider, connection) return } @@ -1090,17 +1069,13 @@ export class McpHub { // The list requests below can each take up to the request timeout. Update // the panel now so the server shows connected immediately, then update it // again when the tool, resource, and template lists arrive. - await this.notifyWebviewOfServerChanges().catch((error: unknown) => { - console.error("[McpHub] Failed to update the MCP panel:", error) - }) + await this.tryNotifyWebview() // Initial fetch of tools and resources connection.server.tools = await this.fetchToolsList(name, source) connection.server.resources = await this.fetchResourcesList(name, source) connection.server.resourceTemplates = await this.fetchResourceTemplatesList(name, source) - await this.notifyWebviewOfServerChanges().catch((error: unknown) => { - console.error("[McpHub] Failed to update the MCP panel:", error) - }) + await this.tryNotifyWebview() } catch (error) { await pendingAuthProvider?.close() // Update status with error @@ -1113,6 +1088,16 @@ export class McpHub { } } + /** Returns the row that owns the transport, so a replaced transport cannot change a new row. */ + private findTransportConnection( + name: string, + source: "global" | "project", + transport: unknown, + ): ConnectedMcpConnection | undefined { + const connection = this.findConnection(name, source) + return connection?.type === "connected" && connection.transport === transport ? connection : undefined + } + private isCurrentOAuthConnection(connection: ConnectedMcpConnection): boolean { return ( !this.isDisposed && @@ -1121,55 +1106,50 @@ export class McpHub { ) } + /** Replaces a cancelled reconnect attempt with an error row, unless a later removal owns the name. */ private stopOAuthReconnect( - connection: ConnectedMcpConnection, + name: string, + source: "global" | "project", config: z.infer, revision: number | undefined, - reason: unknown, ): void { - const { name } = connection.server - const source = connection.server.source ?? "global" - const key = `${name}:${source}` - if (this.connectionRemovals.get(key) !== revision) return + if (this.connectionRemovals.get(`${name}:${source}`) !== revision) return const current = this.findConnection(name, source) - if ( - current && - (current.type !== "connected" || current.server.status !== "connecting" || this.oauthFlows.has(current)) - ) - return + if (current && current.server.status !== "connecting") return // Detach first, then publish the error row before resource cleanup can yield. - const removal = this.deleteConnection(name, source) - if (reason === "cancelled" || reason === "timed-out") { - const stopped = this.createPlaceholderConnection(name, config, source) - this.appendErrorMessage( - stopped, - t(reason === "cancelled" ? "mcp:oauth.flow.cancelled" : "mcp:oauth.flow.timedOut"), - ) - this.connections.push(stopped) - this.sanitizedNameRegistry.set(sanitizeMcpName(name), name) - void this.notifyWebviewOfServerChanges().catch((error: unknown) => - console.error("[McpHub] Failed to update the MCP panel:", error), - ) - } - void removal.catch((error: unknown) => console.error("[McpHub] OAuth reconnect cleanup failed:", error)) + void this.deleteConnection(name, source) + this.addStoppedConnection(name, config, source, t("mcp:oauth.flow.cancelled")) + void this.tryNotifyWebview() + } + + /** Adds a disconnected row that shows the error and permits a restart. */ + private addStoppedConnection( + name: string, + config: z.infer, + source: "global" | "project", + message: string, + ): void { + const stopped = this.createPlaceholderConnection(name, config, source) + this.appendErrorMessage(stopped, message) + this.connections.push(stopped) + this.sanitizedNameRegistry.set(sanitizeMcpName(name), name) } private async reconnectOAuthConnection( connection: ConnectedMcpConnection, config: z.infer, - flow = this.oauthFlows.get(connection), + flow?: McpOAuthFlow, ): Promise { const isFlowActive = () => flow?.phase !== "ended" const canContinue = () => isFlowActive() && this.isCurrentOAuthConnection(connection) if (!canContinue()) return false - flow?.beginReconnect() await connection.authProvider?.close() if (!canContinue()) return false const { name } = connection.server const source = connection.server.source ?? "global" const validatedConfig = this.validateServerConfig(config, name) const key = `${name}:${source}` - const removal = flow ? this.deleteConnection(name, source, flow) : this.deleteConnection(name, source) + const removal = this.deleteConnection(name, source, flow) const revision = this.connectionRemovals.get(key) await removal if ( @@ -1179,22 +1159,38 @@ export class McpHub { this.connectionRemovals.get(key) !== revision ) return false - if (this.findConnection(name, source)) return false const reconnect = this.connectToServer(name, validatedConfig, source, flow) const reconnectRevision = this.connectionRemovals.get(key) - if (flow) { - const abortSetup = () => - this.stopOAuthReconnect(connection, validatedConfig, reconnectRevision, flow.signal.reason) - flow.signal.addEventListener("abort", abortSetup, { once: true }) - flow.addCleanup(() => flow.signal.removeEventListener("abort", abortSetup)) - if (flow.signal.aborted) abortSetup() - } - await reconnect - const replacement = this.findConnection(name, source) - await this.notifyWebviewOfServerChanges() + // A cancellation stops this setup. Other outcomes come from an owner that already handles the row. + flow?.addCleanup((outcome) => { + if (outcome === "cancelled") this.stopOAuthReconnect(name, source, validatedConfig, reconnectRevision) + }) + let replacement: McpConnection | undefined + try { + await reconnect + replacement = this.findConnection(name, source) + } catch (error) { + console.error(`[McpHub] OAuth reconnect failed for "${name}" (${source}):`, error) + // A failure before the new row exists must not remove the server from the panel. + if ( + isFlowActive() && + !this.isDisposed && + this.connectionRemovals.get(key) === reconnectRevision && + !this.findConnection(name, source) + ) { + this.addStoppedConnection( + name, + validatedConfig, + source, + error instanceof Error ? error.message : String(error), + ) + } + throw error + } finally { + await this.tryNotifyWebview() + } return ( replacement?.type === "connected" && - replacement !== connection && isFlowActive() && replacement.server.status === "connected" && this.isCurrentOAuthConnection(replacement) @@ -1224,21 +1220,16 @@ export class McpHub { source: "global" | "project", config: z.infer, authProvider: McpOAuthClientProvider, - transport: StreamableHTTPClientTransport, connection: ConnectedMcpConnection, ): Promise { const existing = this.oauthFlows.get(connection) if (existing) return existing.promise if (!this.isCurrentOAuthConnection(connection)) return Promise.resolve("removed") const flow = this.createOAuthFlow(connection, authProvider) - void this.performOAuthFlow(name, source, config, authProvider, transport, connection, flow) + void this.performOAuthFlow(name, source, config, authProvider, connection, flow) .catch(async (error: unknown) => { console.error(`[McpHub] OAuth flow failed for "${name}":`, error) - await this._surfaceOAuthReconnectFailure( - connection, - error instanceof Error ? error.message : String(error), - ) - flow.finish("failed") + await this._failOAuthFlow(connection, flow, error) }) .finally(() => flow.finish("failed")) return flow.promise @@ -1249,16 +1240,13 @@ export class McpHub { source: "global" | "project", config: z.infer, authProvider: McpOAuthClientProvider, - transport: StreamableHTTPClientTransport, connection: ConnectedMcpConnection, flow: McpOAuthFlow, ): Promise { const serverUrl = "url" in config ? config.url : undefined const oauthClientId = config.type === "streamable-http" ? config.oauth?.clientId : undefined - if (!serverUrl || !this.secretStorage) { - flow.finish("failed") - return - } + // The caller ends a flow that returns without an outcome as "failed". + if (!serverUrl || !this.secretStorage) return let tokenChangedDuringRead = false const unsubscribe = flow.addCleanup( this.secretStorage.onDidChange( @@ -1272,7 +1260,7 @@ export class McpHub { let tokenToUse: Awaited> try { tokenToUse = await this.secretStorage.getOAuthData(serverUrl, oauthClientId) - if (flow.phase !== "ended" && !tokenToUse && tokenChangedDuringRead) { + if (flow.phase !== "ended" && tokenChangedDuringRead) { tokenToUse = await this.secretStorage.getOAuthData(serverUrl, oauthClientId) } } finally { @@ -1282,15 +1270,14 @@ export class McpHub { flow.finish("removed") return } - if (tokenToUse && Date.now() < tokenToUse.expires_at - TOKEN_EXPIRY_BUFFER_MS) { - const tokenKey = tokenToUse.tokens?.access_token - const retryKey = JSON.stringify([name, source, serverUrl, oauthClientId]) + if (tokenToUse && this.isFreshToken(tokenToUse)) { + const tokenKey = JSON.stringify([serverUrl, oauthClientId, tokenToUse.tokens?.access_token]) + const retryKey = `${name}:${source}` const retryState = this.oauthTokenRetries.get(retryKey) const attempt = retryState && retryState.tokenKey === tokenKey ? retryState.count + 1 : 1 if (attempt > OAUTH_TOKEN_RETRY_MAX_ATTEMPTS) { console.warn(`[McpHub] OAuth token retries exhausted for "${name}" (${source})`) - await this._surfaceOAuthReconnectFailure(connection, t("mcp:oauth.flow.retriesExhausted", { name })) - flow.finish("failed") + await this._failOAuthFlow(connection, flow, t("mcp:oauth.flow.retriesExhausted", { name })) return } this.oauthTokenRetries.set(retryKey, { tokenKey, count: attempt }) @@ -1313,7 +1300,6 @@ export class McpHub { config, serverUrl, authProvider, - transport, connection, progress, cancellationToken, @@ -1323,10 +1309,28 @@ export class McpHub { ) } - private async _surfaceOAuthReconnectFailure(connection: ConnectedMcpConnection, message: string): Promise { - if (!this.isCurrentOAuthConnection(connection) || connection.server.status === "connected") return - connection.server.status = "disconnected" - this.appendErrorMessage(connection, message) + private isFreshToken(data: { expires_at: number }): boolean { + return Date.now() < data.expires_at - TOKEN_EXPIRY_BUFFER_MS + } + + /** Shows the error and ends the flow in one synchronous step, then waits for the panel update. */ + private async _failOAuthFlow( + connection: ConnectedMcpConnection, + flow: McpOAuthFlow, + error: unknown, + outcome: McpOAuthFlowOutcome = "failed", + ): Promise { + if (flow.phase === "ended") return + const visible = this.isCurrentOAuthConnection(connection) && connection.server.status !== "connected" + if (visible) { + connection.server.status = "disconnected" + this.appendErrorMessage(connection, error instanceof Error ? error.message : String(error)) + } + flow.finish(outcome) + if (visible) await this.tryNotifyWebview() + } + + private async tryNotifyWebview(): Promise { await this.notifyWebviewOfServerChanges().catch((error: unknown) => console.error("[McpHub] Failed to update the MCP panel:", error), ) @@ -1338,27 +1342,18 @@ export class McpHub { config: z.infer, serverUrl: string, authProvider: McpOAuthClientProvider, - transport: StreamableHTTPClientTransport, connection: ConnectedMcpConnection, progress: vscode.Progress<{ message?: string; increment?: number }>, cancellationToken: vscode.CancellationToken, - oauthClientId?: string, - existingFlow?: McpOAuthFlow, + oauthClientId: string | undefined, + flow: McpOAuthFlow, ): Promise { if (!this.isCurrentOAuthConnection(connection)) return Promise.resolve() - const flow = existingFlow ?? this.createOAuthFlow(connection, authProvider) - const fail = async (message: string, outcome: "failed" | "cancelled" | "timed-out") => { - if (flow.phase === "ended") return - const surfaced = this._surfaceOAuthReconnectFailure(connection, message) - flow.finish(outcome) - await surfaced - } + const fail = (error: unknown, outcome?: McpOAuthFlowOutcome) => + this._failOAuthFlow(connection, flow, error, outcome) const run = (work: () => Promise) => { if (!flow.claim()) return - void work().then( - (connected) => flow.finish(connected ? "connected" : "failed"), - (error: unknown) => fail(error instanceof Error ? error.message : String(error), "failed"), - ) + void work().then((connected) => flow.finish(connected ? "connected" : "failed"), fail) } flow.addCleanup( this.secretStorage!.onDidChange( @@ -1367,11 +1362,15 @@ export class McpHub { if (flow.phase !== "waiting") return void this.secretStorage!.getOAuthData(serverUrl, oauthClientId).then( (data) => { - if (data && Date.now() < data.expires_at - TOKEN_EXPIRY_BUFFER_MS) { + if (data && this.isFreshToken(data)) { run(() => this.reconnectOAuthConnection(connection, config, flow)) } }, - (error: unknown) => fail(error instanceof Error ? error.message : String(error), "failed"), + (error: unknown) => { + // A claimed flow has another owner, so a late read error must not end it. + if (flow.phase !== "waiting") return + return fail(error) + }, ) }, oauthClientId, @@ -1388,7 +1387,7 @@ export class McpHub { void fail(t("mcp:oauth.flow.cancelled"), "cancelled") } if (process.env.MCP_OAUTH_TEST_MODE === "true") { - run(() => this._completeOAuthFlow(authProvider, transport, connection, name, source, cancellationToken)) + run(() => this._completeOAuthFlow(authProvider, connection, flow)) } else { const authenticateLabel = t("mcp:oauth.flow.authenticateButton") void Promise.resolve( @@ -1396,79 +1395,55 @@ export class McpHub { t("mcp:oauth.flow.clickAuthenticate", { name }), authenticateLabel, ), - ).then( - (choice) => { - if (flow.phase !== "waiting") return - if (choice !== authenticateLabel) { - progress.report({ message: t("mcp:oauth.flow.dismissedHint") }) - return - } - run(async () => { - const tokens = await this.secretStorage!.getOAuthData(serverUrl, oauthClientId) - if (flow.phase === "ended") return false - if (tokens && Date.now() < tokens.expires_at - TOKEN_EXPIRY_BUFFER_MS) - return this.reconnectOAuthConnection(connection, config, flow) - return this._completeOAuthFlow( - authProvider, - transport, - connection, - name, - source, - cancellationToken, - ) - }) - }, - (error: unknown) => fail(error instanceof Error ? error.message : String(error), "failed"), - ) + ).then((choice) => { + if (flow.phase !== "waiting") return + if (choice !== authenticateLabel) { + progress.report({ message: t("mcp:oauth.flow.dismissedHint") }) + return + } + run(async () => { + const tokens = await this.secretStorage!.getOAuthData(serverUrl, oauthClientId) + if (flow.phase === "ended") return false + if (tokens && this.isFreshToken(tokens)) + return this.reconnectOAuthConnection(connection, config, flow) + return this._completeOAuthFlow(authProvider, connection, flow) + }) + }, fail) } return flow.promise.then(() => {}) } private async _completeOAuthFlow( authProvider: McpOAuthClientProvider, - _transport: StreamableHTTPClientTransport, connection: ConnectedMcpConnection, - name: string, - source: "global" | "project", - cancellationToken: vscode.CancellationToken, + flow: McpOAuthFlow, ): Promise { - const flow = this.oauthFlows.get(connection) - const canContinue = () => - flow?.phase !== "ended" && - !cancellationToken.isCancellationRequested && - this.isCurrentOAuthConnection(connection) + const canContinue = () => flow.phase !== "ended" && this.isCurrentOAuthConnection(connection) if (!canContinue()) return false - let cancelListener: vscode.Disposable | undefined - const cancelled = new Promise((_, reject) => { - cancelListener = cancellationToken.onCancellationRequested(() => - reject(new Error(t("mcp:oauth.flow.cancelled"))), - ) - }) try { const authorization = async () => { await authProvider.openBrowser() if (!canContinue()) return undefined return authProvider.waitForAuthCode() } - const code = await Promise.race([authorization(), cancelled]) + // A cancel, removal, or dispose ends the flow and releases this wait. + const code = await Promise.race([authorization(), flow.promise.then(() => undefined)]) if (!canContinue() || !code) return false - await authProvider.exchangeCodeForTokens(code) + await authProvider.exchangeCodeForTokens(code, canContinue) if (!canContinue()) return false const connected = await this.reconnectOAuthConnection( connection, JSON.parse(connection.server.config), flow, ) - if (connected && flow?.phase !== "ended") + if (connected && flow.phase !== "ended") { + const { name } = connection.server void vscode.window.showInformationMessage(t("mcp:oauth.flow.connected", { name })) + } return connected } catch (error) { - if (flow?.phase === "ended") return false - await this._surfaceOAuthReconnectFailure(connection, error instanceof Error ? error.message : String(error)) + await this._failOAuthFlow(connection, flow, error) return false - } finally { - cancelListener?.dispose() - if (!flow) await authProvider.close() } } @@ -1697,8 +1672,11 @@ export class McpHub { const currentNames = new Set(currentConnections.map((conn) => conn.server.name)) const newNames = new Set(Object.keys(newServers)) - // Delete removed servers - for (const name of currentNames) { + // Delete removed servers. A server in setup has no row yet, but it has a removal revision. + const attemptedNames = [...this.connectionRemovals.keys()] + .filter((key) => key.endsWith(`:${source}`)) + .map((key) => key.slice(0, -(source.length + 1))) + for (const name of new Set([...currentNames, ...attemptedNames])) { if (!newNames.has(name)) { await this.deleteConnection(name, source) } @@ -1845,8 +1823,19 @@ export class McpHub { connection.server.error = "" await this.notifyWebviewOfServerChanges() await delay(500) // artificial delay to show user that server is restarting + // A disable or removal during the delay wins over the restart. + if ( + this.findConnection(serverName, connection.server.source) !== connection || + connection.server.disabled + ) { + this.isConnecting = false + return + } try { - await this.deleteConnection(serverName, connection.server.source) + const removal = this.deleteConnection(serverName, connection.server.source) + const key = `${serverName}:${connection.server.source ?? "global"}` + const revision = this.connectionRemovals.get(key) + await removal // Parse the config to validate it const parsedConfig = JSON.parse(config) try { @@ -1858,6 +1847,11 @@ export class McpHub { await this.secretStorage.deleteOAuthData(validatedConfig.url, validatedConfig.oauth?.clientId) } + if (this.connectionRemovals.get(key) !== revision) { + this.isConnecting = false + return + } + // Try to connect again using validated config await this.connectToServer(serverName, validatedConfig, connection.server.source || "global") vscode.window.showInformationMessage(t("mcp:info.server_connected", { serverName })) @@ -1998,7 +1992,15 @@ export class McpHub { } } - public async toggleServerDisabled( + public toggleServerDisabled(serverName: string, disabled: boolean, source?: "global" | "project"): Promise { + // Run the toggles for one server in request order, so the file and the row agree. + const previous = this.serverToggles.get(serverName) ?? Promise.resolve() + const toggle = previous.catch(() => {}).then(() => this.applyServerToggle(serverName, disabled, source)) + this.serverToggles.set(serverName, toggle) + return toggle + } + + private async applyServerToggle( serverName: string, disabled: boolean, source?: "global" | "project", @@ -2018,6 +2020,17 @@ export class McpHub { await this.updateServerConfig(serverName, { disabled }, serverSource) } catch (error) { connection.server.disabled = wasDisabled + // A connect attempt can stop while the flag blocks it. Do not leave its row "connecting". + if ( + disabled && + connection.server.status === "connecting" && + !this.oauthFlows.has(connection as ConnectedMcpConnection) && + this.findConnection(serverName, serverSource) === connection + ) { + connection.server.status = "disconnected" + this.appendErrorMessage(connection, error instanceof Error ? error.message : String(error)) + await this.notifyWebviewOfServerChanges() + } throw error } if (this.findConnection(serverName, serverSource) !== connection) return @@ -2027,8 +2040,8 @@ export class McpHub { try { connection.server.disabled = disabled - // If disabling a connected server, disconnect it - if (disabled && connection.server.status !== "disconnected") { + // Disconnect a server that has a live transport or an active attempt + if (disabled && (connection.type === "connected" || connection.server.status !== "disconnected")) { // Clean up file watchers when disabling this.removeFileWatchersForServer(serverName) await this.deleteConnection(serverName, serverSource) @@ -2146,39 +2159,24 @@ export class McpHub { throw new Error("Settings file not accessible") } - // Read and parse the config file - const content = await fs.readFile(configPath, "utf-8") - const config = JSON.parse(content) - - // Validate the config structure - if (!config || typeof config !== "object") { - throw new Error("Invalid config structure") - } - - if (!config.mcpServers || typeof config.mcpServers !== "object") { - config.mcpServers = {} - } - - if (!config.mcpServers[serverName]) { - config.mcpServers[serverName] = {} - } - - // Create a new server config object to ensure clean structure - const serverConfig = { - ...config.mcpServers[serverName], - ...configUpdate, - } - - // Ensure required fields exist - if (!serverConfig.alwaysAllow) { - serverConfig.alwaysAllow = [] - } + // The merge callback runs under the file lock, so another writer cannot lose its change. + const merge = (existing: unknown) => { + const config = z + .object({ mcpServers: z.record(z.string(), z.record(z.string(), z.unknown())) }) + .safeParse(existing) + if (!config.success) { + throw new Error("Invalid config structure") + } + const { mcpServers } = config.data + if (!mcpServers[serverName]) { + throw new Error(`Server ${serverName} not found in config`) + } - config.mcpServers[serverName] = serverConfig + const serverConfig = { ...mcpServers[serverName], ...configUpdate } + // Ensure required fields exist + serverConfig.alwaysAllow ||= [] - // Write the entire config back - const updatedConfig = { - mcpServers: config.mcpServers, + return { mcpServers: { ...mcpServers, [serverName]: serverConfig } } } // Set flag to prevent file watcher from triggering server restart @@ -2187,7 +2185,7 @@ export class McpHub { } this.isProgrammaticUpdate = true try { - await safeWriteJson(configPath, updatedConfig, { prettyPrint: true }) + await safeWriteJson(configPath, {}, { prettyPrint: true, merge }) } finally { // Reset flag after watcher debounce period (non-blocking) this.flagResetTimer = setTimeout(() => { @@ -2311,6 +2309,7 @@ export class McpHub { toolName: string, toolArguments?: Record, source?: "global" | "project", + isAborted?: () => boolean, ): Promise { const connection = this.findConnection(serverName, source) if (!connection || connection.type !== "connected") { @@ -2332,8 +2331,10 @@ export class McpHub { timeout = 60 * 1000 } - try { - return await connection.client.request( + const retryKey = `${serverName}:${source ?? connection.server.source ?? "global"}` + // A successful call shows that the server accepts the token, so the retry bound starts again. + const request = async (target: ConnectedMcpConnection) => { + const result = await target.client.request( { method: "tools/call", params: { @@ -2346,6 +2347,12 @@ export class McpHub { timeout, }, ) + this.oauthTokenRetries.delete(retryKey) + return result + } + + try { + return await request(connection) } catch (error) { if (error instanceof UnauthorizedError && connection.authProvider) { // Mid-session re-auth triggered by a tool call (401) @@ -2356,7 +2363,6 @@ export class McpHub { source ?? connection.server.source ?? "global", JSON.parse(connection.server.config), connection.authProvider, - connection.transport as StreamableHTTPClientTransport, connection, ) @@ -2366,28 +2372,19 @@ export class McpHub { if ( outcome !== "connected" || !newConnection || - newConnection === connection || newConnection.type !== "connected" || newConnection.server.status !== "connected" || !this.isCurrentOAuthConnection(newConnection) ) { - throw new Error(`Failed to reconnect to server ${serverName} after OAuth`) + throw new Error(`Failed to reconnect to server ${serverName} after OAuth (outcome: ${outcome})`) + } + // The sign-in can take minutes. Do not run the tool for a task that stopped. + if (isAborted?.()) { + throw new Error(`The task stopped before the tool call to server ${serverName} could run again`) } try { - return await newConnection.client.request( - { - method: "tools/call", - params: { - name: toolName, - arguments: toolArguments, - }, - }, - CallToolResultSchema, - { - timeout, - }, - ) + return await request(newConnection) } catch (retryError) { if (retryError instanceof UnauthorizedError) { throw new Error( diff --git a/src/services/mcp/McpOAuthClientProvider.ts b/src/services/mcp/McpOAuthClientProvider.ts index e1c4bc5d6d6..0389d21b109 100644 --- a/src/services/mcp/McpOAuthClientProvider.ts +++ b/src/services/mcp/McpOAuthClientProvider.ts @@ -381,7 +381,18 @@ export class McpOAuthClientProvider implements OAuthClientProvider { this._clientInfo = (await response.json()) as OAuthClientInformationFull } + /** + * Returns the tokens without the refresh token. After a 401 the SDK refreshes at a server that + * it discovers from server-controlled metadata, so only this provider uses the refresh token. + */ async tokens(): Promise { + const tokens = await this._loadTokens() + if (!tokens) return undefined + const { refresh_token: _refreshToken, ...accessTokens } = tokens + return accessTokens + } + + private async _loadTokens(): Promise { const data = await this._secretStorage.getOAuthData(this._serverUrl, this._configuredClientId) if (!data) return undefined @@ -392,9 +403,12 @@ export class McpOAuthClientProvider implements OAuthClientProvider { // Access token is expired or near expiry. Try to refresh if we have a refresh token. if (data.tokens.refresh_token) { + // Without discovery the issuer is unknown. Keep the data for a later attempt. + if (!this._authServerMeta) return undefined + // Never send the refresh token to an authorization server other than the one // that issued it. Data without an issuer (saved by older versions) is cleared. - if (data.issuer !== this._authServerMeta?.issuer) { + if (data.issuer !== this._authServerMeta.issuer) { await this._secretStorage.deleteOAuthData(this._serverUrl, this._configuredClientId) return undefined } @@ -424,8 +438,13 @@ export class McpOAuthClientProvider implements OAuthClientProvider { return await this._refreshPromise } catch (error) { console.error(`Failed to refresh MCP OAuth token for ${this._serverUrl}:`, error) - // Clear stale tokens on refresh failure so we don't keep retrying a dead refresh token - await this._secretStorage.deleteOAuthData(this._serverUrl, this._configuredClientId) + // Delete only a refresh token that the server rejected. A temporary error keeps it. + if (error instanceof Error && error.message.includes("invalid_grant")) { + const current = await this._secretStorage.getOAuthData(this._serverUrl, this._configuredClientId) + if (current?.tokens.refresh_token === data.tokens.refresh_token) { + await this._secretStorage.deleteOAuthData(this._serverUrl, this._configuredClientId) + } + } // Fall through to return undefined, which triggers full re-auth } } @@ -537,6 +556,10 @@ export class McpOAuthClientProvider implements OAuthClientProvider { if (!url) { throw new Error("No pending authorization URL — redirectToAuthorization() was not called") } + // The server controls the metadata, so open only a web address. + if (url.protocol !== "https:" && url.protocol !== "http:") { + throw new Error(`The authorization URL uses an unsupported scheme: ${url.protocol}`) + } try { await vscode.env.openExternal(vscode.Uri.parse(url.toString())) } catch { @@ -594,7 +617,7 @@ export class McpOAuthClientProvider implements OAuthClientProvider { * @param authorizationCode The code received in the OAuth callback redirect. * @throws When the token endpoint is unknown or the exchange request fails. */ - async exchangeCodeForTokens(authorizationCode: string): Promise { + async exchangeCodeForTokens(authorizationCode: string, canSave = () => true): Promise { if (!this._authServerMeta?.token_endpoint) { throw new Error("No token_endpoint in auth server metadata — cannot exchange code") } @@ -638,6 +661,8 @@ export class McpOAuthClientProvider implements OAuthClientProvider { } const tokens = (await response.json()) as OAuthTokens + // A deleted, disabled, or cancelled sign-in must not save its token. + if (!canSave()) return await this.saveTokens(tokens) } diff --git a/src/services/mcp/McpOAuthFlow.ts b/src/services/mcp/McpOAuthFlow.ts index 367afbfa4cb..d464d1faba0 100644 --- a/src/services/mcp/McpOAuthFlow.ts +++ b/src/services/mcp/McpOAuthFlow.ts @@ -1,6 +1,8 @@ export type McpOAuthFlowOutcome = "connected" | "cancelled" | "timed-out" | "removed" | "failed" -type McpOAuthFlowPhase = "waiting" | "authenticating" | "reconnecting" | "ended" +type McpOAuthFlowPhase = "waiting" | "authenticating" | "ended" +/** The outcome is undefined when the owner disposes a cleanup before the flow ends. */ +type Cleanup = (outcome?: McpOAuthFlowOutcome) => void /** Owns one OAuth attempt, including its listeners and completion promise. */ export class McpOAuthFlow { @@ -10,12 +12,8 @@ export class McpOAuthFlow { return this.currentPhase } readonly promise: Promise - private readonly cancellation = new AbortController() - get signal(): AbortSignal { - return this.cancellation.signal - } private resolve!: (outcome: McpOAuthFlowOutcome) => void - private readonly cleanups: Array<() => void> = [] + private readonly cleanups: Cleanup[] = [] constructor() { this.promise = new Promise((resolve) => { @@ -23,14 +21,14 @@ export class McpOAuthFlow { }) } - addCleanup(cleanup: () => void): () => void { + addCleanup(cleanup: Cleanup): () => void { let active = true - const dispose = () => { + const dispose: Cleanup = (outcome) => { if (!active) return active = false const index = this.cleanups.indexOf(dispose) if (index !== -1) this.cleanups.splice(index, 1) - cleanup() + cleanup(outcome) } if (this.phase === "ended") dispose() else this.cleanups.push(dispose) @@ -51,29 +49,23 @@ export class McpOAuthFlow { this.waitingTimeout = undefined } - private transitionTo(phase: Exclude): boolean { - if (this.phase === "ended") return false + private transitionTo(phase: "authenticating" | "ended"): void { this.clearWaitingTimeout() this.currentPhase = phase - return true - } - - beginReconnect(): void { - this.transitionTo("reconnecting") } claim(): boolean { if (this.phase !== "waiting") return false - return this.transitionTo("authenticating") + this.transitionTo("authenticating") + return true } finish(outcome: McpOAuthFlowOutcome): void { - if (!this.transitionTo("ended")) return - if (outcome === "cancelled" || outcome === "timed-out" || outcome === "removed") - this.cancellation.abort(outcome) + if (this.phase === "ended") return + this.transitionTo("ended") for (const cleanup of this.cleanups.splice(0).reverse()) { try { - cleanup() + cleanup(outcome) } catch (error) { console.error("[McpHub] OAuth flow cleanup failed:", error) } diff --git a/src/services/mcp/__tests__/McpHub.spec.ts b/src/services/mcp/__tests__/McpHub.spec.ts index 66c61180226..161a155eae4 100644 --- a/src/services/mcp/__tests__/McpHub.spec.ts +++ b/src/services/mcp/__tests__/McpHub.spec.ts @@ -2946,14 +2946,7 @@ describe("McpHub", () => { vsc.window.showInformationMessage.mockResolvedValueOnce(t("mcp:oauth.flow.authenticateButton") as any) vi.spyOn(mcpHub as any, "_completeOAuthFlow").mockResolvedValue(undefined) - await (mcpHub as any)._initiateOAuthFlow( - serverName, - source, - config, - mockAuthProvider, - mockTransport, - mockConnection, - ) + await (mcpHub as any)._initiateOAuthFlow(serverName, source, config, mockAuthProvider, mockConnection) expect(vsc.window.withProgress).toHaveBeenCalledWith( expect.objectContaining({ @@ -2984,7 +2977,6 @@ describe("McpHub", () => { source, config, mockAuthProvider, - mockTransport, mockConnection, ) @@ -3012,14 +3004,7 @@ describe("McpHub", () => { return vi.fn() }) - await (mcpHub as any)._initiateOAuthFlow( - serverName, - source, - config, - mockAuthProvider, - mockTransport, - mockConnection, - ) + await (mcpHub as any)._initiateOAuthFlow(serverName, source, config, mockAuthProvider, mockConnection) expect(mockAuthProvider.close).toHaveBeenCalled() expect((mcpHub as any).deleteConnection).toHaveBeenCalledWith(serverName, source, expect.any(McpOAuthFlow)) @@ -3031,14 +3016,7 @@ describe("McpHub", () => { expires_at: Date.now() + 10 * 60 * 1000, }) - await (mcpHub as any)._initiateOAuthFlow( - serverName, - source, - config, - mockAuthProvider, - mockTransport, - mockConnection, - ) + await (mcpHub as any)._initiateOAuthFlow(serverName, source, config, mockAuthProvider, mockConnection) expect(vsc.window.withProgress).not.toHaveBeenCalled() expect(mockAuthProvider.close).toHaveBeenCalled() @@ -3068,7 +3046,6 @@ describe("McpHub", () => { source, config, mockAuthProvider, - mockTransport, mockConnection, ) @@ -3085,13 +3062,8 @@ describe("McpHub", () => { }) it("should handle a token that is already cancelled at listener registration time", async () => { - // Regression: VS Code's CancellationToken.onCancellationRequested() fires the - // callback synchronously inside the registration call when the token is already - // cancelled. If cleanup() captures `const cancellationDisposable = onCancellationRequested(...)` - // from outer scope, the callback runs while that binding is still in the temporal - // dead zone and accessing it throws ReferenceError. cleanup() must therefore - // receive the disposable as a parameter and the cancellation callback must invoke - // cleanup() without it. + // Regression: VS Code can run the cancellation callback during registration. + // The flow must end and keep no registry entry. vsc.window.withProgress.mockImplementationOnce((_options: any, task: any) => { const progress = { report: vi.fn() } const cancellationToken = { @@ -3107,25 +3079,14 @@ describe("McpHub", () => { }) await expect( - (mcpHub as any)._initiateOAuthFlow( - serverName, - source, - config, - mockAuthProvider, - mockTransport, - mockConnection, - ), + (mcpHub as any)._initiateOAuthFlow(serverName, source, config, mockAuthProvider, mockConnection), ).resolves.toBe("cancelled") expect(mockConnection.server.status).toBe("disconnected") expect((mcpHub as any).appendErrorMessage).toHaveBeenCalled() expect(mockAuthProvider.close).toHaveBeenCalled() - // A listener returned after synchronous cancellation must be disposed immediately. - // If the registration happens AFTER the callback is installed, the entry - // is added after disposal and remains orphaned in the map. Registering the - // watcher BEFORE installing the callback ensures cleanup() finds and - // deletes it cleanly. + // The ended flow leaves no registry entry. expect((mcpHub as any).oauthFlows.has(mockConnection)).toBe(false) }) @@ -3140,7 +3101,6 @@ describe("McpHub", () => { source, config, mockAuthProvider, - mockTransport, mockConnection, ) @@ -3168,14 +3128,7 @@ describe("McpHub", () => { code = resolve }), ) - const result = mcpHub["_initiateOAuthFlow"]( - serverName, - source, - config, - mockAuthProvider, - mockTransport, - mockConnection, - ) + const result = mcpHub["_initiateOAuthFlow"](serverName, source, config, mockAuthProvider, mockConnection) try { await vi.advanceTimersByTimeAsync(OAUTH_FLOW_TIMEOUT_MS - 1000) approve(t("mcp:oauth.flow.authenticateButton")) @@ -3207,14 +3160,13 @@ describe("McpHub", () => { source, config, mockAuthProvider, - mockTransport, mockConnection, ) await vi.advanceTimersByTimeAsync(OAUTH_FLOW_TIMEOUT_MS) await flowPromise - // cleanup(cancellationDisposable) inside the timeout handler must dispose the listener + // The timeout must dispose the cancellation listener. expect(mockDispose).toHaveBeenCalled() }) @@ -3229,14 +3181,7 @@ describe("McpHub", () => { const completeOAuthSpy = vi.spyOn(mcpHub as any, "_completeOAuthFlow") - await (mcpHub as any)._initiateOAuthFlow( - serverName, - source, - config, - mockAuthProvider, - mockTransport, - mockConnection, - ) + await (mcpHub as any)._initiateOAuthFlow(serverName, source, config, mockAuthProvider, mockConnection) expect(completeOAuthSpy).not.toHaveBeenCalled() expect(mockAuthProvider.close).toHaveBeenCalled() @@ -3249,14 +3194,7 @@ describe("McpHub", () => { vi.spyOn(mcpHub as any, "_completeOAuthFlow").mockRejectedValue(new Error("network failure")) await expect( - (mcpHub as any)._initiateOAuthFlow( - serverName, - source, - config, - mockAuthProvider, - mockTransport, - mockConnection, - ), + (mcpHub as any)._initiateOAuthFlow(serverName, source, config, mockAuthProvider, mockConnection), ).resolves.toBe("failed") }) @@ -3265,14 +3203,7 @@ describe("McpHub", () => { // The provider reports a callback listener failure, such as a timeout before the user authenticated. mockAuthProvider.waitForAuthCode.mockRejectedValueOnce(new Error("Callback timeout")) - await mcpHub["_initiateOAuthFlow"]( - serverName, - source, - config, - mockAuthProvider, - mockTransport, - mockConnection, - ) + await mcpHub["_initiateOAuthFlow"](serverName, source, config, mockAuthProvider, mockConnection) expect(mockAuthProvider.openBrowser).toHaveBeenCalledTimes(1) expect(mockAuthProvider.exchangeCodeForTokens).not.toHaveBeenCalled() @@ -3316,13 +3247,12 @@ describe("McpHub", () => { source, config, mockAuthProvider, - mockTransport, mockConnection, ) // Let the flow advance: getOAuthData resolves, withProgress runs, // showInformationMessage resolves (Authenticate clicked), getOAuthData - // re-checked (null), cleanup() called, _completeOAuthFlow entered, + // re-checked (null), _completeOAuthFlow entered, // openBrowser() called, then waitForAuthCode blocks. await new Promise((r) => setTimeout(r, 0)) @@ -3352,7 +3282,6 @@ describe("McpHub", () => { source, config, mockAuthProvider, - mockTransport, mockConnection, ) mcpHub["isDisposed"] = true @@ -3386,7 +3315,6 @@ describe("McpHub", () => { source, config, mockAuthProvider, - mockTransport, mockConnection, ) @@ -3416,7 +3344,6 @@ describe("McpHub", () => { source, config, mockAuthProvider, - mockTransport, mockConnection, ) @@ -3425,7 +3352,7 @@ describe("McpHub", () => { await flowPromise // Should NOT have tried to reconnect — the watcher fired but no valid token exists - expect((mcpHub as any).connectToServer).not.toHaveBeenCalledWith(serverName, expect.anything(), source) + expect((mcpHub as any).connectToServer).not.toHaveBeenCalled() }) it("should reconnect when cross-window token is written while getOAuthData is in-flight", async () => { @@ -3454,7 +3381,6 @@ describe("McpHub", () => { source, config, mockAuthProvider, - mockTransport, mockConnection, ) @@ -3468,28 +3394,58 @@ describe("McpHub", () => { expect(vsc.window.withProgress).not.toHaveBeenCalled() }) - it("joins repeated OAuth requests on the same connection", async () => { + it("reads the token again when it changes during a read that returns an expired token", async () => { + mockSecretStorage.getOAuthData + .mockResolvedValueOnce({ expires_at: 0 }) + .mockResolvedValue({ expires_at: Date.now() + 10 * 60 * 1000 }) + mockSecretStorage.onDidChange.mockImplementationOnce((_url: string, changed: () => void) => { + changed() + return vi.fn() + }) + + await mcpHub["_initiateOAuthFlow"](serverName, source, config, mockAuthProvider, mockConnection) + + expect(mcpHub["connectToServer"]).toHaveBeenCalled() + expect(vsc.window.withProgress).not.toHaveBeenCalled() + }) + + it("ignores a token read error that arrives after another owner claimed the flow", async () => { vi.useFakeTimers() vsc.window.showInformationMessage.mockImplementation(() => new Promise(() => {})) - const first = mcpHub["_initiateOAuthFlow"]( - serverName, - source, - config, - mockAuthProvider, - mockTransport, - mockConnection, + let changed = () => {} + mockSecretStorage.onDidChange.mockImplementation((_url: string, listener: () => void) => { + changed = listener + return vi.fn() + }) + const pending = mcpHub["_initiateOAuthFlow"](serverName, source, config, mockAuthProvider, mockConnection) + await vi.advanceTimersByTimeAsync(0) + const flow = mcpHub["oauthFlows"].get(mockConnection) + if (!flow) throw new Error("Missing flow") + let fail = (_error: Error) => {} + mockSecretStorage.getOAuthData.mockImplementationOnce( + () => + new Promise((_resolve, reject) => { + fail = reject + }), ) + changed() + flow.claim() + fail(new Error("storage unavailable")) + await vi.advanceTimersByTimeAsync(0) + + expect(flow.phase).toBe("authenticating") + flow.finish("removed") + await pending + }) + + it("joins repeated OAuth requests on the same connection", async () => { + vi.useFakeTimers() + vsc.window.showInformationMessage.mockImplementation(() => new Promise(() => {})) + const first = mcpHub["_initiateOAuthFlow"](serverName, source, config, mockAuthProvider, mockConnection) await vi.advanceTimersByTimeAsync(0) const flow = mcpHub["oauthFlows"].get(mockConnection) const subscriptions = mockSecretStorage.onDidChange.mock.calls.length - const second = mcpHub["_initiateOAuthFlow"]( - serverName, - source, - config, - mockAuthProvider, - mockTransport, - mockConnection, - ) + const second = mcpHub["_initiateOAuthFlow"](serverName, source, config, mockAuthProvider, mockConnection) await vi.advanceTimersByTimeAsync(0) expect(mcpHub["oauthFlows"].get(mockConnection)).toBe(flow) expect(mockSecretStorage.onDidChange).toHaveBeenCalledTimes(subscriptions) @@ -3508,25 +3464,11 @@ describe("McpHub", () => { }), ) vsc.window.showInformationMessage.mockImplementation(() => new Promise(() => {})) - const first = mcpHub["_initiateOAuthFlow"]( - serverName, - source, - config, - mockAuthProvider, - mockTransport, - mockConnection, - ) + const first = mcpHub["_initiateOAuthFlow"](serverName, source, config, mockAuthProvider, mockConnection) await vi.advanceTimersByTimeAsync(0) const replacement = { ...mockConnection, server: { ...mockConnection.server } } vi.mocked(mcpHub["findConnection"]).mockReturnValue(replacement) - const second = mcpHub["_initiateOAuthFlow"]( - serverName, - source, - config, - mockAuthProvider, - mockTransport, - replacement, - ) + const second = mcpHub["_initiateOAuthFlow"](serverName, source, config, mockAuthProvider, replacement) await vi.advanceTimersByTimeAsync(0) const currentFlow = mcpHub["oauthFlows"].get(replacement) resolveFirstToast(t("mcp:oauth.flow.authenticateButton")) @@ -3549,7 +3491,6 @@ describe("McpHub", () => { source: "global" | "project", config: unknown, authProvider: unknown, - transport: unknown, connection: unknown, ) => Promise appendErrorMessage: Mock & ((connection: unknown, message: string) => void) @@ -3557,15 +3498,7 @@ describe("McpHub", () => { } const closeMock = vi.fn().mockResolvedValue(undefined) mockAuthProvider.close = closeMock - hub.connectToServer.mockImplementation(async () => { - mcpHub.connections = [ - { - ...mockConnection, - server: { ...mockConnection.server, status: "disconnected", error: "reconnect failed" }, - }, - ] - throw new Error("reconnect failed") - }) + hub.connectToServer.mockRejectedValue(new Error("reconnect failed")) // Two subscriptions happen: the cross-window pre-read watcher in // _initiateOAuthFlow stays silent; the flow watcher delivers valid tokens. let subscriptions = 0 @@ -3580,11 +3513,10 @@ describe("McpHub", () => { }) // Must resolve through the catch path instead of staying pending forever. - await hub._initiateOAuthFlow(serverName, source, config, mockAuthProvider, {}, mockConnection) + await hub._initiateOAuthFlow(serverName, source, config, mockAuthProvider, mockConnection) - expect(mcpHub.connections[0]?.server.status).toBe("disconnected") - expect(mcpHub.connections[0]?.server.error).toBe("reconnect failed") - expect(hub.appendErrorMessage).not.toHaveBeenCalledWith(mockConnection, "reconnect failed") + // The integration spec checks the error row on a real hub. + expect(hub.connectToServer).toHaveBeenCalled() expect(closeMock).toHaveBeenCalled() expect(hub.oauthFlows.size).toBe(0) }) @@ -3601,27 +3533,17 @@ describe("McpHub", () => { source: "global" | "project", config: unknown, authProvider: unknown, - transport: unknown, connection: unknown, ) => Promise appendErrorMessage: Mock & ((connection: unknown, message: string) => void) connectToServer: Mock & ((...args: unknown[]) => Promise) } - hub.connectToServer.mockImplementation(async () => { - mcpHub.connections = [ - { - ...mockConnection, - server: { ...mockConnection.server, status: "disconnected", error: "fast reconnect failed" }, - }, - ] - throw new Error("fast reconnect failed") - }) + hub.connectToServer.mockRejectedValue(new Error("fast reconnect failed")) - await hub._initiateOAuthFlow(serverName, source, config, mockAuthProvider, {}, mockConnection) + await hub._initiateOAuthFlow(serverName, source, config, mockAuthProvider, mockConnection) - expect(mcpHub.connections[0]?.server.status).toBe("disconnected") - expect(mcpHub.connections[0]?.server.error).toBe("fast reconnect failed") - expect(hub.appendErrorMessage).not.toHaveBeenCalledWith(mockConnection, "fast reconnect failed") + // The integration spec checks the error row on a real hub. + expect(hub.connectToServer).toHaveBeenCalled() expect(hub.oauthFlows.size).toBe(0) }) @@ -3893,7 +3815,6 @@ describe("McpHub", () => { "global", hub["validateServerConfig"](JSON.parse(connection.server.config), serverName), connection.authProvider, - connection.transport as StreamableHTTPClientTransport, connection, ) } @@ -3907,6 +3828,55 @@ describe("McpHub", () => { } }) + // Invariant: McpOAuthRetry.Fresh. Only rejections since the last successful tool call count. + it("restores the rejected-token budget after a successful tool call", async () => { + const { connectCount } = await setupRejectingServer(0) + const hub = await createHubWithSavedToken() + try { + for (let attempt = 0; attempt <= OAUTH_TOKEN_RETRY_MAX_ATTEMPTS; attempt++) { + const connection = hub.connections.find((entry) => entry.server.name === serverName) + if (!connection || connection.type !== "connected" || !connection.authProvider) + throw new Error("Missing connection") + connection.server.status = "connecting" + await hub["_initiateOAuthFlow"]( + serverName, + "global", + hub["validateServerConfig"](JSON.parse(connection.server.config), serverName), + connection.authProvider, + connection, + ) + await hub.callTool(serverName, "tool", {}, "global") + } + expect(connectCount()).toBe(2 + OAUTH_TOKEN_RETRY_MAX_ATTEMPTS) + expect(hub.connections[0]?.server.status).toBe("connected") + } finally { + await hub.dispose() + } + }) + + it("starts a new retry budget for a changed access token", async () => { + await setupRejectingServer(0) + const hub = await createHubWithSavedToken() + try { + hub["oauthTokenRetries"].set(`${serverName}:global`, { tokenKey: "another token", count: 99 }) + const connection = hub.connections[0] + if (!connection || connection.type !== "connected" || !connection.authProvider) + throw new Error("Missing connection") + connection.server.status = "connecting" + await hub["_initiateOAuthFlow"]( + serverName, + "global", + hub["validateServerConfig"](JSON.parse(connection.server.config), serverName), + connection.authProvider, + connection, + ) + expect(hub["oauthTokenRetries"].get(`${serverName}:global`)?.count).toBe(1) + expect(hub.connections[0]?.server.status).toBe("connected") + } finally { + await hub.dispose() + } + }) + it("delays each automatic reconnect of the same rejected token", async () => { await setupRejectingServer(Number.POSITIVE_INFINITY) const hub = await createHubWithSavedToken() @@ -3977,6 +3947,10 @@ describe("McpHub", () => { hub as unknown as { notifyWebviewOfServerChanges: () => Promise }, "notifyWebviewOfServerChanges", ) + const postedTools: unknown[] = [] + notifySpy.mockImplementation(async () => { + postedTools.push(structuredClone(conn()?.server.tools)) + }) const ready = hub.waitUntilReady() const conn = () => { const found = hub.connections.find((c) => c.server.name === serverName) @@ -3993,11 +3967,8 @@ describe("McpHub", () => { // When the lists arrive, the panel updates again with their results. resolveTools!({ tools: [{ name: "slow-tool" }] }) await ready - // The early connected update plus at least one post-list update. - await vi.waitFor(() => expect(notifySpy.mock.calls.length).toBeGreaterThanOrEqual(2)) - expect(conn()?.server.tools).toEqual([ - { name: "slow-tool", alwaysAllow: false, enabledForPrompt: true }, - ]) + const tools = [{ name: "slow-tool", alwaysAllow: false, enabledForPrompt: true }] + await vi.waitFor(() => expect(postedTools.at(-1)).toEqual(tools)) } finally { await hub.dispose() } diff --git a/src/services/mcp/__tests__/McpOAuthClientProvider.spec.ts b/src/services/mcp/__tests__/McpOAuthClientProvider.spec.ts index 8d3ae5d3c50..dcb646d5835 100644 --- a/src/services/mcp/__tests__/McpOAuthClientProvider.spec.ts +++ b/src/services/mcp/__tests__/McpOAuthClientProvider.spec.ts @@ -424,19 +424,24 @@ describe("McpOAuthClientProvider", () => { mockFetch.mockResolvedValueOnce({ ok: false, status: 400, - text: () => Promise.resolve("invalid_grant"), + text: () => Promise.resolve('{"error":"invalid_grant"}'), }) const secretStorage = createMockSecretStorage() await secretStorage.saveOAuthData("https://example.com/mcp", { tokens: { access_token: "expired", refresh_token: "dead-refresh", token_type: "Bearer" }, expires_at: Date.now() - 1000, issuer: "https://auth.example.com", + client_info: { client_id: "registered", redirect_uris: [] }, }) mockCallbackListeners(1) const provider = await McpOAuthClientProvider.create("https://example.com/mcp", secretStorage) // The failed refresh clears the stale data; the next sign-in is a full flow. expect(await provider.tokens()).toBeUndefined() + expect(mockFetch).toHaveBeenLastCalledWith( + expect.stringContaining("/token"), + expect.objectContaining({ body: expect.stringContaining("grant_type=refresh_token") }), + ) expect(secretStorage.deleteOAuthData).toHaveBeenCalled() const url = sdkAuthorizationUrl() @@ -648,7 +653,8 @@ describe("McpOAuthClientProvider", () => { }) const result = await provider.tokens() - expect(result).toEqual({ ...refreshedTokens, refresh_token: "valid-refresh" }) + // Invariant: McpOAuthRefreshToken.NoLeak. The SDK never receives the refresh token. + expect(result).toEqual(refreshedTokens) expect(mockFetch).toHaveBeenCalledWith( expect.stringContaining("/token"), expect.objectContaining({ @@ -688,7 +694,8 @@ describe("McpOAuthClientProvider", () => { const result = await provider.tokens() - expect(result?.refresh_token).toBe("new-refresh") + expect(result?.access_token).toBe("new-access") + expect(result).not.toHaveProperty("refresh_token") expect((await secretStorage.getOAuthData("https://example.com/mcp"))?.tokens.refresh_token).toBe( "new-refresh", ) @@ -879,6 +886,71 @@ describe("McpOAuthClientProvider", () => { expect(await secretStorage.getOAuthData(serverUrl, clientId)).toBeUndefined() }) + it("does not give the SDK the refresh token of a current access token", async () => { + setupCallbackServerMock() + const secretStorage = createMockSecretStorage() + const provider = await McpOAuthClientProvider.create("https://example.com/mcp", secretStorage) + await provider.saveTokens({ + access_token: "current", + refresh_token: "secret", + token_type: "Bearer", + expires_in: 3600, + }) + + expect(await provider.tokens()).toEqual({ access_token: "current", token_type: "Bearer", expires_in: 3600 }) + expect((await secretStorage.getOAuthData("https://example.com/mcp"))?.tokens.refresh_token).toBe("secret") + await provider.close() + }) + + // Invariant: McpOAuthRefreshToken.NoLostCredential. + it.each([ + ["discovery is not available", true, undefined], + ["the token endpoint returns HTTP 500", false, { ok: false, status: 500, text: async () => "unavailable" }], + ["the network fails", false, new Error("offline")], + ])("keeps the stored data when %s", async (_label, skipDiscovery, outcome) => { + setupCallbackServerMock() + const secretStorage = createMockSecretStorage() + const provider = await McpOAuthClientProvider.create("https://example.com/mcp", secretStorage, undefined, { + skipDiscovery, + }) + await secretStorage.saveOAuthData("https://example.com/mcp", { + tokens: { access_token: "expired", refresh_token: "usable", token_type: "Bearer" }, + expires_at: Date.now() - 1000, + issuer: "https://auth.example.com", + client_info: { client_id: "registered", redirect_uris: [] }, + }) + if (outcome instanceof Error) mockFetch.mockRejectedValueOnce(outcome) + else if (outcome) mockFetch.mockResolvedValueOnce(outcome) + + expect(await provider.tokens()).toBeUndefined() + expect(secretStorage.deleteOAuthData).not.toHaveBeenCalled() + await provider.close() + }) + + it("keeps a newer refresh token that another window saved during a rejected refresh", async () => { + setupCallbackServerMock() + const secretStorage = createMockSecretStorage() + const provider = await McpOAuthClientProvider.create("https://example.com/mcp", secretStorage) + const data = { + tokens: { access_token: "expired", refresh_token: "old", token_type: "Bearer" }, + expires_at: Date.now() - 1000, + issuer: "https://auth.example.com", + client_info: { client_id: "registered", redirect_uris: [] }, + } + await secretStorage.saveOAuthData("https://example.com/mcp", data) + mockFetch.mockImplementationOnce(async () => { + await secretStorage.saveOAuthData("https://example.com/mcp", { + ...data, + tokens: { ...data.tokens, refresh_token: "newer" }, + }) + return { ok: false, status: 400, text: async () => '{"error":"invalid_grant"}' } + }) + + expect(await provider.tokens()).toBeUndefined() + expect(secretStorage.deleteOAuthData).not.toHaveBeenCalled() + await provider.close() + }) + it("should return undefined for expired tokens without refresh token", async () => { setupCallbackServerMock() const secretStorage = createMockSecretStorage() @@ -941,6 +1013,24 @@ describe("McpOAuthClientProvider", () => { await provider.close() }) + it.each(["file:///etc/passwd", "vscode://extension/command", "javascript:alert(1)"])( + "does not open %s", + async (url) => { + setupCallbackServerMock() + vi.mocked(vscode.env.openExternal).mockClear() + const provider = await McpOAuthClientProvider.create( + "https://example.com/mcp", + createMockSecretStorage(), + ) + // Discovery replaces the endpoint, so set the URL that the server metadata would select. + provider["_pendingAuthorizationUrl"] = new URL(url) + + await expect(provider.openBrowser()).rejects.toThrow("unsupported scheme") + expect(vscode.env.openExternal).not.toHaveBeenCalled() + await provider.close() + }, + ) + it("should show URL as fallback if browser open fails", async () => { setupCallbackServerMock() ;(vscode.env.openExternal as any).mockRejectedValueOnce(new Error("no browser")) diff --git a/src/services/mcp/__tests__/McpOAuthFlow.spec.ts b/src/services/mcp/__tests__/McpOAuthFlow.spec.ts index a5f6045116b..6166220bfdf 100644 --- a/src/services/mcp/__tests__/McpOAuthFlow.spec.ts +++ b/src/services/mcp/__tests__/McpOAuthFlow.spec.ts @@ -13,9 +13,8 @@ describe("McpOAuthFlow ownership", () => { flow.finish(outcome) flow.finish("failed") expect(flow.phase).toBe("ended") - expect(flow.signal.aborted).toBe(["cancelled", "timed-out", "removed"].includes(outcome)) expect(await flow.promise).toBe(outcome) - expect(cleanup).toHaveBeenCalledOnce() + expect(cleanup).toHaveBeenCalledExactlyOnceWith(outcome) }, ) @@ -30,7 +29,6 @@ describe("McpOAuthFlow ownership", () => { flow.setWaitingTimeout(expired, 300_000) flow.finish(outcome) expect(vi.getTimerCount()).toBe(0) - flow.beginReconnect() expect(flow.claim()).toBe(false) expect(flow.phase).toBe("ended") await vi.advanceTimersByTimeAsync(300_000) @@ -43,19 +41,18 @@ describe("McpOAuthFlow ownership", () => { }, ) - it.each(["browser", "reconnect"])("approval timer ends before %s work starts", async (step) => { + it("approval timer ends when a continuation claims the flow", async () => { vi.useFakeTimers() const flow = new McpOAuthFlow() const expired = vi.fn() try { flow.setWaitingTimeout(expired, 300_000) await vi.advanceTimersByTimeAsync(299_999) - if (step === "browser") expect(flow.claim()).toBe(true) - else flow.beginReconnect() + expect(flow.claim()).toBe(true) expect(vi.getTimerCount()).toBe(0) await vi.advanceTimersByTimeAsync(300_000) expect(expired).not.toHaveBeenCalled() - expect(flow.phase).toBe(step === "browser" ? "authenticating" : "reconnecting") + expect(flow.phase).toBe("authenticating") } finally { flow.finish("removed") vi.useRealTimers() @@ -69,7 +66,6 @@ describe("McpOAuthFlow ownership", () => { flow.setWaitingTimeout(() => flow.finish("timed-out"), 300_000) await vi.advanceTimersByTimeAsync(300_000) expect(await flow.promise).toBe("timed-out") - expect(flow.signal.reason).toBe("timed-out") expect(vi.getTimerCount()).toBe(0) } finally { flow.finish("removed") diff --git a/src/services/mcp/__tests__/mcp-oauth-flow.property.spec.ts b/src/services/mcp/__tests__/mcp-oauth-flow.property.spec.ts index 77e515cba1e..39e0de24540 100644 --- a/src/services/mcp/__tests__/mcp-oauth-flow.property.spec.ts +++ b/src/services/mcp/__tests__/mcp-oauth-flow.property.spec.ts @@ -250,7 +250,6 @@ type TestConnection = { type FlowHandle = { connection: TestConnection authProvider: { close: Mock } - cancellationToken?: { onCancellationRequested: Mock } promise: Promise resolved: boolean } @@ -264,12 +263,13 @@ type FlowHub = { config: unknown, serverUrl: string, authProvider: unknown, - transport: unknown, connection: unknown, progress: unknown, cancellationToken: unknown, - oauthClientId?: string, + oauthClientId: string | undefined, + flow: unknown, ) => Promise + createOAuthFlow: (connection: unknown, authProvider: unknown) => unknown deleteConnection: (name: string, source?: string) => Promise notifyWebviewOfServerChanges: Mock findConnection: Mock @@ -297,6 +297,13 @@ async function createFlowHub(): Promise { return hub } +/** Runs the browser step as a claimed flow, as the Authenticate click does. */ +function completeClaimedFlow(hub: McpHub, provider: McpOAuthClientProvider, connection: ConnectedMcpConnection) { + const owner = hub["createOAuthFlow"](connection, provider) + owner.claim() + return hub["_completeOAuthFlow"](provider, connection, owner) +} + /** Starts one real _runOAuthFlow with a toast that never resolves. */ function startFlow(hub: FlowHub, tool = false): FlowHandle { const connection: TestConnection = { @@ -326,16 +333,15 @@ function startFlow(hub: FlowHub, tool = false): FlowHandle { oauthConfig, serverUrl, authProvider, - {}, connection, { report: vi.fn() }, cancellationToken, undefined, + hub.createOAuthFlow(connection, authProvider), ) const handle: FlowHandle = { connection, authProvider, - cancellationToken, promise: flowPromise, resolved: false, } @@ -430,7 +436,7 @@ describe("MCP OAuth flow property tests", () => { } }) - // Invariant: McpOAuthFlowEnd.NoStaleWrite, PR #2762 findings #1, #2, #3 and #8. + // Invariant: McpOAuthFlowEnd.NoStaleWrite. it.each( ["token-read", "backoff", "browser", "exchange", "close"].flatMap((phase) => ["accept", "delete", "disable", "replace", "dispose"].map((action) => ({ phase, action })), @@ -469,10 +475,6 @@ describe("MCP OAuth flow property tests", () => { const connect = vi.fn(methods.connect).mockResolvedValue(undefined) hub["connectToServer"] = connect hub["notifyWebviewOfServerChanges"] = vi.fn(methods.notify).mockResolvedValue(undefined) - const cancellation = { - isCancellationRequested: false, - onCancellationRequested: vi.fn(() => ({ dispose: vi.fn() })), - } if (phase === "token-read") vi.mocked(storage.getOAuthData).mockImplementationOnce(async () => { await held @@ -489,17 +491,9 @@ describe("MCP OAuth flow property tests", () => { "global", hub["validateServerConfig"](oauthConfig, serverName), provider, - connection.transport as StreamableHTTPClientTransport, - connection, - ) - : hub["_completeOAuthFlow"]( - provider, - connection.transport as StreamableHTTPClientTransport, connection, - serverName, - "global", - cancellation, ) + : completeClaimedFlow(hub, provider, connection) await flushPromises() expect(connect).not.toHaveBeenCalled() if (action === "delete") await hub.deleteConnection(serverName, "global") @@ -640,8 +634,8 @@ describe("MCP OAuth flow property tests", () => { } }) - // Invariants: McpOAuthFlowEnd.NoDuplicateFlow, NoOrphanFlow, ToolNotOrphaned. - it("flow-end property: a removed watcher always ends its flow, and tool waits are released", async () => { + // Invariants: McpOAuthFlowEnd.NoDuplicateFlow and NoOrphanFlow. The final loop releases each tool wait. + it("flow-end property: a removed flow always ends", async () => { const random = makeRandom(486) const histories = 16 const actions = ["start", "replace", "delete", "tool", "dispose"] as const @@ -649,16 +643,12 @@ describe("MCP OAuth flow property tests", () => { for (let history = 0; history < histories; history++) { const hub = await createFlowHub() const flows: FlowHandle[] = [] - let toolWaiting = false const steps = 3 + Math.floor(random() * 4) for (let step = 0; step < steps; step++) { const action = pick(random, actions) if (action === "start" || action === "replace" || action === "tool") { - if (action === "tool") { - toolWaiting = true - } - // Starting a flow replaces any existing watcher through the shared path. + // Starting a flow replaces the current flow through the shared path. flows.push(startFlow(hub, action === "tool")) } else if (action === "delete") { await hub.deleteConnection(serverName, "global") @@ -673,12 +663,8 @@ describe("MCP OAuth flow property tests", () => { // NoDuplicateFlow: at most one unresolved flow. const unresolved = flows.filter((flow) => !flow.resolved) expect(unresolved.length).toBeLessThanOrEqual(1) - // NoOrphanFlow: a pending flow still owns the watcher. + // NoOrphanFlow: a pending flow stays registered. expect(unresolved.length === 1).toBe(hub.oauthFlows.size === 1) - // ToolNotOrphaned: a tool wait is live on a flow or was released by its end. - if (toolWaiting) { - expect(hub.oauthFlows.size === 1 || unresolved.length === 0).toBe(true) - } } // Every flow promise settles once the hub goes away. @@ -692,29 +678,27 @@ describe("MCP OAuth flow property tests", () => { }) // Invariant: McpOAuthFlowEnd.NoErrorLeak. - it.each(["invalid OAuth config", "missing OAuth endpoint", "OAuth reconnect rejected"])( - "error-leak property: %s ends the flow and preserves the error", - async (message) => { - const hub = await createFlowHub() - const flow = startFlow(hub) - hub.validateServerConfig.mockImplementationOnce(() => { - throw new Error(message) - }) - vi.mocked(hub.secretStorage.getOAuthData).mockResolvedValue({ - tokens: { access_token: "token", token_type: "Bearer" }, - expires_at: Date.now() + 600_000, - }) - const callbacks = vi.mocked(hub.secretStorage.onDidChange).mock.calls - callbacks[0][1]() - await flow.promise - expect(flow.resolved).toBe(true) - expect(flow.connection.server.status).toBe("disconnected") - expect(flow.connection.server.error).toBe(message) - expect(flow.authProvider.close).toHaveBeenCalled() - expect(hub.oauthFlows.size).toBe(0) - await hub.dispose() - }, - ) + it("error-leak property: a rejected reconnect ends the flow and preserves the error", async () => { + const message = "OAuth reconnect rejected" + const hub = await createFlowHub() + const flow = startFlow(hub) + hub.validateServerConfig.mockImplementationOnce(() => { + throw new Error(message) + }) + vi.mocked(hub.secretStorage.getOAuthData).mockResolvedValue({ + tokens: { access_token: "token", token_type: "Bearer" }, + expires_at: Date.now() + 600_000, + }) + const callbacks = vi.mocked(hub.secretStorage.onDidChange).mock.calls + callbacks[0][1]() + await flow.promise + expect(flow.resolved).toBe(true) + expect(flow.connection.server.status).toBe("disconnected") + expect(flow.connection.server.error).toBe(message) + expect(flow.authProvider.close).toHaveBeenCalled() + expect(hub.oauthFlows.size).toBe(0) + await hub.dispose() + }) // Invariant: McpOAuthStatusHandoff.PanelShowsConnected. it("status-handoff property: the panel shows connected before slow lists finish, then updates again", async () => { diff --git a/src/services/mcp/__tests__/mcp-oauth-ownership.integration.spec.ts b/src/services/mcp/__tests__/mcp-oauth-ownership.integration.spec.ts index 5d907e5de8e..938401f72ea 100644 --- a/src/services/mcp/__tests__/mcp-oauth-ownership.integration.spec.ts +++ b/src/services/mcp/__tests__/mcp-oauth-ownership.integration.spec.ts @@ -8,6 +8,7 @@ import type { ClineProvider } from "../../../core/webview/ClineProvider" import type { SecretStorageService, StoredMcpOAuthData } from "../SecretStorageService" import { t } from "../../../i18n" import { McpHub } from "../McpHub" +import { McpOAuthClientProvider } from "../McpOAuthClientProvider" vi.mock("vscode", () => ({ workspace: { @@ -38,6 +39,214 @@ function deferred() { return { promise, resolve } } +type Row = { name: string; status: string; error?: string; disabled?: boolean } + +type HarnessOptions = { + /** Holds or fails an authorized JSON-RPC request. A number is the HTTP status to send. */ + onRequest?: (method: string, token: string) => Promise + onToken?: () => Promise + onBrowser?: () => Promise + onDiscovery?: () => Promise + /** The HTTP status for the SSE GET request. The default is 405. */ + getStatus?: number + savedToken?: string + /** Configures no client ID and marks the URL as a known non-OAuth server. */ + knownNonOAuth?: boolean + testMode?: boolean +} + +/** Starts a real hub, provider, SDK, callback listener, and local HTTP server. */ +async function startHarness(options: HarnessOptions = {}) { + const directory = await mkdtemp(join(tmpdir(), "mcp-ownership-")) + const requests: Array<{ method: string; token: string }> = [] + let base = "" + const send = (response: ServerResponse, data: unknown, status = 200) => { + response.writeHead(status, { "Content-Type": "application/json" }) + response.end(JSON.stringify(data)) + } + const server = createServer((request, response) => { + void (async () => { + if (request.url?.includes("oauth-protected-resource")) { + send(response, { resource: `${base}/mcp`, authorization_servers: [base] }) + } else if (request.url?.includes(".well-known")) { + await options.onDiscovery?.() + send(response, { + issuer: base, + authorization_endpoint: `${base}/authorize`, + token_endpoint: `${base}/token`, + registration_endpoint: `${base}/register`, + response_types_supported: ["code"], + grant_types_supported: ["authorization_code"], + code_challenge_methods_supported: ["S256"], + token_endpoint_auth_methods_supported: ["none"], + }) + } else if (request.url === "/register") { + let body = "" + for await (const chunk of request) body += String(chunk) + send(response, { ...(JSON.parse(body) as object), client_id: "static-client" }, 201) + } else if (request.url === "/token") { + requests.push({ method: "token", token: "" }) + await options.onToken?.() + send(response, { access_token: "accepted", token_type: "Bearer", expires_in: 3600 }) + } else if (request.method === "DELETE") { + response.writeHead(200).end() + } else if (request.method === "GET") { + requests.push({ method: "GET", token: request.headers.authorization?.replace("Bearer ", "") ?? "" }) + response.writeHead(options.getStatus ?? 405).end() + } else { + let body = "" + for await (const chunk of request) body += String(chunk) + const message = JSON.parse(body) as { id?: number; method: string } + const token = request.headers.authorization?.replace("Bearer ", "") ?? "" + requests.push({ method: message.method, token }) + const status = token ? await options.onRequest?.(message.method, token) : undefined + if (status || (token !== "accepted" && token !== options.savedToken)) { + response.setHeader( + "WWW-Authenticate", + `Bearer resource_metadata="${base}/.well-known/oauth-protected-resource"`, + ) + send(response, { error: "rejected" }, status || 401) + } else if (message.id === undefined) { + response.writeHead(202).end() + } else { + const result = + message.method === "initialize" + ? { + protocolVersion: "2025-03-26", + capabilities: { tools: {}, resources: {} }, + serverInfo: { name: "local", version: "1" }, + } + : message.method === "tools/call" + ? { content: [] } + : { tools: [], resources: [], resourceTemplates: [] } + send(response, { jsonrpc: "2.0", id: message.id, result }) + } + } + })().catch((error: unknown) => { + send(response, { error: String(error) }, 500) + }) + }) + await new Promise((resolve) => { + server.listen(0, "127.0.0.1", resolve) + }) + const address = server.address() + if (!address || typeof address === "string") throw new Error("Missing server address") + base = `http://127.0.0.1:${address.port}` + const url = `${base}/mcp` + const oauth = options.knownNonOAuth ? undefined : { clientId: "static-client" } + if (options.knownNonOAuth) McpOAuthClientProvider.markNonOAuth(url) + const config = { type: "streamable-http", url, oauth } + await writeFile(join(directory, "mcp_settings.json"), JSON.stringify({ mcpServers: { local: config } })) + const values = new Map() + if (options.savedToken) { + values.set(url, { + tokens: { access_token: options.savedToken, token_type: "Bearer" }, + expires_at: Date.now() + 3_600_000, + issuer: base, + client_info: { client_id: "static-client", redirect_uris: [] }, + }) + } + const listeners = new Set<() => void>() + // The store double supplies only the OAuth storage API used by the real provider. + const storage = { + hasOAuthData: vi.fn(async (key: string) => values.has(key)), + getOAuthData: async (key: string) => values.get(key), + saveOAuthData: async (key: string, data: StoredMcpOAuthData) => { + values.set(key, data) + for (const listener of listeners) listener() + }, + deleteOAuthData: async (key: string) => { + values.delete(key) + }, + onDidChange: (_url: string, listener: () => void) => { + listeners.add(listener) + return () => { + listeners.delete(listener) + } + }, + } + const panelRows: Row[][] = [] + // The extension double supplies settings, panel updates, and the extension version. + const provider = { + ensureSettingsDirectoryExists: async () => directory, + postMessageToWebview: vi.fn((message: { type: string; mcpServers?: Row[] }) => { + if (message.type === "mcpServers" && message.mcpServers) panelRows.push(structuredClone(message.mcpServers)) + }), + getState: async () => ({ mcpEnabled: true }), + context: { extension: { packageJSON: { version: "1" } } }, + } as unknown as ClineProvider + vi.mocked(vscode.env.openExternal).mockReset() + vi.mocked(vscode.env.openExternal).mockImplementation(async (uri) => { + await options.onBrowser?.() + const authorization = new URL(uri.toString()) + const callback = new URL(authorization.searchParams.get("redirect_uri")!) + callback.searchParams.set("code", "authorization-code") + callback.searchParams.set("state", authorization.searchParams.get("state")!) + await fetch(callback) + return true + }) + const previous = process.env.MCP_OAUTH_TEST_MODE + // Test mode skips the notification UI but keeps the full OAuth and HTTP flow. + if (options.testMode === false) delete process.env.MCP_OAUTH_TEST_MODE + else process.env.MCP_OAUTH_TEST_MODE = "true" + const cancellationListeners = new Set<() => void>() + const cancellationToken = { + isCancellationRequested: false, + onCancellationRequested: (listener: () => void) => { + cancellationListeners.add(listener) + return { + dispose: () => { + cancellationListeners.delete(listener) + }, + } + }, + } + const progress = vi.fn((_options: unknown, task: (progress: unknown, token: unknown) => unknown) => + task({ report: vi.fn() }, cancellationToken), + ) + Object.assign(vscode.window, { withProgress: progress }) + const hub = new McpHub(provider, storage as unknown as SecretStorageService) + const completions: Promise[] = [] + const complete = hub["_completeOAuthFlow"].bind(hub) + hub["_completeOAuthFlow"] = (...args) => { + const completion = complete(...args) + completions.push(completion) + return completion + } + return { + hub, + url, + values, + storage, + panelRows, + requests, + count: (method: string) => requests.filter((request) => request.method === method).length, + cancel: () => { + cancellationToken.isCancellationRequested = true + for (const listener of cancellationListeners) listener() + }, + resetCancellation: () => { + cancellationToken.isCancellationRequested = false + }, + /** Waits for every flow, including a flow whose listener an external action removed. */ + settle: async () => { + await vi.waitFor(() => expect(hub["oauthFlows"].size).toBe(0), { timeout: 5000 }) + await Promise.all(progress.mock.results.map((result) => result.value)) + await Promise.all(completions) + }, + close: async () => { + await hub.dispose() + if (previous === undefined) delete process.env.MCP_OAUTH_TEST_MODE + else process.env.MCP_OAUTH_TEST_MODE = previous + server.closeAllConnections() + await new Promise((resolve) => { + server.close(() => resolve()) + }) + await rm(directory, { recursive: true, force: true }) + }, + } +} + // Invariant: McpOAuthFlowEnd.NoStaleWrite. The hub, OAuth provider, SDK, and callback listener are real. describe("OAuth ownership through the HTTP boundary", () => { beforeEach(() => nock.enableNetConnect(/^(127\.0\.0\.1|localhost)(:|$)/)) @@ -50,197 +259,51 @@ describe("OAuth ownership through the HTTP boundary", () => { "disable", "dispose", "cancel", - ...(phase === "reconnect" ? ["timeout", "cancel-delete"] : []), + ...(phase === "reconnect" ? ["cancel-delete"] : []), ].map((action) => ({ phase, action })), ), )( "$action during $phase does not restore a removed or disabled server", async ({ phase, action }) => { - const directory = await mkdtemp(join(tmpdir(), "mcp-ownership-")) const entered = deferred() const release = deferred() - let initializeRequests = 0 - let base = "" - const send = (response: ServerResponse, data: unknown, status = 200) => { - response.writeHead(status, { "Content-Type": "application/json" }) - response.end(JSON.stringify(data)) + const hold = async () => { + entered.resolve() + await release.promise } - const server = createServer((request, response) => { - void (async () => { - if (request.url?.includes("oauth-protected-resource")) { - send(response, { resource: `${base}/mcp`, authorization_servers: [base] }) - } else if (request.url?.includes(".well-known")) { - send(response, { - issuer: base, - authorization_endpoint: `${base}/authorize`, - token_endpoint: `${base}/token`, - response_types_supported: ["code"], - grant_types_supported: ["authorization_code"], - code_challenge_methods_supported: ["S256"], - token_endpoint_auth_methods_supported: ["none"], - }) - } else if (request.url === "/token") { - if (phase === "exchange") { - entered.resolve() - await release.promise - } - send(response, { access_token: "accepted", token_type: "Bearer", expires_in: 3600 }) - } else if (request.method === "DELETE") { - response.writeHead(200).end() - } else if (request.method === "GET") { - response.writeHead(405).end() - } else { - let body = "" - for await (const chunk of request) body += String(chunk) - const message = JSON.parse(body) as { id?: number; method: string } - if (message.method === "initialize") initializeRequests++ - if (request.headers.authorization !== "Bearer accepted") { - response.setHeader( - "WWW-Authenticate", - `Bearer resource_metadata="${base}/.well-known/oauth-protected-resource"`, - ) - send(response, { error: "unauthorized" }, 401) - } else if (message.id === undefined) { - response.writeHead(202).end() - } else { - if (phase === "reconnect" && message.method === "initialize") { - entered.resolve() - await release.promise - } - const result = - message.method === "initialize" - ? { - protocolVersion: "2025-03-26", - capabilities: { tools: {}, resources: {} }, - serverInfo: { name: "local", version: "1" }, - } - : { tools: [], resources: [], resourceTemplates: [] } - send(response, { jsonrpc: "2.0", id: message.id, result }) - } - } - })().catch((error: unknown) => { - send(response, { error: String(error) }, 500) - }) - }) - await new Promise((resolve) => { - server.listen(0, "127.0.0.1", resolve) - }) - const address = server.address() - if (!address || typeof address === "string") throw new Error("Missing server address") - base = `http://127.0.0.1:${address.port}` - const config = { type: "streamable-http", url: `${base}/mcp`, oauth: { clientId: "static-client" } } - await writeFile(join(directory, "mcp_settings.json"), JSON.stringify({ mcpServers: { local: config } })) - const values = new Map() - const listeners = new Set<() => void>() - // The store double supplies only the OAuth storage API used by the real provider. - const storage = { - hasOAuthData: async (url: string) => values.has(url), - getOAuthData: async (url: string) => values.get(url), - saveOAuthData: async (url: string, data: StoredMcpOAuthData) => { - values.set(url, data) - for (const listener of listeners) listener() - }, - deleteOAuthData: async (url: string) => { - values.delete(url) - }, - onDidChange: (_url: string, listener: () => void) => { - listeners.add(listener) - return () => { - listeners.delete(listener) - } + const harness = await startHarness({ + onBrowser: phase === "browser" ? hold : undefined, + onToken: phase === "exchange" ? hold : undefined, + onRequest: async (method, token) => { + if (phase === "reconnect" && method === "initialize" && token === "accepted") await hold() }, - } as unknown as SecretStorageService - const panelRows: Array> = [] - // The extension double supplies settings, panel updates, and the extension version. - const provider = { - ensureSettingsDirectoryExists: async () => directory, - postMessageToWebview: vi.fn( - (message: { - type: string - mcpServers?: Array<{ name: string; status: string; error?: string }> - }) => { - if (message.type === "mcpServers" && message.mcpServers) - panelRows.push(structuredClone(message.mcpServers)) - }, - ), - getState: async () => ({ mcpEnabled: true }), - context: { extension: { packageJSON: { version: "1" } } }, - } as unknown as ClineProvider - vi.mocked(vscode.env.openExternal).mockImplementation(async (uri) => { - if (phase === "browser") { - entered.resolve() - await release.promise - } - const url = new URL(uri.toString()) - const callback = new URL(url.searchParams.get("redirect_uri")!) - callback.searchParams.set("code", "authorization-code") - callback.searchParams.set("state", url.searchParams.get("state")!) - await fetch(callback) - return true }) - const previous = process.env.MCP_OAUTH_TEST_MODE - process.env.MCP_OAUTH_TEST_MODE = "true" - // Test mode skips the notification UI but keeps the full OAuth and HTTP flow. - const cancellationListeners = new Set<() => void>() - const cancellationToken = { - isCancellationRequested: false, - onCancellationRequested: (listener: () => void) => { - cancellationListeners.add(listener) - return { - dispose: () => { - cancellationListeners.delete(listener) - }, - } - }, - } - const progress = vi.fn((_options: unknown, task: (progress: unknown, token: unknown) => unknown) => - task({ report: vi.fn() }, cancellationToken), - ) - Object.assign(vscode.window, { withProgress: progress }) - const hub = new McpHub(provider, storage) - const completions: Promise[] = [] - const complete = hub["_completeOAuthFlow"].bind(hub) - hub["_completeOAuthFlow"] = (...args) => { - const completion = complete(...args) - completions.push(completion) - return completion - } + const { hub, panelRows } = harness try { await hub.waitUntilReady() await entered.promise - const before = initializeRequests + const before = harness.count("initialize") if (action === "delete") await hub.deleteConnection("local", "global") if (action === "disable") await hub.toggleServerDisabled("local", true, "global") if (action === "dispose") await hub.dispose() - if (action === "cancel" || action === "cancel-delete") { - cancellationToken.isCancellationRequested = true - for (const listener of cancellationListeners) listener() - } + if (action === "cancel" || action === "cancel-delete") harness.cancel() if (action === "cancel-delete") await hub.deleteConnection("local", "global") - if (action === "timeout") { - const flow = [...hub["oauthFlows"].values()][0] - if (!flow) throw new Error("Missing reconnect flow") - flow.finish("timed-out") - } release.resolve() - await vi.waitFor(() => expect(hub["oauthFlows"].size).toBe(0)) - // The flow can finish after its watcher was removed by the external action. - await Promise.all(progress.mock.results.map((result) => result.value)) - await Promise.all(completions) + await harness.settle() + // A late code exchange must not save a token for a flow that ended. + if (phase === "exchange" && action !== "accept") expect(harness.values.size).toBe(0) if (action === "accept") { expect(hub.connections[0]?.server.status).toBe("connected") - if (phase === "reconnect") expect(initializeRequests).toBe(before) - else expect(initializeRequests).toBeGreaterThan(before) + if (phase === "reconnect") expect(harness.count("initialize")).toBe(before) + else expect(harness.count("initialize")).toBeGreaterThan(before) } else { - expect(initializeRequests).toBe(before) + expect(harness.count("initialize")).toBe(before) if (action === "disable") expect(hub.connections[0]?.server.disabled).toBe(true) - else if (action === "cancel" || action === "timeout") { + else if (action === "cancel") { expect(hub.connections).toHaveLength(1) expect(hub.connections[0]?.server.status).toBe("disconnected") expect(hub.connections[0]?.server.disabled).not.toBe(true) - expect(hub.connections[0]?.server.error).toBe( - t(action === "cancel" ? "mcp:oauth.flow.cancelled" : "mcp:oauth.flow.timedOut"), - ) + expect(hub.connections[0]?.server.error).toBe(t("mcp:oauth.flow.cancelled")) await vi.waitFor(() => expect(panelRows.at(-1)?.[0]).toMatchObject({ name: "local", @@ -249,7 +312,7 @@ describe("OAuth ownership through the HTTP boundary", () => { }), ) if (phase === "reconnect") { - cancellationToken.isCancellationRequested = false + harness.resetCancellation() await hub.restartConnection("local", "global") await vi.waitFor(() => expect(hub.connections[0]?.server.status).toBe("connected")) } @@ -257,16 +320,302 @@ describe("OAuth ownership through the HTTP boundary", () => { } } finally { release.resolve() - await hub.dispose() - if (previous === undefined) delete process.env.MCP_OAUTH_TEST_MODE - else process.env.MCP_OAUTH_TEST_MODE = previous - server.closeAllConnections() - await new Promise((resolve) => { - server.close(() => resolve()) - }) - await rm(directory, { recursive: true, force: true }) + await harness.close() + } + }, + 15000, + ) + + // Invariant: McpServerToggle.DisabledStays. The flag blocks continuations while the write is pending. + it.each(["disable", "delete"])( + "%s while the disable write is pending does not reconnect", + async (action) => { + const entered = deferred() + const release = deferred() + const exchange = deferred() + const held = deferred() + const harness = await startHarness({ + onToken: async () => { + entered.resolve() + await release.promise + }, + }) + const { hub } = harness + const write = hub["updateServerConfig"].bind(hub) + hub["updateServerConfig"] = async (...args) => { + held.resolve() + await exchange.promise + await write(...args) + } + try { + await entered.promise + const before = harness.count("initialize") + const toggle = hub.toggleServerDisabled("local", true, "global") + await held.promise + if (action === "delete") await hub.deleteConnection("local", "global") + release.resolve() + await harness.settle() + expect(harness.count("initialize")).toBe(before) + exchange.resolve() + await toggle + expect(harness.count("initialize")).toBe(before) + expect(hub.connections).toHaveLength(action === "delete" ? 0 : 1) + } finally { + release.resolve() + exchange.resolve() + await harness.close() + } + }, + 15000, + ) + + it("runs discovery again when a server that skipped discovery requires OAuth", async () => { + const harness = await startHarness({ knownNonOAuth: true }) + const reconnect = vi.spyOn( + harness.hub as unknown as { reconnectOAuthConnection: () => Promise }, + "reconnectOAuthConnection", + ) + try { + await harness.hub.waitUntilReady() + // The first reconnect has no flow. It is the rediscovery step. + expect(reconnect.mock.calls[0]).toHaveLength(2) + } finally { + await harness.close() + } + }, 15000) + + // The rediscovery reconnect has no flow, so only the removal revision can stop it. + it("does not reconnect a server that is deleted during the rediscovery cleanup", async () => { + const harness = await startHarness({ knownNonOAuth: true }) + const { hub } = harness + const reconnect = hub["reconnectOAuthConnection"].bind(hub) + const removals: Promise[] = [] + hub["reconnectOAuthConnection"] = (connection, config, flow) => { + const close = connection.transport.close.bind(connection.transport) + if (!flow) { + connection.transport.close = async () => { + connection.transport.close = close + // A user delete is a later event, so it arrives while the cleanup is pending. + await Promise.resolve() + removals.push(hub.deleteConnection("local", "global")) + await close() + } + } + return reconnect(connection, config, flow) + } + try { + await hub.waitUntilReady() + expect(removals).toHaveLength(1) + expect(hub.connections).toHaveLength(0) + // Only the first connect sends a request. + expect(harness.count("initialize")).toBe(1) + } finally { + await harness.close() + } + }, 15000) + + it("keeps the new row connected when the replaced transport closes late", async () => { + const harness = await startHarness({ savedToken: "stale" }) + const { hub } = harness + try { + await hub.waitUntilReady() + const old = hub.connections[0] + if (old?.type !== "connected") throw new Error("Missing connection") + const onclose = old.transport.onclose + await hub.restartConnection("local", "global") + await harness.settle() + await vi.waitFor(() => expect(hub.connections[0]?.server.status).toBe("connected")) + const posts = harness.panelRows.length + onclose?.() + expect(hub.connections[0]?.server.status).toBe("connected") + expect(harness.panelRows).toHaveLength(posts) + } finally { + await harness.close() + } + }, 15000) + + // Invariant: McpOAuthRefreshToken.NoLeak. The real SDK cannot refresh, so a 401 cannot start a loop. + it("does not refresh or loop when the SSE request returns HTTP 401", async () => { + const harness = await startHarness({ savedToken: "stale", getStatus: 401 }) + try { + harness.values.get(harness.url)!.tokens.refresh_token = "secret" + await harness.hub.restartConnection("local", "global") + await new Promise((resolve) => setTimeout(resolve, 500)) + expect(harness.count("token")).toBe(0) + expect(harness.count("GET")).toBeLessThanOrEqual(3) + } finally { + await harness.close() + } + }, 15000) + + // Invariant: McpOAuthFlowEnd.NoStaleWrite. A tool call is retried only after an accepted sign-in. + it.each(["accept", "cancel", "delete", "disable", "abort"])( + "%s during the sign-in that a rejected tool call starts", + async (action) => { + const entered = deferred() + const release = deferred() + let rejectTool = false + let browsers = 0 + const harness = await startHarness({ + onBrowser: async () => { + if (++browsers === 1) return + entered.resolve() + await release.promise + }, + onRequest: async (method) => { + if (method !== "tools/call" || !rejectTool) return + rejectTool = false + harness.values.delete(harness.url) + return 401 + }, + }) + const { hub } = harness + try { + await hub.waitUntilReady() + await harness.settle() + await vi.waitFor(() => expect(hub.connections[0]?.server.status).toBe("connected")) + rejectTool = true + let aborted = false + const call = hub + .callTool("local", "tool", {}, "global", () => aborted) + .then( + () => "resolved", + () => "rejected", + ) + await entered.promise + if (action === "cancel") harness.cancel() + if (action === "delete") await hub.deleteConnection("local", "global") + if (action === "disable") await hub.toggleServerDisabled("local", true, "global") + aborted = action === "abort" + release.resolve() + + expect(await call).toBe(action === "accept" ? "resolved" : "rejected") + expect(harness.count("tools/call")).toBe(action === "accept" ? 2 : 1) + await harness.settle() + } finally { + release.resolve() + await harness.close() } }, 15000, ) + + // A server that is still in setup has no row. A removal must stop that attempt too. + it.each([ + ["deleted", (hub: McpHub) => hub.deleteConnection("local", "global")], + ["removed from the settings", (hub: McpHub) => hub.updateServerConnections({}, "global")], + ])( + "does not connect a server that is %s during setup", + async (_label, remove) => { + const entered = deferred() + const release = deferred() + const harness = await startHarness({ + onDiscovery: async () => { + entered.resolve() + await release.promise + }, + }) + try { + await entered.promise + await remove(harness.hub) + release.resolve() + await harness.hub.waitUntilReady() + await harness.settle() + expect(harness.hub.connections).toHaveLength(0) + expect(harness.count("initialize")).toBe(0) + } finally { + release.resolve() + await harness.close() + } + }, + 15000, + ) + + // Invariants: McpOAuthPanelSettle.Settled, PanelMatches, and RowKept. + it.each(["after the new row", "before the new row"])( + "posts a disconnected row when the reconnect fails %s", + async (point) => { + let fail = () => {} + const harness = await startHarness({ + onToken: async () => fail(), + onRequest: async (method, token) => + point === "after the new row" && method === "initialize" && token === "accepted" ? 500 : undefined, + }) + if (point === "before the new row") { + fail = () => harness.storage.hasOAuthData.mockRejectedValueOnce(new Error("storage unavailable")) + } + try { + await harness.hub.waitUntilReady() + await harness.settle() + expect(harness.hub.connections).toHaveLength(1) + expect(harness.hub.connections[0]?.server.status).toBe("disconnected") + expect(harness.hub.connections[0]?.server.error).toBeTruthy() + await vi.waitFor(() => + expect(harness.panelRows.at(-1)?.[0]).toMatchObject({ name: "local", status: "disconnected" }), + ) + } finally { + await harness.close() + } + }, + 15000, + ) + + it("keeps the sign-in successful when a panel update fails", async () => { + const harness = await startHarness() + const { hub } = harness + const notify = hub["notifyWebviewOfServerChanges"].bind(hub) + let rejected = 0 + hub["notifyWebviewOfServerChanges"] = async () => { + // Fail each update that follows the token exchange. + if (harness.count("token")) { + rejected++ + throw new Error("panel closed") + } + await notify() + } + try { + await hub.waitUntilReady() + await harness.settle() + expect(rejected).toBeGreaterThan(0) + expect(hub.connections[0]?.server.status).toBe("connected") + await expect(Promise.all([hub.callTool("local", "tool", {}, "global")])).resolves.toHaveLength(1) + } finally { + await harness.close() + } + }, 15000) + + // Invariant: McpOAuthPanelSettle.Settled. A second 401 must not join a flow that has no more work. + it("does not stay connecting when a second 401 arrives while the retry limit error is posted", async () => { + const harness = await startHarness({ savedToken: "stale", onRequest: async () => 401 }) + const { hub } = harness + const notify = hub["notifyWebviewOfServerChanges"].bind(hub) + const joined: Promise[] = [] + hub["notifyWebviewOfServerChanges"] = async () => { + // A second 401 is a later event, so it arrives while the panel update is pending. + await Promise.resolve() + const connection = hub.connections[0] + if (!joined.length && connection?.type === "connected" && connection.server.error) { + connection.server.status = "connecting" + joined.push( + hub["_initiateOAuthFlow"]( + "local", + "global", + JSON.parse(connection.server.config), + connection.authProvider!, + connection, + ), + ) + } + await notify() + } + try { + await hub.waitUntilReady() + await vi.waitFor(() => expect(joined).toHaveLength(1), { timeout: 12000 }) + await Promise.all(joined) + await harness.settle() + expect(hub.connections[0]?.server.status).toBe("disconnected") + } finally { + await harness.close() + } + }, 30000) }) diff --git a/src/services/mcp/__tests__/mcp-server-toggle.integration.spec.ts b/src/services/mcp/__tests__/mcp-server-toggle.integration.spec.ts new file mode 100644 index 00000000000..bdaa9081c2d --- /dev/null +++ b/src/services/mcp/__tests__/mcp-server-toggle.integration.spec.ts @@ -0,0 +1,149 @@ +import { mkdtemp, readFile, rm, writeFile } from "fs/promises" +import { tmpdir } from "os" +import { join } from "path" +import delay from "delay" + +import type { ClineProvider } from "../../../core/webview/ClineProvider" +import { safeWriteJson } from "../../../utils/safeWriteJson" +import { McpHub } from "../McpHub" + +vi.mock("../../../utils/safeWriteJson", async (importOriginal) => { + const actual = await importOriginal() + return { safeWriteJson: vi.fn(actual.safeWriteJson) } +}) +vi.mock("delay", () => ({ default: vi.fn(async () => {}) })) +vi.mock("vscode", () => ({ + workspace: { + createFileSystemWatcher: () => ({ + onDidChange: vi.fn(), + onDidCreate: vi.fn(), + onDidDelete: vi.fn(), + dispose: vi.fn(), + }), + onDidSaveTextDocument: () => ({ dispose: vi.fn() }), + onDidChangeWorkspaceFolders: () => ({ dispose: vi.fn() }), + workspaceFolders: [], + }, + window: { showErrorMessage: vi.fn(), showInformationMessage: vi.fn(), showWarningMessage: vi.fn() }, +})) + +/** Starts a real hub with one stdio server that exits at once, so no test needs a live server. */ +async function startHub() { + const directory = await mkdtemp(join(tmpdir(), "mcp-toggle-")) + const settings = join(directory, "mcp_settings.json") + const config = { command: process.execPath, args: ["-e", ""] } + await writeFile(settings, JSON.stringify({ mcpServers: { local: { ...config, disabled: true } } })) + // The extension double supplies settings, panel updates, and the extension version. + const provider = { + ensureSettingsDirectoryExists: async () => directory, + postMessageToWebview: vi.fn(), + getState: async () => ({ mcpEnabled: true }), + context: { extension: { packageJSON: { version: "1" } } }, + } as unknown as ClineProvider + const hub = new McpHub(provider) + await hub.waitUntilReady() + return { + hub, + saved: async () => JSON.parse(await readFile(settings, "utf8")).mcpServers, + settings, + close: async () => { + await hub.dispose() + await rm(directory, { recursive: true, force: true }) + }, + } +} + +// Invariants: McpServerToggle.Consistent, DisabledStays, and NotStuck. +describe("MCP server toggle and restart", () => { + let harness: Awaited> + + beforeEach(async () => { + vi.mocked(safeWriteJson).mockClear() + harness = await startHub() + }) + + afterEach(async () => { + await harness.close() + }) + + const row = () => harness.hub.connections.find((connection) => connection.server.name === "local")!.server + + /** Puts a row in the "connecting" state, as during OAuth setup. */ + const setConnecting = async () => { + await writeFile(harness.settings, JSON.stringify({ mcpServers: { local: { command: "x" } } })) + row().disabled = false + row().status = "connecting" + } + + it("keeps the saved value after two failed disables", async () => { + await setConnecting() + vi.mocked(safeWriteJson).mockRejectedValue(new Error("disk full")) + const results = await Promise.allSettled([ + harness.hub.toggleServerDisabled("local", true, "global"), + harness.hub.toggleServerDisabled("local", true, "global"), + ]) + vi.mocked(safeWriteJson).mockReset() + + expect(results.map((result) => result.status)).toEqual(["rejected", "rejected"]) + expect(row().disabled).not.toBe(true) + }) + + it("does not leave the row connecting after a failed disable", async () => { + await setConnecting() + vi.mocked(safeWriteJson).mockRejectedValueOnce(new Error("disk full")) + + await expect(harness.hub.toggleServerDisabled("local", true, "global")).rejects.toThrow("disk full") + + expect(row().status).toBe("disconnected") + expect(row().error).toContain("disk full") + }) + + it("applies two toggles in the order of the requests", async () => { + const write = vi.mocked(safeWriteJson).getMockImplementation()! + vi.mocked(safeWriteJson).mockImplementationOnce(async (...args) => { + await new Promise((resolve) => setTimeout(resolve, 100)) + await write(...args) + }) + await Promise.all([ + harness.hub.toggleServerDisabled("local", false, "global"), + harness.hub.toggleServerDisabled("local", true, "global"), + ]) + + expect((await harness.saved()).local.disabled).toBe(true) + expect(harness.hub.connections).toHaveLength(1) + expect(row()).toMatchObject({ disabled: true, status: "disconnected" }) + }) + + it("keeps a server disabled when the disable arrives during the restart delay", async () => { + await harness.hub.toggleServerDisabled("local", false, "global") + vi.mocked(delay).mockImplementationOnce(async () => { + await harness.hub.toggleServerDisabled("local", true, "global") + }) + + await harness.hub.restartConnection("local", "global") + + expect((await harness.saved()).local.disabled).toBe(true) + expect(row()).toMatchObject({ disabled: true, status: "disconnected" }) + }, 15000) + + it("keeps a setting that another writer saved before the toggle write", async () => { + const write = vi.mocked(safeWriteJson).getMockImplementation()! + vi.mocked(safeWriteJson).mockImplementationOnce(async (...args) => { + const current = await harness.saved() + await writeFile(harness.settings, JSON.stringify({ mcpServers: { ...current, other: { command: "y" } } })) + await write(...args) + }) + + await harness.hub.toggleServerDisabled("local", true, "global") + + expect(Object.keys(await harness.saved())).toEqual(["local", "other"]) + }) + + it("does not add a server that the settings file no longer has", async () => { + await writeFile(harness.settings, JSON.stringify({ mcpServers: {} })) + + await expect(harness.hub.toggleServerDisabled("local", true, "global")).rejects.toThrow("not found") + + expect(await harness.saved()).toEqual({}) + }) +}) diff --git a/src/services/mcp/utils/__tests__/callbackServer.listener.spec.ts b/src/services/mcp/utils/__tests__/callbackServer.listener.spec.ts index 119beb6140c..442c79678c8 100644 --- a/src/services/mcp/utils/__tests__/callbackServer.listener.spec.ts +++ b/src/services/mcp/utils/__tests__/callbackServer.listener.spec.ts @@ -77,3 +77,18 @@ describe("startCallbackServer with a real listener", () => { } }) }) + +describe("stopCallbackServer with an unused socket", () => { + it("stops when a client holds a connection and sends no request", async () => { + const { server, port, result, cancel } = await startCallbackServer(0, STATE) + const cancelled = result.catch(() => {}) + const client = await connectClient(port) + try { + await stopCallbackServer(server, cancel) + expect(server.listening).toBe(false) + } finally { + client.destroy() + await cancelled + } + }, 5000) +}) diff --git a/src/services/mcp/utils/callbackServer.ts b/src/services/mcp/utils/callbackServer.ts index 2ef72a31590..f437e70579c 100644 --- a/src/services/mcp/utils/callbackServer.ts +++ b/src/services/mcp/utils/callbackServer.ts @@ -228,6 +228,11 @@ export function startCallbackServer( export function stopCallbackServer(server: http.Server, cancel: () => void): Promise { cancel() return new Promise((resolve) => { - server.close(() => resolve()) + // A browser can hold an unused socket open. Close it after a short wait. + const timer = setTimeout(() => server.closeAllConnections?.(), 1000) + server.close(() => { + clearTimeout(timer) + resolve() + }) }) }