diff --git a/docs/architecture/tla/FileLockCleanup.DoubleRelease.cfg b/docs/architecture/tla/FileLockCleanup.DoubleRelease.cfg new file mode 100644 index 0000000000..cbee5efc56 --- /dev/null +++ b/docs/architecture/tla/FileLockCleanup.DoubleRelease.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + CleanupPolicy = "twice" + KeepOperationOutcome = TRUE + AwaitOperation = TRUE +INVARIANTS ReleaseAfterOperation ReleasedOnce PreservedOutcome diff --git a/docs/architecture/tla/FileLockCleanup.NoAwait.cfg b/docs/architecture/tla/FileLockCleanup.NoAwait.cfg new file mode 100644 index 0000000000..84702a9b90 --- /dev/null +++ b/docs/architecture/tla/FileLockCleanup.NoAwait.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + CleanupPolicy = "once" + KeepOperationOutcome = TRUE + AwaitOperation = FALSE +INVARIANTS ReleaseAfterOperation ReleasedOnce PreservedOutcome diff --git a/docs/architecture/tla/FileLockCleanup.NoRelease.cfg b/docs/architecture/tla/FileLockCleanup.NoRelease.cfg new file mode 100644 index 0000000000..2293a102b3 --- /dev/null +++ b/docs/architecture/tla/FileLockCleanup.NoRelease.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + CleanupPolicy = "never" + KeepOperationOutcome = TRUE + AwaitOperation = TRUE +INVARIANTS ReleaseAfterOperation ReleasedOnce PreservedOutcome diff --git a/docs/architecture/tla/FileLockCleanup.ReleaseMasksOutcome.cfg b/docs/architecture/tla/FileLockCleanup.ReleaseMasksOutcome.cfg new file mode 100644 index 0000000000..5b277f4828 --- /dev/null +++ b/docs/architecture/tla/FileLockCleanup.ReleaseMasksOutcome.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + CleanupPolicy = "once" + KeepOperationOutcome = FALSE + AwaitOperation = TRUE +INVARIANTS ReleaseAfterOperation ReleasedOnce PreservedOutcome diff --git a/docs/architecture/tla/FileLockCleanup.cfg b/docs/architecture/tla/FileLockCleanup.cfg new file mode 100644 index 0000000000..1fa8e57995 --- /dev/null +++ b/docs/architecture/tla/FileLockCleanup.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + CleanupPolicy = "once" + KeepOperationOutcome = TRUE + AwaitOperation = TRUE +INVARIANTS ReleaseAfterOperation ReleasedOnce PreservedOutcome diff --git a/docs/architecture/tla/FileLockCleanup.tla b/docs/architecture/tla/FileLockCleanup.tla new file mode 100644 index 0000000000..9955a47185 --- /dev/null +++ b/docs/architecture/tla/FileLockCleanup.tla @@ -0,0 +1,39 @@ +---- MODULE FileLockCleanup ---- +\* Source: withFileLock acquisition and callback. Sink: release count and returned outcome. +\* Failure: release is early, omitted, repeated, or hides the operation outcome. +\* Property test: utils/__tests__/fileLock.test.ts. Errors are input oracles. +\* Replay: all four cleanup mutations fail real-code tests. Original cleanup cases pass. +\* Review ratchet: added 0, covered 0, gap 0. This is a simplification contract. +\* Expect: fixed checks pass and each retained guard-removal check fails. +\* Cost: one agent; split from independent projections of the 192-state model. +\* Result: fixed passes in 24 states; all 4 failure variants fail. No new defect found. +\* Prior review or proposal came before these invariants. +\* This model does not prove the code. No new production change is included. +EXTENDS Naturals, FiniteSets +CONSTANTS CleanupPolicy, KeepOperationOutcome, AwaitOperation +VARIABLES cleanupPhase, operationOutcome, releaseFails, acquireFails, releaseCount, returned +vars == <> +Init == cleanupPhase = "acquire" /\ operationOutcome \in {"ok", "error"} + /\ releaseFails \in BOOLEAN /\ acquireFails \in BOOLEAN /\ releaseCount = 0 /\ returned = "none" +AcquireForWork == + /\ cleanupPhase = "acquire" + /\ cleanupPhase' = IF acquireFails THEN "done" ELSE "operation" + /\ returned' = IF acquireFails THEN "acquire-error" ELSE returned + /\ UNCHANGED <> +FinishOperation == + /\ cleanupPhase = "operation" /\ cleanupPhase' = "cleanup" + /\ UNCHANGED <> +FinishCleanup == + /\ cleanupPhase = "cleanup" /\ cleanupPhase' = "done" + /\ releaseCount' = CASE CleanupPolicy = "never" -> 0 [] CleanupPolicy = "twice" -> 2 [] OTHER -> 1 + /\ returned' = IF releaseFails /\ ~KeepOperationOutcome THEN "release-error" ELSE operationOutcome + /\ UNCHANGED <> +ReleaseEarly == + /\ cleanupPhase = "operation" /\ ~AwaitOperation /\ releaseCount = 0 /\ releaseCount' = 1 + /\ UNCHANGED <> +Next == AcquireForWork \/ FinishOperation \/ FinishCleanup \/ ReleaseEarly +Spec == Init /\ [][Next]_vars +ReleaseAfterOperation == cleanupPhase = "operation" => releaseCount = 0 +ReleasedOnce == cleanupPhase = "done" => releaseCount = IF acquireFails THEN 0 ELSE 1 +PreservedOutcome == cleanupPhase = "done" => returned = IF acquireFails THEN "acquire-error" ELSE operationOutcome +==== diff --git a/docs/architecture/tla/JsonFaultInjection.MissedFaultHook.cfg b/docs/architecture/tla/JsonFaultInjection.MissedFaultHook.cfg new file mode 100644 index 0000000000..025cfae47b --- /dev/null +++ b/docs/architecture/tla/JsonFaultInjection.MissedFaultHook.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANT CanonicalFixtures = FALSE +INVARIANT FaultReached diff --git a/docs/architecture/tla/JsonFaultInjection.cfg b/docs/architecture/tla/JsonFaultInjection.cfg new file mode 100644 index 0000000000..b50e9460e8 --- /dev/null +++ b/docs/architecture/tla/JsonFaultInjection.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANT CanonicalFixtures = TRUE +INVARIANT FaultReached diff --git a/docs/architecture/tla/JsonFaultInjection.tla b/docs/architecture/tla/JsonFaultInjection.tla new file mode 100644 index 0000000000..f7b133c275 --- /dev/null +++ b/docs/architecture/tla/JsonFaultInjection.tla @@ -0,0 +1,33 @@ +---- MODULE JsonFaultInjection ---- +\* Source: writer and TaskHistoryStore test paths. Sink: rename, stat, and unlink fault hooks. +\* Failure: a lexical fixture path does not match the canonical writer path. +\* Expect: canonical fixtures reach the hook; the alias variant fails. +\* Property tests: safeWriteJson.test.ts and safeWriteJson.interruption.test.ts in utils/__tests__. +\* Replay: an aliased TMPDIR reproduced all 15 Windows assertion failures on Linux. +\* After the fix, both suites pass all 53 cases with an aliased TMPDIR and the CI config. +\* CI ratchet: added 1, covered 0, gap 0. CI logs came before this invariant. +\* Cost: one agent, two fixture roots. Result: fixed passes in 6 states; the alias variant fails. No new defect found. +\* This checks path-spelling assumptions, not native path resolution or production code. +\* PR #2762 follow-up: covered 2, added 0, gap 0. The same alias mismatch bypassed unlink hooks. +\* Property test: core/task-persistence/__tests__/TaskHistoryStore.deleteSemantics.spec.ts. +\* Expect: resolving the fixture root restores all three missing unlink failures. +\* Replay before fix: an aliased TMPDIR reproduces all three Windows failures on Linux. +\* Wider alias replay: a read barrier also paused the delete helper at a different path spelling. +\* Property test: core/task-persistence/__tests__/TaskHistoryStore.realConcurrency.spec.ts. +\* Follow-up result: 240 tests pass with an aliased TMPDIR. No new production defect found. +\* Cost: one agent, two fixture roots; no model state was added. +\* Windows CI passes the writer suites; the TaskHistoryStore fixture fix awaits native CI. +EXTENDS Naturals +CONSTANT CanonicalFixtures +VARIABLES fixturePath, phase, hookObserved +vars == <> +WriterTarget == "canonical" +HookTarget == IF CanonicalFixtures THEN WriterTarget ELSE fixturePath +Init == fixturePath \in {"canonical", "alias"} /\ phase = "setup" /\ hookObserved = FALSE +Prepare == phase = "setup" /\ phase' = "ready" /\ UNCHANGED <> +Observe == phase = "ready" /\ phase' = "observed" + /\ hookObserved' = (HookTarget = WriterTarget) /\ UNCHANGED fixturePath +Next == Prepare \/ Observe +Spec == Init /\ [][Next]_vars +FaultReached == phase = "observed" => hookObserved +==== diff --git a/docs/architecture/tla/JsonFileLockIdentity.NoCanonicalLocks.cfg b/docs/architecture/tla/JsonFileLockIdentity.NoCanonicalLocks.cfg new file mode 100644 index 0000000000..e86062f4ba --- /dev/null +++ b/docs/architecture/tla/JsonFileLockIdentity.NoCanonicalLocks.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + CanonicalLocks = FALSE +INVARIANTS SameFileSerialized diff --git a/docs/architecture/tla/JsonFileLockIdentity.cfg b/docs/architecture/tla/JsonFileLockIdentity.cfg new file mode 100644 index 0000000000..e9931a7f7d --- /dev/null +++ b/docs/architecture/tla/JsonFileLockIdentity.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + CanonicalLocks = TRUE +INVARIANTS SameFileSerialized diff --git a/docs/architecture/tla/JsonFileLockIdentity.tla b/docs/architecture/tla/JsonFileLockIdentity.tla new file mode 100644 index 0000000000..bc3fd1aa89 --- /dev/null +++ b/docs/architecture/tla/JsonFileLockIdentity.tla @@ -0,0 +1,34 @@ +---- MODULE JsonFileLockIdentity ---- +\* Source: resolveFileLockPath. Sink: acquireFileLock and write, delete, and recovery paths. +\* Failure: operations on one stable file alias use different locks and overlap. +\* Property test: utils/__tests__/jsonFileLockIdentity.test.ts. +\* Follow-up to #2762: added 1, covered 0, gap 0. This was a supplied observation. +\* Replay: four leaf-link cases failed before the fix; all alias cases pass after it. +\* Path resolution is an oracle. Concurrent link changes remain outside scope. +\* Expect: fixed checks pass and each retained guard-removal check fails. +\* Cost: one agent; split from independent projections of the 192-state model. +\* Result: fixed passes in 4 states; all 1 failure variants fail. No new defect found. +\* Prior review or proposal came before these invariants. +\* Review #2762 through 293de2b9d6 #12: gap 1. Path resolution is an oracle in this lock model. +\* The native relative-link test failed before resolving the physical parent and passes after it. +\* The model cannot parse native paths. Expect unchanged four-state lock results; no new model defect expected. +\* This model does not prove the code. Cost: one regression test and one path expression. +EXTENDS Naturals, FiniteSets +CONSTANTS CanonicalLocks +VARIABLES active +vars == <> +Operations == {"write", "delete", "recover"} +LockKey(op) == IF CanonicalLocks \/ op = "write" THEN "real" ELSE "alias" +Init == active = {} +Acquire == + /\ \E op \in Operations \ active : + /\ \A peer \in active : LockKey(peer) # LockKey(op) + /\ active' = active \cup {op} + +Release == + /\ \E op \in active : active' = active \ {op} + +Next == Acquire \/ Release +Spec == Init /\ [][Next]_vars +SameFileSerialized == Cardinality(active) <= 1 +==== diff --git a/docs/architecture/tla/JsonWriteMetadata.NoFollowLink.cfg b/docs/architecture/tla/JsonWriteMetadata.NoFollowLink.cfg new file mode 100644 index 0000000000..cffdecd159 --- /dev/null +++ b/docs/architecture/tla/JsonWriteMetadata.NoFollowLink.cfg @@ -0,0 +1,10 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + PreserveMode = TRUE + FollowLink = FALSE + SkipMerge = TRUE +INVARIANTS KeepMode KeepLink SkipUnchanged + +CONSTANTS GuardRoot = TRUE FlushBeforeMode = TRUE +INVARIANTS WorkspaceOnly Flushed diff --git a/docs/architecture/tla/JsonWriteMetadata.NoPreserveMode.cfg b/docs/architecture/tla/JsonWriteMetadata.NoPreserveMode.cfg new file mode 100644 index 0000000000..4af8d7d4d0 --- /dev/null +++ b/docs/architecture/tla/JsonWriteMetadata.NoPreserveMode.cfg @@ -0,0 +1,10 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + PreserveMode = FALSE + FollowLink = TRUE + SkipMerge = TRUE +INVARIANTS KeepMode KeepLink SkipUnchanged + +CONSTANTS GuardRoot = TRUE FlushBeforeMode = TRUE +INVARIANTS WorkspaceOnly Flushed diff --git a/docs/architecture/tla/JsonWriteMetadata.NoSkipMerge.cfg b/docs/architecture/tla/JsonWriteMetadata.NoSkipMerge.cfg new file mode 100644 index 0000000000..0e2603b365 --- /dev/null +++ b/docs/architecture/tla/JsonWriteMetadata.NoSkipMerge.cfg @@ -0,0 +1,10 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + PreserveMode = TRUE + FollowLink = TRUE + SkipMerge = FALSE +INVARIANTS KeepMode KeepLink SkipUnchanged + +CONSTANTS GuardRoot = TRUE FlushBeforeMode = TRUE +INVARIANTS WorkspaceOnly Flushed diff --git a/docs/architecture/tla/JsonWriteMetadata.OutsideWorkspace.cfg b/docs/architecture/tla/JsonWriteMetadata.OutsideWorkspace.cfg new file mode 100644 index 0000000000..b16079e84b --- /dev/null +++ b/docs/architecture/tla/JsonWriteMetadata.OutsideWorkspace.cfg @@ -0,0 +1,10 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + PreserveMode = TRUE + FollowLink = TRUE + SkipMerge = TRUE +INVARIANTS KeepMode KeepLink SkipUnchanged + +CONSTANTS GuardRoot = FALSE FlushBeforeMode = TRUE +INVARIANTS WorkspaceOnly Flushed diff --git a/docs/architecture/tla/JsonWriteMetadata.ReadOnlyFlush.cfg b/docs/architecture/tla/JsonWriteMetadata.ReadOnlyFlush.cfg new file mode 100644 index 0000000000..73ca57e399 --- /dev/null +++ b/docs/architecture/tla/JsonWriteMetadata.ReadOnlyFlush.cfg @@ -0,0 +1,10 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + PreserveMode = TRUE + FollowLink = TRUE + SkipMerge = TRUE +INVARIANTS KeepMode KeepLink SkipUnchanged + +CONSTANTS GuardRoot = TRUE FlushBeforeMode = FALSE +INVARIANTS WorkspaceOnly Flushed diff --git a/docs/architecture/tla/JsonWriteMetadata.cfg b/docs/architecture/tla/JsonWriteMetadata.cfg new file mode 100644 index 0000000000..3de3af64dc --- /dev/null +++ b/docs/architecture/tla/JsonWriteMetadata.cfg @@ -0,0 +1,10 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + PreserveMode = TRUE + FollowLink = TRUE + SkipMerge = TRUE +INVARIANTS KeepMode KeepLink SkipUnchanged + +CONSTANTS GuardRoot = TRUE FlushBeforeMode = TRUE +INVARIANTS WorkspaceOnly Flushed diff --git a/docs/architecture/tla/JsonWriteMetadata.tla b/docs/architecture/tla/JsonWriteMetadata.tla new file mode 100644 index 0000000000..3cce8fd0a4 --- /dev/null +++ b/docs/architecture/tla/JsonWriteMetadata.tla @@ -0,0 +1,39 @@ +---- MODULE JsonWriteMetadata ---- +\* Source: safeWriteJson reads a path, mode, and merge result. Sink: replacement metadata. +\* Failure: replacement changes permissions, replaces a link, or writes unchanged data. +\* Property test: utils/__tests__/safeWriteJson.metadata.test.ts. +\* Review #2762: added 2 (#14, #16), covered 0, gap 1 (concurrent link changes). +\* Replay: old code fails mode, link, and unchanged-merge cases; the fix passes. +\* Expect: fixed checks pass and each retained guard-removal check fails. +\* Cost: one agent; split from independent projections of the 192-state model. +\* Result: fixed passes in 2 states; all 3 failure variants fail. No new defect found. +\* Prior review or proposal came before these invariants. +\* This model does not prove the code. +EXTENDS Naturals, FiniteSets +\* Review #2762 through 293de2b9d6 #5, #14, #17: added 2, gap 1 (native mode and link errors need tests). +\* Expect: a path outside the workspace cannot be replaced; a read-only target is flushed before mode restore. +\* Resolved containment is an oracle. A changed symlink during path resolution remains outside scope. +\* Source: project Hub, installer, and open-settings writes pass allowedRoot. Sink: safeWriteJson replacement. +\* Result: fixed passes in 2 states; all five failure variants fail. Cost: two input predicates, no extra fixed states. +CONSTANTS GuardRoot, FlushBeforeMode +CONSTANTS PreserveMode, FollowLink, SkipMerge +VARIABLES phase, modeKept, linkKept, unchangedKept, boundaryKept, flushed +vars == <> +Init == boundaryKept = TRUE /\ flushed = TRUE /\ phase = "read" /\ modeKept = TRUE /\ linkKept = TRUE /\ unchangedKept = TRUE +Replace == + /\ phase = "read" /\ phase' = "done" + + /\ \E restricted \in BOOLEAN, linked \in BOOLEAN, unchanged \in BOOLEAN, inside \in BOOLEAN : + /\ boundaryKept' = (inside \/ GuardRoot) + /\ flushed' = (~restricted \/ FlushBeforeMode) + /\ modeKept' = (~restricted \/ PreserveMode \/ (unchanged /\ SkipMerge)) + /\ linkKept' = (~linked \/ FollowLink \/ (unchanged /\ SkipMerge)) + /\ unchangedKept' = (~unchanged \/ SkipMerge) +Next == Replace +Spec == Init /\ [][Next]_vars +WorkspaceOnly == boundaryKept +Flushed == flushed +KeepMode == modeKept +KeepLink == linkKept +SkipUnchanged == unchangedKept +==== diff --git a/docs/architecture/tla/McpConnectionOwnership.DeleteReplacement.cfg b/docs/architecture/tla/McpConnectionOwnership.DeleteReplacement.cfg new file mode 100644 index 0000000000..3c9c9b979a --- /dev/null +++ b/docs/architecture/tla/McpConnectionOwnership.DeleteReplacement.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + KeepStoppedRow = TRUE + GuardSetup = TRUE + DetachBeforeClose = TRUE + 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 0000000000..fa475cb18d --- /dev/null +++ b/docs/architecture/tla/McpConnectionOwnership.LateDetach.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + KeepStoppedRow = TRUE + GuardSetup = TRUE + DetachBeforeClose = 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 0000000000..e646e011fa --- /dev/null +++ b/docs/architecture/tla/McpConnectionOwnership.LateSetup.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + KeepStoppedRow = TRUE + GuardSetup = FALSE + DetachBeforeClose = TRUE + 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 0000000000..edf7b96db5 --- /dev/null +++ b/docs/architecture/tla/McpConnectionOwnership.LostRecoveryRow.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + KeepStoppedRow = FALSE + GuardSetup = TRUE + DetachBeforeClose = TRUE + 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 0000000000..3061a6e73a --- /dev/null +++ b/docs/architecture/tla/McpConnectionOwnership.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + KeepStoppedRow = TRUE + GuardSetup = TRUE + DetachBeforeClose = TRUE + 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 0000000000..9eb4d580c0 --- /dev/null +++ b/docs/architecture/tla/McpConnectionOwnership.tla @@ -0,0 +1,85 @@ +---- 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: 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. +\* 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. +\* Review #2762 finding #9: covered. connectionKey retains the name and source at every writer. +\* The helper extraction changes no ownership transition. This model does not parse string keys. +\* Null result: source isolation tests and the fixed and sabotage configurations still pass. +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 == <> +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)) + /\ 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 <> +\* 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 + /\ 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/McpCredentialOwnership.BypassSharedFailure.cfg b/docs/architecture/tla/McpCredentialOwnership.BypassSharedFailure.cfg new file mode 100644 index 0000000000..7910a1b607 --- /dev/null +++ b/docs/architecture/tla/McpCredentialOwnership.BypassSharedFailure.cfg @@ -0,0 +1,11 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + LocalRefreshCache = FALSE + HandleSharedFailure = FALSE + ShareRefresh = TRUE + BindRegistration = TRUE + KeepMismatch = TRUE + GuardIssuer = TRUE + LogMismatch = TRUE +INVARIANTS CurrentCredentialResult SettledResult SharedRefresh BoundRegistration KeepCredential SafeDiscovery ReportMismatch diff --git a/docs/architecture/tla/McpCredentialOwnership.LocalRefreshCache.cfg b/docs/architecture/tla/McpCredentialOwnership.LocalRefreshCache.cfg new file mode 100644 index 0000000000..bc426047c8 --- /dev/null +++ b/docs/architecture/tla/McpCredentialOwnership.LocalRefreshCache.cfg @@ -0,0 +1,11 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + LocalRefreshCache = TRUE + HandleSharedFailure = TRUE + ShareRefresh = TRUE + BindRegistration = TRUE + KeepMismatch = TRUE + GuardIssuer = TRUE + LogMismatch = TRUE +INVARIANTS CurrentCredentialResult SettledResult SharedRefresh BoundRegistration KeepCredential SafeDiscovery ReportMismatch diff --git a/docs/architecture/tla/McpCredentialOwnership.NoBindRegistration.cfg b/docs/architecture/tla/McpCredentialOwnership.NoBindRegistration.cfg new file mode 100644 index 0000000000..a502edb2bd --- /dev/null +++ b/docs/architecture/tla/McpCredentialOwnership.NoBindRegistration.cfg @@ -0,0 +1,11 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + LocalRefreshCache = FALSE + HandleSharedFailure = TRUE + ShareRefresh = TRUE + BindRegistration = FALSE + KeepMismatch = TRUE + GuardIssuer = TRUE + LogMismatch = TRUE +INVARIANTS CurrentCredentialResult SettledResult SharedRefresh BoundRegistration KeepCredential SafeDiscovery ReportMismatch diff --git a/docs/architecture/tla/McpCredentialOwnership.NoGuardIssuer.cfg b/docs/architecture/tla/McpCredentialOwnership.NoGuardIssuer.cfg new file mode 100644 index 0000000000..2021ad39cf --- /dev/null +++ b/docs/architecture/tla/McpCredentialOwnership.NoGuardIssuer.cfg @@ -0,0 +1,11 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + LocalRefreshCache = FALSE + HandleSharedFailure = TRUE + ShareRefresh = TRUE + BindRegistration = TRUE + KeepMismatch = TRUE + GuardIssuer = FALSE + LogMismatch = TRUE +INVARIANTS CurrentCredentialResult SettledResult SharedRefresh BoundRegistration KeepCredential SafeDiscovery ReportMismatch diff --git a/docs/architecture/tla/McpCredentialOwnership.NoKeepMismatch.cfg b/docs/architecture/tla/McpCredentialOwnership.NoKeepMismatch.cfg new file mode 100644 index 0000000000..4a7a58936e --- /dev/null +++ b/docs/architecture/tla/McpCredentialOwnership.NoKeepMismatch.cfg @@ -0,0 +1,11 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + LocalRefreshCache = FALSE + HandleSharedFailure = TRUE + ShareRefresh = TRUE + BindRegistration = TRUE + KeepMismatch = FALSE + GuardIssuer = TRUE + LogMismatch = TRUE +INVARIANTS CurrentCredentialResult SettledResult SharedRefresh BoundRegistration KeepCredential SafeDiscovery ReportMismatch diff --git a/docs/architecture/tla/McpCredentialOwnership.NoLogMismatch.cfg b/docs/architecture/tla/McpCredentialOwnership.NoLogMismatch.cfg new file mode 100644 index 0000000000..d14a309c14 --- /dev/null +++ b/docs/architecture/tla/McpCredentialOwnership.NoLogMismatch.cfg @@ -0,0 +1,11 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + LocalRefreshCache = FALSE + HandleSharedFailure = TRUE + ShareRefresh = TRUE + BindRegistration = TRUE + KeepMismatch = TRUE + GuardIssuer = TRUE + LogMismatch = FALSE +INVARIANTS CurrentCredentialResult SettledResult SharedRefresh BoundRegistration KeepCredential SafeDiscovery ReportMismatch diff --git a/docs/architecture/tla/McpCredentialOwnership.NoShareRefresh.cfg b/docs/architecture/tla/McpCredentialOwnership.NoShareRefresh.cfg new file mode 100644 index 0000000000..9c6b9786f3 --- /dev/null +++ b/docs/architecture/tla/McpCredentialOwnership.NoShareRefresh.cfg @@ -0,0 +1,11 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + LocalRefreshCache = FALSE + HandleSharedFailure = TRUE + ShareRefresh = FALSE + BindRegistration = TRUE + KeepMismatch = TRUE + GuardIssuer = TRUE + LogMismatch = TRUE +INVARIANTS CurrentCredentialResult SettledResult SharedRefresh BoundRegistration KeepCredential SafeDiscovery ReportMismatch diff --git a/docs/architecture/tla/McpCredentialOwnership.cfg b/docs/architecture/tla/McpCredentialOwnership.cfg new file mode 100644 index 0000000000..f9ca5c02db --- /dev/null +++ b/docs/architecture/tla/McpCredentialOwnership.cfg @@ -0,0 +1,11 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + LocalRefreshCache = FALSE + HandleSharedFailure = TRUE + ShareRefresh = TRUE + BindRegistration = TRUE + KeepMismatch = TRUE + GuardIssuer = TRUE + LogMismatch = TRUE +INVARIANTS CurrentCredentialResult SettledResult SharedRefresh BoundRegistration KeepCredential SafeDiscovery ReportMismatch diff --git a/docs/architecture/tla/McpCredentialOwnership.tla b/docs/architecture/tla/McpCredentialOwnership.tla new file mode 100644 index 0000000000..136ac41f2f --- /dev/null +++ b/docs/architecture/tla/McpCredentialOwnership.tla @@ -0,0 +1,79 @@ +---- MODULE McpCredentialOwnership ---- +EXTENDS Naturals +\* Review #2762: added #9, #10, #11, #12, #13. The review came before this model. +\* Source: tokens reads stored data and discovery. Sink: refresh request, save, delete, and log. +\* Failure: two providers consume one rotating token and lose a result. +\* Failure: refresh mixes registrations, or stale discovery deletes current data. +\* Failure: discovery uses unsafe transport, or an issuer mismatch has no log. +\* Invariants: SharedRefresh, BoundRegistration, KeepCredential, SafeDiscovery, ReportMismatch. +\* Expect: separate requests, mixed registration, deletion, and unsafe discovery each fail. +\* Scope: two overlapping callers in one window share a storage service. Credential identity and responses are oracles. +\* Gap: separate windows and storage wrappers have no shared refresh or storage CAS. +\* Property tests: McpOAuthClientProvider.spec.ts, SecretStorageService.spec.ts, and utils/__tests__/oauth.spec.ts. +\* Simplification: use one pending request per credential. Derive requests from caller assignments. +\* Failure: a provider cache joins an older credential, or a duplicate caller loses the shared error. +\* Invariants: SharedRefresh, CurrentCredentialResult, and SettledResult. Result values are oracles. +\* Expect: one coordinator preserves success, rejection, retry, and replacement behavior. +\* Expect: the local-cache variant fails after replacement. Separate requests fail SharedRefresh. +\* Sources: https://pkg.go.dev/golang.org/x/sync/singleflight and RFC 9700 section 4.14.2. +\* Source: _loadTokens reads the storage key and token. Sink: refresh map lookup and caller result. +\* Result: fixed holds in 222 states. All seven variants fail, including local cache and skipped error handling. +\* Replay: restoring the former local cache fails two shared-error cases and the credential-replacement case. +\* Fixed provider and storage suites pass 177 tests. Identity cases check every storage reader and writer. +\* Finding: the local cache can join an old credential and return a rejection outside the shared handler. +\* The larger state count represents overlap, replacement, and response settlement. Requests are now derived. +\* Review ratchet: added 2, covered 0, gap 1. Repeated calls after settlement use real-code retry tests. +\* Cost: one agent, about 10 minutes. The proposal came before these invariants. No new dependency. +\* This model does not prove the code. +CONSTANTS ShareRefresh, BindRegistration, KeepMismatch, GuardIssuer, LogMismatch, LocalRefreshCache, HandleSharedFailure +Callers == {1, 2} +Slots == {1, 2} \X {0, 1, 2} +VARIABLES current, sameProvider, calls, seen, outcomes, returned, mixed, deleted, unsafe, silent +vars == <> +Init == current = 1 /\ sameProvider \in BOOLEAN + /\ calls = [p \in Callers |-> <<0, 0>>] /\ seen = [p \in Callers |-> 0] + /\ outcomes = [k \in Slots |-> "pending"] /\ returned = [p \in Callers |-> "waiting"] + /\ mixed = FALSE /\ deleted = FALSE /\ unsafe = FALSE /\ silent = FALSE +Requests == {calls[p] : p \in {c \in Callers : seen[c] # 0}} +Pending == {k \in Requests : outcomes[k] = "pending"} +Read == + /\ \E p \in Callers : + /\ seen[p] = 0 /\ (p = 1 \/ (seen[1] # 0 /\ Pending # {})) + /\ LET slot == IF LocalRefreshCache /\ sameProvider /\ Pending # {} + THEN CHOOSE k \in Pending : TRUE + ELSE <> + IN calls' = [calls EXCEPT ![p] = slot] + /\ seen' = [seen EXCEPT ![p] = current] + /\ UNCHANGED <> +Replace == + /\ current = 1 /\ current' = 2 + /\ UNCHANGED <> +Complete == + /\ \E k \in Pending, result \in {"ok", "retry", "rejected"} : outcomes' = [outcomes EXCEPT ![k] = result] + /\ UNCHANGED <> +Return == + /\ \E p \in Callers : + /\ seen[p] # 0 /\ returned[p] = "waiting" /\ outcomes[calls[p]] # "pending" + /\ returned' = [returned EXCEPT ![p] = + IF ~HandleSharedFailure /\ sameProvider /\ p = 2 /\ calls[1] = calls[2] + /\ outcomes[calls[p]] # "ok" THEN "thrown" ELSE outcomes[calls[p]]] + /\ UNCHANGED <> +Registration == + /\ \E changed \in BOOLEAN : mixed' = (changed /\ ~BindRegistration) + /\ UNCHANGED <> +Discovery == + /\ \E mismatch \in BOOLEAN, secure \in BOOLEAN : + /\ deleted' = (mismatch /\ ~KeepMismatch) + /\ unsafe' = (~secure /\ ~GuardIssuer) + /\ silent' = (mismatch /\ ~LogMismatch) + /\ UNCHANGED <> +Next == Read \/ Replace \/ Complete \/ Return \/ Registration \/ Discovery +Spec == Init /\ [][Next]_vars +SharedRefresh == \A p, q \in Callers : seen[p] # 0 /\ seen[p] = seen[q] => calls[p] = calls[q] +CurrentCredentialResult == \A p \in Callers : seen[p] # 0 => calls[p][1] = seen[p] +SettledResult == \A p \in Callers : returned[p] # "waiting" => returned[p] = outcomes[calls[p]] +BoundRegistration == ~mixed +KeepCredential == ~deleted +SafeDiscovery == ~unsafe +ReportMismatch == ~silent +==== diff --git a/docs/architecture/tla/McpOAuthFlowEnd.ClaimTimer.cfg b/docs/architecture/tla/McpOAuthFlowEnd.ClaimTimer.cfg new file mode 100644 index 0000000000..4022995490 --- /dev/null +++ b/docs/architecture/tla/McpOAuthFlowEnd.ClaimTimer.cfg @@ -0,0 +1,13 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + StopOnFinish = TRUE + StopOnClaim = 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.DeleteLeak.cfg b/docs/architecture/tla/McpOAuthFlowEnd.DeleteLeak.cfg new file mode 100644 index 0000000000..58969f1b95 --- /dev/null +++ b/docs/architecture/tla/McpOAuthFlowEnd.DeleteLeak.cfg @@ -0,0 +1,14 @@ +\* Sabotage. deleteConnection no longer ends the flow. The invariant must fail. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + StopOnFinish = TRUE + StopOnClaim = TRUE + CheckOutcome = TRUE + ClaimOnce = TRUE + GuardContinuation = TRUE + ReplaceEndsFlow = TRUE + DeleteEndsFlow = FALSE + DisposeEndsFlows = TRUE + ErrorEndsFlow = TRUE +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 new file mode 100644 index 0000000000..5bd59e2f1e --- /dev/null +++ b/docs/architecture/tla/McpOAuthFlowEnd.DisposeLeak.cfg @@ -0,0 +1,14 @@ +\* Sabotage. dispose no longer ends the flows. The invariant must fail. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + StopOnFinish = TRUE + StopOnClaim = TRUE + CheckOutcome = TRUE + ClaimOnce = TRUE + GuardContinuation = TRUE + ReplaceEndsFlow = TRUE + DeleteEndsFlow = TRUE + DisposeEndsFlows = FALSE + ErrorEndsFlow = TRUE +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 0000000000..2123ac5577 --- /dev/null +++ b/docs/architecture/tla/McpOAuthFlowEnd.DoubleClaim.cfg @@ -0,0 +1,13 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + StopOnFinish = TRUE + StopOnClaim = 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 new file mode 100644 index 0000000000..2ea53b1dbe --- /dev/null +++ b/docs/architecture/tla/McpOAuthFlowEnd.ErrorLeak.cfg @@ -0,0 +1,14 @@ +\* Sabotage. A reconnect error no longer ends the flow. The invariant must fail. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + StopOnFinish = TRUE + StopOnClaim = TRUE + CheckOutcome = TRUE + ClaimOnce = TRUE + GuardContinuation = TRUE + ReplaceEndsFlow = TRUE + DeleteEndsFlow = TRUE + DisposeEndsFlows = TRUE + ErrorEndsFlow = FALSE +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 0000000000..5b4d52c766 --- /dev/null +++ b/docs/architecture/tla/McpOAuthFlowEnd.FinishTimer.cfg @@ -0,0 +1,13 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + StopOnFinish = FALSE + StopOnClaim = 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 0000000000..18710457cb --- /dev/null +++ b/docs/architecture/tla/McpOAuthFlowEnd.IgnoreOutcome.cfg @@ -0,0 +1,13 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + StopOnFinish = TRUE + StopOnClaim = 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.ReplaceLeak.cfg b/docs/architecture/tla/McpOAuthFlowEnd.ReplaceLeak.cfg new file mode 100644 index 0000000000..cdc4063417 --- /dev/null +++ b/docs/architecture/tla/McpOAuthFlowEnd.ReplaceLeak.cfg @@ -0,0 +1,14 @@ +\* Sabotage. A replaced flow no longer ends. The invariant must fail. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + StopOnFinish = TRUE + StopOnClaim = TRUE + CheckOutcome = TRUE + ClaimOnce = TRUE + GuardContinuation = TRUE + ReplaceEndsFlow = FALSE + DeleteEndsFlow = TRUE + DisposeEndsFlows = TRUE + ErrorEndsFlow = TRUE +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 0000000000..ade484bfb3 --- /dev/null +++ b/docs/architecture/tla/McpOAuthFlowEnd.StaleContinuation.cfg @@ -0,0 +1,13 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + StopOnFinish = TRUE + StopOnClaim = 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 new file mode 100644 index 0000000000..135a4c8688 --- /dev/null +++ b/docs/architecture/tla/McpOAuthFlowEnd.cfg @@ -0,0 +1,13 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + StopOnFinish = TRUE + StopOnClaim = 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.tla b/docs/architecture/tla/McpOAuthFlowEnd.tla new file mode 100644 index 0000000000..9233dfe9e8 --- /dev/null +++ b/docs/architecture/tla/McpOAuthFlowEnd.tla @@ -0,0 +1,254 @@ +---- MODULE McpOAuthFlowEnd ---- +EXTENDS Naturals +\* 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 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 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 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 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. +\* 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. +\* 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 a claim keeps the timer armed. +\* Cost: one agent; two timer transitions and fake-time properties. +\* 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 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. +\* 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 +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 +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 + +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 + /\ 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 == + /\ UNCHANGED <> + /\ UNCHANGED <> + /\ UNCHANGED claims + /\ UNCHANGED <> + /\ 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 == + /\ UNCHANGED <> + /\ UNCHANGED <> + /\ UNCHANGED claims + /\ UNCHANGED <> + /\ 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 == + /\ UNCHANGED <> + /\ UNCHANGED <> + /\ UNCHANGED claims + /\ UNCHANGED <> + /\ 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 == + /\ UNCHANGED <> + /\ UNCHANGED <> + /\ UNCHANGED claims + /\ UNCHANGED <> + /\ 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 == + /\ UNCHANGED <> + /\ UNCHANGED <> + /\ UNCHANGED claims + /\ UNCHANGED <> + /\ 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 == + /\ 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 <> +ClaimTimer == + /\ timerPhase = "waiting" + /\ ChangeTimerPhase("claimed", StopOnClaim) +FinishTimer == + /\ timerPhase # "ended" + /\ ChangeTimerPhase("ended", StopOnFinish) +TimerOnlyWhileWaiting == timerArmed => timerPhase = "waiting" + +Next == + \/ FinishTimer + \/ ClaimTimer + \/ Settle + \/ RetryTool + \/ Claim + \/ Invalidate + \/ Continue + \/ StartFlow + \/ CallTool + \/ DeleteConnection + \/ WatcherError + \/ FlowEnds + \/ Dispose + +Spec == Init /\ [][Next]_vars + +TypeOK == + /\ timerPhase \in {"waiting", "claimed", "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 + /\ 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 = 1) + +\* A reconnect error never leaves its flow pending. +NoErrorLeak == ~errorLeak + +==== diff --git a/docs/architecture/tla/McpOAuthPanelSettle.DropRow.cfg b/docs/architecture/tla/McpOAuthPanelSettle.DropRow.cfg new file mode 100644 index 0000000000..b795861c46 --- /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 0000000000..87e8855fe8 --- /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 0000000000..1462062a49 --- /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 0000000000..538f2fc2a3 --- /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 0000000000..afa6dae49b --- /dev/null +++ b/docs/architecture/tla/McpOAuthPanelSettle.tla @@ -0,0 +1,60 @@ +---- 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. +\* Review #2762 finding #11: gap. Toast approval is outside this row model. +\* Real HTTP tests now cover Authenticate, dismiss with cancel, and approval timeout. +\* Cost: one agent; three table cases. The fixed and sabotage models remain unchanged. +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.NoEnsure.cfg b/docs/architecture/tla/McpOAuthRedirectUrl.NoEnsure.cfg new file mode 100644 index 0000000000..2e8385ca0d --- /dev/null +++ b/docs/architecture/tla/McpOAuthRedirectUrl.NoEnsure.cfg @@ -0,0 +1,7 @@ +\* 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 +INVARIANTS TypeOK NoBadOpen diff --git a/docs/architecture/tla/McpOAuthRedirectUrl.NoOverride.cfg b/docs/architecture/tla/McpOAuthRedirectUrl.NoOverride.cfg new file mode 100644 index 0000000000..4630388c8f --- /dev/null +++ b/docs/architecture/tla/McpOAuthRedirectUrl.NoOverride.cfg @@ -0,0 +1,7 @@ +\* Sabotage. The redirect_uri override is removed. The invariant must fail. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + FixRedirectUri = FALSE + EnsureListener = TRUE +INVARIANTS TypeOK NoBadOpen diff --git a/docs/architecture/tla/McpOAuthRedirectUrl.cfg b/docs/architecture/tla/McpOAuthRedirectUrl.cfg new file mode 100644 index 0000000000..5c79ccd11f --- /dev/null +++ b/docs/architecture/tla/McpOAuthRedirectUrl.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + FixRedirectUri = TRUE + EnsureListener = TRUE +INVARIANTS TypeOK NoBadOpen diff --git a/docs/architecture/tla/McpOAuthRedirectUrl.tla b/docs/architecture/tla/McpOAuthRedirectUrl.tla new file mode 100644 index 0000000000..8b2de0e1af --- /dev/null +++ b/docs/architecture/tla/McpOAuthRedirectUrl.tla @@ -0,0 +1,86 @@ +---- 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 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: 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). +\* 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 + +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 + +\* Both cached registration and fresh DCR can start the listener. +RegisterClient == + /\ listenerPort' = 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/McpOAuthRefreshToken.CloseBlocksRefresh.cfg b/docs/architecture/tla/McpOAuthRefreshToken.CloseBlocksRefresh.cfg new file mode 100644 index 0000000000..a1edcbb9c6 --- /dev/null +++ b/docs/architecture/tla/McpOAuthRefreshToken.CloseBlocksRefresh.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + CloseBlocksRefresh = TRUE + StripFromSdk = TRUE + KeepUnknownIssuer = TRUE + DropOnlyRejected = TRUE + BindDiscovery = TRUE + GuardSave = TRUE + ParseRejection = TRUE + EndpointPolicy = "advertised" +INVARIANTS RefreshAfterClose TypeOK NoLeak NoLostCredential BoundEndpoint AvailableEndpoint FreshSave ExactRejection + +CONSTANTS ClientAuthentication = TRUE SafeRegistration = TRUE +INVARIANTS CorrectClientAuth SafeClientRegistration diff --git a/docs/architecture/tla/McpOAuthRefreshToken.DropOnTransient.cfg b/docs/architecture/tla/McpOAuthRefreshToken.DropOnTransient.cfg new file mode 100644 index 0000000000..931c7cf3bc --- /dev/null +++ b/docs/architecture/tla/McpOAuthRefreshToken.DropOnTransient.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + CloseBlocksRefresh = FALSE + StripFromSdk = TRUE + KeepUnknownIssuer = TRUE + DropOnlyRejected = FALSE + BindDiscovery = TRUE + GuardSave = TRUE + ParseRejection = TRUE + EndpointPolicy = "advertised" +INVARIANTS RefreshAfterClose TypeOK NoLeak NoLostCredential BoundEndpoint AvailableEndpoint FreshSave ExactRejection + +CONSTANTS ClientAuthentication = TRUE SafeRegistration = TRUE +INVARIANTS CorrectClientAuth SafeClientRegistration diff --git a/docs/architecture/tla/McpOAuthRefreshToken.DropUnknownIssuer.cfg b/docs/architecture/tla/McpOAuthRefreshToken.DropUnknownIssuer.cfg new file mode 100644 index 0000000000..45e351ead5 --- /dev/null +++ b/docs/architecture/tla/McpOAuthRefreshToken.DropUnknownIssuer.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + CloseBlocksRefresh = FALSE + StripFromSdk = TRUE + KeepUnknownIssuer = FALSE + DropOnlyRejected = TRUE + BindDiscovery = TRUE + GuardSave = TRUE + ParseRejection = TRUE + EndpointPolicy = "advertised" +INVARIANTS RefreshAfterClose TypeOK NoLeak NoLostCredential BoundEndpoint AvailableEndpoint FreshSave ExactRejection + +CONSTANTS ClientAuthentication = TRUE SafeRegistration = TRUE +INVARIANTS CorrectClientAuth SafeClientRegistration diff --git a/docs/architecture/tla/McpOAuthRefreshToken.HttpsOnly.cfg b/docs/architecture/tla/McpOAuthRefreshToken.HttpsOnly.cfg new file mode 100644 index 0000000000..525a093bcb --- /dev/null +++ b/docs/architecture/tla/McpOAuthRefreshToken.HttpsOnly.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + CloseBlocksRefresh = FALSE + StripFromSdk = TRUE + KeepUnknownIssuer = TRUE + DropOnlyRejected = TRUE + BindDiscovery = TRUE + GuardSave = TRUE + ParseRejection = TRUE + EndpointPolicy = "https-only" +INVARIANTS RefreshAfterClose TypeOK NoLeak NoLostCredential BoundEndpoint AvailableEndpoint FreshSave ExactRejection + +CONSTANTS ClientAuthentication = TRUE SafeRegistration = TRUE +INVARIANTS CorrectClientAuth SafeClientRegistration diff --git a/docs/architecture/tla/McpOAuthRefreshToken.NoBindDiscovery.cfg b/docs/architecture/tla/McpOAuthRefreshToken.NoBindDiscovery.cfg new file mode 100644 index 0000000000..129322b437 --- /dev/null +++ b/docs/architecture/tla/McpOAuthRefreshToken.NoBindDiscovery.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + CloseBlocksRefresh = FALSE + StripFromSdk = TRUE + KeepUnknownIssuer = TRUE + DropOnlyRejected = TRUE + BindDiscovery = FALSE + GuardSave = TRUE + ParseRejection = TRUE + EndpointPolicy = "advertised" +INVARIANTS RefreshAfterClose TypeOK NoLeak NoLostCredential BoundEndpoint AvailableEndpoint FreshSave ExactRejection + +CONSTANTS ClientAuthentication = TRUE SafeRegistration = TRUE +INVARIANTS CorrectClientAuth SafeClientRegistration diff --git a/docs/architecture/tla/McpOAuthRefreshToken.NoGuardSave.cfg b/docs/architecture/tla/McpOAuthRefreshToken.NoGuardSave.cfg new file mode 100644 index 0000000000..9ba7ac8591 --- /dev/null +++ b/docs/architecture/tla/McpOAuthRefreshToken.NoGuardSave.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + CloseBlocksRefresh = FALSE + StripFromSdk = TRUE + KeepUnknownIssuer = TRUE + DropOnlyRejected = TRUE + BindDiscovery = TRUE + GuardSave = FALSE + ParseRejection = TRUE + EndpointPolicy = "advertised" +INVARIANTS RefreshAfterClose TypeOK NoLeak NoLostCredential BoundEndpoint AvailableEndpoint FreshSave ExactRejection + +CONSTANTS ClientAuthentication = TRUE SafeRegistration = TRUE +INVARIANTS CorrectClientAuth SafeClientRegistration diff --git a/docs/architecture/tla/McpOAuthRefreshToken.NoParseRejection.cfg b/docs/architecture/tla/McpOAuthRefreshToken.NoParseRejection.cfg new file mode 100644 index 0000000000..1b943d86fd --- /dev/null +++ b/docs/architecture/tla/McpOAuthRefreshToken.NoParseRejection.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + CloseBlocksRefresh = FALSE + StripFromSdk = TRUE + KeepUnknownIssuer = TRUE + DropOnlyRejected = TRUE + BindDiscovery = TRUE + GuardSave = TRUE + ParseRejection = FALSE + EndpointPolicy = "advertised" +INVARIANTS RefreshAfterClose TypeOK NoLeak NoLostCredential BoundEndpoint AvailableEndpoint FreshSave ExactRejection + +CONSTANTS ClientAuthentication = TRUE SafeRegistration = TRUE +INVARIANTS CorrectClientAuth SafeClientRegistration diff --git a/docs/architecture/tla/McpOAuthRefreshToken.SameOriginOnly.cfg b/docs/architecture/tla/McpOAuthRefreshToken.SameOriginOnly.cfg new file mode 100644 index 0000000000..cf934d4fbb --- /dev/null +++ b/docs/architecture/tla/McpOAuthRefreshToken.SameOriginOnly.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + CloseBlocksRefresh = FALSE + StripFromSdk = TRUE + KeepUnknownIssuer = TRUE + DropOnlyRejected = TRUE + BindDiscovery = TRUE + GuardSave = TRUE + ParseRejection = TRUE + EndpointPolicy = "same-origin" +INVARIANTS RefreshAfterClose TypeOK NoLeak NoLostCredential BoundEndpoint AvailableEndpoint FreshSave ExactRejection + +CONSTANTS ClientAuthentication = TRUE SafeRegistration = TRUE +INVARIANTS CorrectClientAuth SafeClientRegistration diff --git a/docs/architecture/tla/McpOAuthRefreshToken.SdkRefresh.cfg b/docs/architecture/tla/McpOAuthRefreshToken.SdkRefresh.cfg new file mode 100644 index 0000000000..475b680c9e --- /dev/null +++ b/docs/architecture/tla/McpOAuthRefreshToken.SdkRefresh.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + CloseBlocksRefresh = FALSE + StripFromSdk = FALSE + KeepUnknownIssuer = TRUE + DropOnlyRejected = TRUE + BindDiscovery = TRUE + GuardSave = TRUE + ParseRejection = TRUE + EndpointPolicy = "advertised" +INVARIANTS RefreshAfterClose TypeOK NoLeak NoLostCredential BoundEndpoint AvailableEndpoint FreshSave ExactRejection + +CONSTANTS ClientAuthentication = TRUE SafeRegistration = TRUE +INVARIANTS CorrectClientAuth SafeClientRegistration diff --git a/docs/architecture/tla/McpOAuthRefreshToken.UnsafeRegistration.cfg b/docs/architecture/tla/McpOAuthRefreshToken.UnsafeRegistration.cfg new file mode 100644 index 0000000000..76d0eef81b --- /dev/null +++ b/docs/architecture/tla/McpOAuthRefreshToken.UnsafeRegistration.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + CloseBlocksRefresh = FALSE + StripFromSdk = TRUE + KeepUnknownIssuer = TRUE + DropOnlyRejected = TRUE + BindDiscovery = TRUE + GuardSave = TRUE + ParseRejection = TRUE + EndpointPolicy = "advertised" +INVARIANTS RefreshAfterClose TypeOK NoLeak NoLostCredential BoundEndpoint AvailableEndpoint FreshSave ExactRejection + +CONSTANTS ClientAuthentication = TRUE SafeRegistration = FALSE +INVARIANTS CorrectClientAuth SafeClientRegistration diff --git a/docs/architecture/tla/McpOAuthRefreshToken.UnsafeTransport.cfg b/docs/architecture/tla/McpOAuthRefreshToken.UnsafeTransport.cfg new file mode 100644 index 0000000000..f858ae4aaf --- /dev/null +++ b/docs/architecture/tla/McpOAuthRefreshToken.UnsafeTransport.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + CloseBlocksRefresh = FALSE + StripFromSdk = TRUE + KeepUnknownIssuer = TRUE + DropOnlyRejected = TRUE + BindDiscovery = TRUE + GuardSave = TRUE + ParseRejection = TRUE + EndpointPolicy = "unguarded" +INVARIANTS RefreshAfterClose TypeOK NoLeak NoLostCredential BoundEndpoint AvailableEndpoint FreshSave ExactRejection + +CONSTANTS ClientAuthentication = TRUE SafeRegistration = TRUE +INVARIANTS CorrectClientAuth SafeClientRegistration diff --git a/docs/architecture/tla/McpOAuthRefreshToken.WrongClientAuth.cfg b/docs/architecture/tla/McpOAuthRefreshToken.WrongClientAuth.cfg new file mode 100644 index 0000000000..3850562574 --- /dev/null +++ b/docs/architecture/tla/McpOAuthRefreshToken.WrongClientAuth.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + CloseBlocksRefresh = FALSE + StripFromSdk = TRUE + KeepUnknownIssuer = TRUE + DropOnlyRejected = TRUE + BindDiscovery = TRUE + GuardSave = TRUE + ParseRejection = TRUE + EndpointPolicy = "advertised" +INVARIANTS RefreshAfterClose TypeOK NoLeak NoLostCredential BoundEndpoint AvailableEndpoint FreshSave ExactRejection + +CONSTANTS ClientAuthentication = FALSE SafeRegistration = TRUE +INVARIANTS CorrectClientAuth SafeClientRegistration diff --git a/docs/architecture/tla/McpOAuthRefreshToken.cfg b/docs/architecture/tla/McpOAuthRefreshToken.cfg new file mode 100644 index 0000000000..686ac30039 --- /dev/null +++ b/docs/architecture/tla/McpOAuthRefreshToken.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + CloseBlocksRefresh = FALSE + StripFromSdk = TRUE + KeepUnknownIssuer = TRUE + DropOnlyRejected = TRUE + BindDiscovery = TRUE + GuardSave = TRUE + ParseRejection = TRUE + EndpointPolicy = "advertised" +INVARIANTS RefreshAfterClose TypeOK NoLeak NoLostCredential BoundEndpoint AvailableEndpoint FreshSave ExactRejection + +CONSTANTS ClientAuthentication = TRUE SafeRegistration = TRUE +INVARIANTS CorrectClientAuth SafeClientRegistration diff --git a/docs/architecture/tla/McpOAuthRefreshToken.tla b/docs/architecture/tla/McpOAuthRefreshToken.tla new file mode 100644 index 0000000000..b5f5b2c741 --- /dev/null +++ b/docs/architecture/tla/McpOAuthRefreshToken.tla @@ -0,0 +1,110 @@ +---- MODULE McpOAuthRefreshToken ---- +\* Source: tokens reads SecretStorage and discovery; close stops the callback listener. +\* Sink: SDK token reads, credential requests, saved refresh responses, and rejected-token deletion. +\* Failures: the SDK receives a refresh token, temporary errors delete it, or discovery misdirects it. +\* Failures: transport blocks a valid advertised endpoint, stale refresh saves, or close prevents refresh. +\* Failure: an error description causes credential deletion without a parsed HTTP 400 invalid_grant. +\* Invariants: NoLeak, NoLostCredential, BoundEndpoint, AvailableEndpoint, FreshSave, RefreshAfterClose, ExactRejection. +\* Scope: one stored credential and one refresh. Discovery and request outcomes are oracles. +\* Gap: separate windows can write between a storage read and mutation. Storage has no CAS. +\* Property test: src/services/mcp/__tests__/McpOAuthClientProvider.spec.ts. +\* Review #2762: the supplied reviews added issuer, transport, freshness, rejection, and close checks. +\* Round 3: added 1 for finding #1. McpCredentialOwnership covers findings #9 through #13. +\* History: SDK refresh caused repeated token requests. Provider-owned refresh prevents that path. +\* History: endpoint compatibility, parsed rejection, and stored-token guards passed their replay cases. +\* Result before simplification: 24 states. The close guard and all nine prior variants fail. +\* Replay: close before or during refresh fails on old code and passes on the fix. +\* Simplification: consolidate the header. Keep all transitions and checked invariants. +\* Expect: the same states and variants remain. No new defect is expected. +\* Sources: RFC 8414 sections 2 and 3.3; RFC 9700 section 4.14.2. +\* Cost: one agent, shared with credential ownership. Simplification result: 24 states. All variants fail as expected. +\* Reviews came before the invariants. This model does not prove the code. +CONSTANTS StripFromSdk, KeepUnknownIssuer, DropOnlyRejected, + BindDiscovery, GuardSave, ParseRejection, EndpointPolicy, CloseBlocksRefresh +VARIABLES listenerClosed, refreshDenied, stored, sink, lost, disclosed, staleSave, falseDelete, deniedEndpoint, phase +\* Review #2762 through 293de2b9d6 #13 and #20: added 2; #15 diagnostics covered by native tests. +\* Source: exchange, refresh, and registration requests. Sink: credentials in the body or Authorization header. +\* Expect: both grants use the stored method; registration rejects unsafe transport and all redirects. +\* Result: fixed passes in 24 states; all twelve failure variants fail. Cost: two request predicates, no extra fixed states. +CONSTANTS ClientAuthentication, SafeRegistration +VARIABLES authCorrect, registrationLeaked +vars == <> + +Init == authCorrect = TRUE /\ registrationLeaked = FALSE /\ listenerClosed = FALSE /\ refreshDenied = FALSE /\ stored = TRUE /\ sink = "none" /\ lost = FALSE + /\ disclosed = FALSE /\ staleSave = FALSE /\ falseDelete = FALSE /\ deniedEndpoint = FALSE /\ phase = "idle" + +\* 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' = ~(temporary + \/ (live = "issuer" /\ result = "rejected")) + /\ lost' = (lost \/ temporary) + /\ UNCHANGED <> + +DiscoveryRequest == + /\ \E issuerMatches \in BOOLEAN, otherOrigin \in BOOLEAN, + transport \in {"https", "loopback", "unsafe"} : + LET allowed == transport # "unsafe" + endpointAccepted == CASE EndpointPolicy = "same-origin" -> allowed /\ ~otherOrigin + [] EndpointPolicy = "https-only" -> transport = "https" + [] EndpointPolicy = "unguarded" -> TRUE + [] OTHER -> allowed + accepted == (issuerMatches \/ ~BindDiscovery) /\ endpointAccepted + IN /\ disclosed' = (accepted /\ (~issuerMatches \/ ~allowed)) + /\ deniedEndpoint' = (issuerMatches /\ allowed /\ ~accepted) + /\ UNCHANGED <> +RefreshBegin == + /\ phase = "idle" /\ phase' = "fetch" + /\ UNCHANGED <> +Invalidate == + /\ phase = "fetch" /\ phase' \in {"invalidated"} + /\ UNCHANGED <> +CloseListener == + /\ ~listenerClosed /\ listenerClosed' = TRUE + /\ UNCHANGED <> +RefreshSave == + /\ phase \in {"fetch", "invalidated"} + /\ refreshDenied' = (phase = "fetch" /\ listenerClosed /\ CloseBlocksRefresh) + /\ staleSave' = (~GuardSave /\ phase # "fetch") /\ phase' = "done" + /\ UNCHANGED <> +RefreshError == + /\ \E status400 \in BOOLEAN, exactError \in BOOLEAN, mentionsError \in BOOLEAN : + falseDelete' = (~ParseRejection /\ mentionsError /\ ~(status400 /\ exactError)) + /\ UNCHANGED <> +\* Client auth uses one registration for both grants. Encoding is a native-code oracle. +TokenRequest == + /\ \E grant \in {"exchange", "refresh"}, method \in {"none", "post", "basic"} : + authCorrect' = (ClientAuthentication \/ (grant = "exchange" /\ method = "post") \/ method = "none") + /\ UNCHANGED <> +RegisterRequest == + /\ \E safeTransport \in BOOLEAN, redirect \in BOOLEAN : + registrationLeaked' = (~SafeRegistration /\ (~safeTransport \/ redirect)) + /\ UNCHANGED <> +CorrectClientAuth == authCorrect +SafeClientRegistration == ~registrationLeaked +Next == TokenRequest \/ RegisterRequest \/ CloseListener \/ SdkRead \/ ProviderRefresh \/ DiscoveryRequest \/ RefreshBegin \/ Invalidate \/ RefreshSave \/ RefreshError +Spec == Init /\ [][Next]_vars + +TypeOK == stored \in BOOLEAN /\ lost \in BOOLEAN /\ sink \in {"none", "issuer", "other"} +NoLeak == sink # "other" +NoLostCredential == ~lost + +BoundEndpoint == ~disclosed +AvailableEndpoint == ~deniedEndpoint +RefreshAfterClose == ~refreshDenied +FreshSave == ~staleSave +ExactRejection == ~falseDelete + +==== diff --git a/docs/architecture/tla/McpOAuthRetry.DiscoveryLoop.cfg b/docs/architecture/tla/McpOAuthRetry.DiscoveryLoop.cfg new file mode 100644 index 0000000000..b309c579b0 --- /dev/null +++ b/docs/architecture/tla/McpOAuthRetry.DiscoveryLoop.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANT GuardDiscovery = FALSE +CONSTANT ResetOnInitialize = FALSE +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 0000000000..68cdc6297c --- /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 new file mode 100644 index 0000000000..290f8360f2 --- /dev/null +++ b/docs/architecture/tla/McpOAuthRetry.ResetOnInitialize.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANT GuardDiscovery = TRUE +CONSTANT ResetOnInitialize = TRUE +CONSTANT ResetOnSuccess = TRUE +INVARIANTS TypeOK Bounded Fresh DiscoveryBounded diff --git a/docs/architecture/tla/McpOAuthRetry.cfg b/docs/architecture/tla/McpOAuthRetry.cfg new file mode 100644 index 0000000000..c0a354bba7 --- /dev/null +++ b/docs/architecture/tla/McpOAuthRetry.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANT GuardDiscovery = TRUE +CONSTANT ResetOnInitialize = FALSE +CONSTANT ResetOnSuccess = TRUE +INVARIANTS TypeOK Bounded Fresh DiscoveryBounded diff --git a/docs/architecture/tla/McpOAuthRetry.tla b/docs/architecture/tla/McpOAuthRetry.tla new file mode 100644 index 0000000000..38a701230f --- /dev/null +++ b/docs/architecture/tla/McpOAuthRetry.tla @@ -0,0 +1,56 @@ +---- MODULE McpOAuthRetry ---- +EXTENDS Naturals +\* 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. +\* 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 + /\ 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 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 <> +NoMetadata == + /\ (skippedDiscovery \/ ~GuardDiscovery) + /\ discoveryRetries < 2 + /\ skippedDiscovery' = FALSE + /\ discoveryRetries' = discoveryRetries + 1 + /\ UNCHANGED <> +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.GenericDuringAuth.cfg b/docs/architecture/tla/McpOAuthStatusHandoff.GenericDuringAuth.cfg new file mode 100644 index 0000000000..2f7a4a7b6d --- /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 new file mode 100644 index 0000000000..1809b21dd4 --- /dev/null +++ b/docs/architecture/tla/McpOAuthStatusHandoff.NoEarlyNotify.cfg @@ -0,0 +1,8 @@ +\* Sabotage. The status change no longer updates the panel. The invariant must fail. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + GuardTransport = TRUE + GuardConnecting = TRUE + NotifyOnConnected = FALSE +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 0000000000..2dcb12b433 --- /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 new file mode 100644 index 0000000000..66238f85f1 --- /dev/null +++ b/docs/architecture/tla/McpOAuthStatusHandoff.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + GuardTransport = TRUE + GuardConnecting = TRUE + NotifyOnConnected = TRUE +INVARIANTS TypeOK PanelShowsConnected NoStaleTransportError AuthStillConnecting diff --git a/docs/architecture/tla/McpOAuthStatusHandoff.tla b/docs/architecture/tla/McpOAuthStatusHandoff.tla new file mode 100644 index 0000000000..c14d4b98d7 --- /dev/null +++ b/docs/architecture/tla/McpOAuthStatusHandoff.tla @@ -0,0 +1,105 @@ +---- 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. +\* 401 errors and generic HTTP errors use a separate stream-status oracle. +\* Expect: Fixed holds. NoEarlyNotify fails. +\* 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. +\* 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. +\* 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 +VARIABLES panelStatus \* status the panel last received +VARIABLES pendingLists \* list requests not finished yet (0 to 2) +VARIABLES listsArrived \* the list results were fetched + +VARIABLES streamStatus, staleError, interruptedAuth +vars == <> + +Init == + /\ streamStatus = "connecting" /\ staleError = FALSE /\ interruptedAuth = FALSE + /\ 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 == + /\ UNCHANGED <> + /\ 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 == + /\ 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 # "connecting" + 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 + /\ listsArrived \in BOOLEAN + +\* While the lists are still pending, the panel already shows connected. +PanelShowsConnected == (status = "connected" /\ ~listsArrived) => panelStatus = "connected" + +==== diff --git a/docs/architecture/tla/McpServerToggle.NoResume.cfg b/docs/architecture/tla/McpServerToggle.NoResume.cfg new file mode 100644 index 0000000000..ff9e5d94df --- /dev/null +++ b/docs/architecture/tla/McpServerToggle.NoResume.cfg @@ -0,0 +1,9 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Serialize = TRUE + Resume = FALSE + GuardRestart = TRUE +INVARIANTS TypeOK Consistent DisabledStays NotStuck +CONSTANT ExpandRestartIdentity = TRUE +INVARIANT ClearedCredential diff --git a/docs/architecture/tla/McpServerToggle.RawRestartIdentity.cfg b/docs/architecture/tla/McpServerToggle.RawRestartIdentity.cfg new file mode 100644 index 0000000000..c7bdc16a7f --- /dev/null +++ b/docs/architecture/tla/McpServerToggle.RawRestartIdentity.cfg @@ -0,0 +1,9 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Serialize = TRUE + Resume = TRUE + GuardRestart = TRUE +INVARIANTS TypeOK Consistent DisabledStays NotStuck +CONSTANT ExpandRestartIdentity = FALSE +INVARIANT ClearedCredential diff --git a/docs/architecture/tla/McpServerToggle.UnguardedRestart.cfg b/docs/architecture/tla/McpServerToggle.UnguardedRestart.cfg new file mode 100644 index 0000000000..54d415547e --- /dev/null +++ b/docs/architecture/tla/McpServerToggle.UnguardedRestart.cfg @@ -0,0 +1,9 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Serialize = TRUE + Resume = TRUE + GuardRestart = FALSE +INVARIANTS TypeOK Consistent DisabledStays NotStuck +CONSTANT ExpandRestartIdentity = TRUE +INVARIANT ClearedCredential diff --git a/docs/architecture/tla/McpServerToggle.Unordered.cfg b/docs/architecture/tla/McpServerToggle.Unordered.cfg new file mode 100644 index 0000000000..e927d389d8 --- /dev/null +++ b/docs/architecture/tla/McpServerToggle.Unordered.cfg @@ -0,0 +1,9 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Serialize = FALSE + Resume = TRUE + GuardRestart = TRUE +INVARIANTS TypeOK Consistent DisabledStays NotStuck +CONSTANT ExpandRestartIdentity = TRUE +INVARIANT ClearedCredential diff --git a/docs/architecture/tla/McpServerToggle.cfg b/docs/architecture/tla/McpServerToggle.cfg new file mode 100644 index 0000000000..9d74d2d3f0 --- /dev/null +++ b/docs/architecture/tla/McpServerToggle.cfg @@ -0,0 +1,9 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Serialize = TRUE + Resume = TRUE + GuardRestart = TRUE +INVARIANTS TypeOK Consistent DisabledStays NotStuck +CONSTANT ExpandRestartIdentity = TRUE +INVARIANT ClearedCredential diff --git a/docs/architecture/tla/McpServerToggle.tla b/docs/architecture/tla/McpServerToggle.tla new file mode 100644 index 0000000000..7c6f4b75b2 --- /dev/null +++ b/docs/architecture/tla/McpServerToggle.tla @@ -0,0 +1,103 @@ +---- 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. +\* Review #2762 finding #5: sibling writers now merge under the lock. +\* McpSettingsWriters and its property tests cover this former gap. No toggle action changed. +\* 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. +\* Review #2762 follow-up: manual restart used raw URL/client ID templates to clear expanded credentials. +\* Source: restartConnection reads server.config. Sink: deleteOAuthData must use the expanded identity. +\* Expect: the raw-key variant fails when either field has a variable; the existing 114 fixed states remain. +\* Native test: mcp-server-toggle.integration.spec.ts covers literal, URL, client ID, and both variable cases. +\* Expansion is an oracle. Its native syntax is outside this model; the real helper is used by the test. +\* Review ratchet: added 1, covered 0, gap 0. The supplied finding came before the invariant. +\* Result: fixed passes in 114 states; all four failure variants fail. Native MCP suite passes 495 tests. +\* Replay: URL, client ID, and combined variable cases failed before the fix; the literal case passed. +\* Cost: one boolean stays TRUE in the fixed model, so it adds no fixed states. No independent defect found. +\* This model does not prove the code. +CONSTANTS ExpandRestartIdentity +CONSTANTS Serialize, Resume, GuardRestart +VARIABLES clearedIdentity +VARIABLES disk, flag, queue, sent, row, restart, removed +vars == <> + +Init == + /\ clearedIdentity = TRUE + /\ 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" + /\ \E variableUrl \in BOOLEAN, variableClient \in BOOLEAN : + clearedIdentity' = (ExpandRestartIdentity \/ ~(variableUrl \/ variableClient)) + /\ 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"} +ClearedCredential == clearedIdentity +NotStuck == (Idle /\ ~disk) => row # "abandoned" +==== diff --git a/docs/architecture/tla/McpSettingsApply.DropWatchers.cfg b/docs/architecture/tla/McpSettingsApply.DropWatchers.cfg new file mode 100644 index 0000000000..9b8c8633ee --- /dev/null +++ b/docs/architecture/tla/McpSettingsApply.DropWatchers.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS RefindRow = TRUE RawComparison = TRUE KeepWatchers = FALSE +INVARIANTS CurrentRow StableRow LiveWatchers diff --git a/docs/architecture/tla/McpSettingsApply.ExpandedComparison.cfg b/docs/architecture/tla/McpSettingsApply.ExpandedComparison.cfg new file mode 100644 index 0000000000..cf9e7fc76f --- /dev/null +++ b/docs/architecture/tla/McpSettingsApply.ExpandedComparison.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS RefindRow = TRUE RawComparison = FALSE KeepWatchers = TRUE +INVARIANTS CurrentRow StableRow LiveWatchers diff --git a/docs/architecture/tla/McpSettingsApply.StaleRow.cfg b/docs/architecture/tla/McpSettingsApply.StaleRow.cfg new file mode 100644 index 0000000000..ec0838ad0c --- /dev/null +++ b/docs/architecture/tla/McpSettingsApply.StaleRow.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS RefindRow = FALSE RawComparison = TRUE KeepWatchers = TRUE +INVARIANTS CurrentRow StableRow LiveWatchers diff --git a/docs/architecture/tla/McpSettingsApply.cfg b/docs/architecture/tla/McpSettingsApply.cfg new file mode 100644 index 0000000000..d8b21d0182 --- /dev/null +++ b/docs/architecture/tla/McpSettingsApply.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS RefindRow = TRUE RawComparison = TRUE KeepWatchers = TRUE +INVARIANTS CurrentRow StableRow LiveWatchers diff --git a/docs/architecture/tla/McpSettingsApply.tla b/docs/architecture/tla/McpSettingsApply.tla new file mode 100644 index 0000000000..f134120caa --- /dev/null +++ b/docs/architecture/tla/McpSettingsApply.tla @@ -0,0 +1,34 @@ +---- MODULE McpSettingsApply ---- +\* Source: queued disable/revoke and repeated watcher apply. Sink: the current row and its watchers. +\* Failures: a queued write updates a replaced row; an unchanged apply replaces a row or closes its watchers. +\* Invariants: CurrentRow, StableRow, LiveWatchers. Prior PR #2762 review supplied these three failures. +\* Review ratchet: covered 3, added 0, gap 0. No individual review thread URLs were supplied. +\* Split from McpSettingsWriters: these actions do not read or change the writer history. +\* Derive runtimeCurrent, rowKept, and watchersKept from applyPhase and the guard constants. +\* Each old state has exactly these values. Removing them preserves the projected behaviors. +\* Expect: four fixed states; all three failure variants fail. No independent defect is expected. +\* Native tests: mcp-server-toggle.integration.spec.ts checks a held apply, env config, and watcher identity. +\* Gap: native variable expansion and cross-source watcher delivery use real-code tests. +\* Gap: real VS Code delivery for a symlink target still needs an extension-host test. +\* Result: four fixed states; all three failure variants fail. State dumps match the prior apply projection. +\* Cost: one phase variable replaces four stored values. No independent defect found. +\* Native MCP suite: 491 tests pass. This model does not prove the code. +EXTENDS Naturals +CONSTANTS RefindRow, RawComparison, KeepWatchers +VARIABLE applyPhase +vars == <> +runtimeCurrent == CASE applyPhase = "idle" -> TRUE + [] applyPhase = "replaced" -> FALSE + [] OTHER -> RefindRow +rowKept == applyPhase # "done" \/ RawComparison +watchersKept == applyPhase # "done" \/ KeepWatchers +Init == applyPhase = "idle" +ReplaceRow == applyPhase = "idle" /\ applyPhase' = "replaced" +FinishWrite == applyPhase = "replaced" /\ applyPhase' = "written" +RepeatApply == applyPhase = "written" /\ applyPhase' = "done" +Next == ReplaceRow \/ FinishWrite \/ RepeatApply +Spec == Init /\ [][Next]_vars +CurrentRow == applyPhase \in {"written", "done"} => runtimeCurrent +StableRow == applyPhase = "done" => rowKept +LiveWatchers == applyPhase = "done" => watchersKept +==== diff --git a/docs/architecture/tla/McpSettingsEntryPoints.MergeCreate.cfg b/docs/architecture/tla/McpSettingsEntryPoints.MergeCreate.cfg new file mode 100644 index 0000000000..cef6d74d9f --- /dev/null +++ b/docs/architecture/tla/McpSettingsEntryPoints.MergeCreate.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS SaveFirst = TRUE QueueStartup = TRUE MergeCreate = FALSE ReportFailure = TRUE StopUnsafe = TRUE +INVARIANTS CurrentSwitch LatestApply KeepCreated VisibleFailure NoUnsafeFallback SafeFallback diff --git a/docs/architecture/tla/McpSettingsEntryPoints.QueueStartup.cfg b/docs/architecture/tla/McpSettingsEntryPoints.QueueStartup.cfg new file mode 100644 index 0000000000..06b09c2703 --- /dev/null +++ b/docs/architecture/tla/McpSettingsEntryPoints.QueueStartup.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS SaveFirst = TRUE QueueStartup = FALSE MergeCreate = TRUE ReportFailure = TRUE StopUnsafe = TRUE +INVARIANTS CurrentSwitch LatestApply KeepCreated VisibleFailure NoUnsafeFallback SafeFallback diff --git a/docs/architecture/tla/McpSettingsEntryPoints.ReportFailure.cfg b/docs/architecture/tla/McpSettingsEntryPoints.ReportFailure.cfg new file mode 100644 index 0000000000..c5667d9943 --- /dev/null +++ b/docs/architecture/tla/McpSettingsEntryPoints.ReportFailure.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS SaveFirst = TRUE QueueStartup = TRUE MergeCreate = TRUE ReportFailure = FALSE StopUnsafe = TRUE +INVARIANTS CurrentSwitch LatestApply KeepCreated VisibleFailure NoUnsafeFallback SafeFallback diff --git a/docs/architecture/tla/McpSettingsEntryPoints.SaveFirst.cfg b/docs/architecture/tla/McpSettingsEntryPoints.SaveFirst.cfg new file mode 100644 index 0000000000..e6a8fb8a2e --- /dev/null +++ b/docs/architecture/tla/McpSettingsEntryPoints.SaveFirst.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS SaveFirst = FALSE QueueStartup = TRUE MergeCreate = TRUE ReportFailure = TRUE StopUnsafe = TRUE +INVARIANTS CurrentSwitch LatestApply KeepCreated VisibleFailure NoUnsafeFallback SafeFallback diff --git a/docs/architecture/tla/McpSettingsEntryPoints.StopUnsafe.cfg b/docs/architecture/tla/McpSettingsEntryPoints.StopUnsafe.cfg new file mode 100644 index 0000000000..20816fb8ae --- /dev/null +++ b/docs/architecture/tla/McpSettingsEntryPoints.StopUnsafe.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS SaveFirst = TRUE QueueStartup = TRUE MergeCreate = TRUE ReportFailure = TRUE StopUnsafe = FALSE +INVARIANTS CurrentSwitch LatestApply KeepCreated VisibleFailure NoUnsafeFallback SafeFallback diff --git a/docs/architecture/tla/McpSettingsEntryPoints.cfg b/docs/architecture/tla/McpSettingsEntryPoints.cfg new file mode 100644 index 0000000000..9ed1fd074a --- /dev/null +++ b/docs/architecture/tla/McpSettingsEntryPoints.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS SaveFirst = TRUE QueueStartup = TRUE MergeCreate = TRUE ReportFailure = TRUE StopUnsafe = TRUE +INVARIANTS CurrentSwitch LatestApply KeepCreated VisibleFailure NoUnsafeFallback SafeFallback diff --git a/docs/architecture/tla/McpSettingsEntryPoints.tla b/docs/architecture/tla/McpSettingsEntryPoints.tla new file mode 100644 index 0000000000..bee874be1f --- /dev/null +++ b/docs/architecture/tla/McpSettingsEntryPoints.tla @@ -0,0 +1,89 @@ +---- MODULE McpSettingsEntryPoints ---- +\* Sources: updateSettings, McpHub constructor, openProjectMcpSettings, and registration. +\* Sinks: Hub reads, watcher apply, safeWriteJson, user messages, and SDK transport creation. +\* Failures: refresh reads an old switch; startup wins over an edit; create loses a competing file. +\* Failures: rejected writes stay silent; unsafe registration reaches the SDK fallback. +\* Invariants are the opposite of these failures. Review #2762 at a39023af2f supplied them first. +\* Expect: each failure variant fails. No independent defect is expected. +\* Review ratchet: added 5 (#1, #2, #7, #8, #9), covered 0, gap 11. +\* Gaps: #3 and #15-16 concern process and text. #4-6 and #10-14 need native tests or text checks. +\* Parsing, I/O, and registration outcomes are oracles. No parser is copied into the model. +\* The queue orders startup before a watcher that arrives after the initial read. +\* Result: fixed passes in 16 states. All five failure variants fail. No independent model defect was found. +\* Replay: both switch values fail before the fix. Startup, create, and unsafe fallback mutations fail native tests. +\* Earlier native replay rejected identity and rediscovery-reconnect mutations. It missed the connect-time entry. +\* Native replay required an error row when unsafe registration stops before transport creation. +\* Cost: one agent, about 13 minutes for the review fixes. No individual thread URLs were supplied. +\* Simplification: six independent histories share phase and value variables, without a cross-product. +\* Native tests: webviewMessageHandler.spec.ts and mcp-server-toggle.integration.spec.ts check ordering and errors. +\* Native tests: mcp-oauth-ownership.integration.spec.ts checks URL templates and the unsafe fallback. +\* This model checks source-to-sink order. It does not prove the code. +\* Refactor expectation: one error helper preserves VisibleFailure and each action's diagnostic text. +\* Direct initializeMcpServers calls must retain the same source queue and startup ordering. +\* Sources: refactoring.com/catalog/extractFunction.html and refactoring.com/catalog/inlineFunction.html. +\* Refactor result: fixed passes in 16 states and all five failure variants fail. Native suites pass 337 tests. +\* Cost: one shared error helper and two removed forwarding methods. No new defect was found. +\* Review follow-up: covered 0, added 0, gap 2 for the stale provider assertion and missing connect-time retry test. +\* The model has no native variable expansion or mock-call oracle. Keep both checks in native tests. +\* Expect: a stale rejected token exhausts retries without replacing the raw URL template in the row. +\* The exact sabotage passes configInjected to _initiateOAuthFlow from connectToServer. +\* The unsafe diagnostic now says "Unsafe OAuth endpoint" for both token and registration requests. +\* Follow-up result: the exact connect-time mutation fails the raw-template assertion after token retry exhaustion. +\* Restored code passes 5,122 tests in 164 related files, including ClineProvider.spec.ts. Types, lint, and format pass. +\* The fixed model passes in 16 states and all five failure configs fail. No independent model defect was found. +\* Cost: one agent, about four minutes. The standalone writer-model reduction is saved outside this PR worktree. +\* Review follow-up: covered 2 by LatestApply and KeepCreated; gap 1 for exact notification counts. +\* Expect: native replay rejects a project reload that bypasses the source queue. +\* Default creation now returns SKIP_JSON_WRITE for a parsed existing file, preserving its bytes and metadata. +\* Gap: the merge API gives null for both absent and malformed files. It cannot distinguish that narrow create race. +\* Result: 620 focused tests pass. The exact project queue-bypass mutation fails the pending-apply assertion. +\* Fixed model passes in 16 states; all five failure configs fail. No independent model defect was found. +\* Cost: one agent, three narrow changes. Required audit notes remain under this folder's AGENTS.md. +EXTENDS Naturals +CONSTANTS SaveFirst, QueueStartup, MergeCreate, ReportFailure, StopUnsafe +VARIABLES scenario, phase, stored, observed +vars == <> +Init == /\ scenario \in {"switch", "startup", "create", "reject", "unsafe", "safe"} + /\ phase = "start" /\ stored = "old" /\ observed = "none" +\* New and old stand for either requested Boolean and its opposite. +Save == /\ scenario = "switch" + /\ phase = IF SaveFirst THEN "start" ELSE "read" + /\ stored' = "new" /\ phase' = IF SaveFirst THEN "saved" ELSE "done" + /\ UNCHANGED <> +Refresh == /\ scenario = "switch" + /\ phase = IF SaveFirst THEN "saved" ELSE "start" + /\ observed' = stored /\ phase' = IF SaveFirst THEN "done" ELSE "read" + /\ UNCHANGED <> +ReadStartup == /\ scenario = "startup" /\ phase = "start" /\ phase' = "read" + /\ UNCHANGED <> +Watcher == /\ scenario = "startup" + /\ phase = IF QueueStartup THEN "loaded" ELSE "read" + /\ observed' = "new" /\ stored' = "new" + /\ phase' = IF QueueStartup THEN "done" ELSE "watched" + /\ UNCHANGED scenario +FinishStartup == /\ scenario = "startup" + /\ phase = IF QueueStartup THEN "read" ELSE "watched" + /\ observed' = "old" /\ phase' = IF QueueStartup THEN "loaded" ELSE "done" + /\ UNCHANGED <> +OtherWriter == /\ scenario = "create" /\ phase = "start" + /\ stored' = "existing" /\ phase' = "created" + /\ UNCHANGED <> +Create == /\ scenario = "create" /\ phase = "created" /\ phase' = "done" + /\ stored' = IF MergeCreate THEN stored ELSE "empty" + /\ UNCHANGED <> +Reject == /\ scenario = "reject" /\ phase = "start" /\ phase' = "done" + /\ observed' = IF ReportFailure THEN "message" ELSE "none" + /\ UNCHANGED <> +Registration == /\ scenario \in {"unsafe", "safe"} /\ phase = "start" + /\ phase' = "done" + /\ observed' = IF scenario = "unsafe" /\ StopUnsafe THEN "stopped" ELSE "SDK" + /\ UNCHANGED <> +Next == Save \/ Refresh \/ ReadStartup \/ Watcher \/ FinishStartup \/ OtherWriter \/ Create \/ Reject \/ Registration +Spec == Init /\ [][Next]_vars +CurrentSwitch == scenario = "switch" /\ phase = "done" => observed = stored +LatestApply == scenario = "startup" /\ phase = "done" => observed = stored +KeepCreated == scenario = "create" /\ phase = "done" => stored = "existing" +VisibleFailure == scenario = "reject" /\ phase = "done" => observed = "message" +NoUnsafeFallback == scenario = "unsafe" /\ phase = "done" => observed = "stopped" +SafeFallback == scenario = "safe" /\ phase = "done" => observed = "SDK" +==== diff --git a/docs/architecture/tla/McpSettingsInputs.DoubleNotice.cfg b/docs/architecture/tla/McpSettingsInputs.DoubleNotice.cfg new file mode 100644 index 0000000000..881ea45a99 --- /dev/null +++ b/docs/architecture/tla/McpSettingsInputs.DoubleNotice.cfg @@ -0,0 +1,12 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + AcceptNull = TRUE + ReportError = TRUE + ValidateInput = TRUE + SkipMissing = TRUE + PreserveExtra = TRUE +INVARIANTS AcceptEmpty ReportFailure RejectInvalid SkipAbsent KeepExtra + +CONSTANT ReportOnce = FALSE +INVARIANT OneNotice diff --git a/docs/architecture/tla/McpSettingsInputs.NoAcceptNull.cfg b/docs/architecture/tla/McpSettingsInputs.NoAcceptNull.cfg new file mode 100644 index 0000000000..421009e9a1 --- /dev/null +++ b/docs/architecture/tla/McpSettingsInputs.NoAcceptNull.cfg @@ -0,0 +1,12 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + AcceptNull = FALSE + ReportError = TRUE + ValidateInput = TRUE + SkipMissing = TRUE + PreserveExtra = TRUE +INVARIANTS AcceptEmpty ReportFailure RejectInvalid SkipAbsent KeepExtra + +CONSTANT ReportOnce = TRUE +INVARIANT OneNotice diff --git a/docs/architecture/tla/McpSettingsInputs.NoPreserveExtra.cfg b/docs/architecture/tla/McpSettingsInputs.NoPreserveExtra.cfg new file mode 100644 index 0000000000..fe8cd90006 --- /dev/null +++ b/docs/architecture/tla/McpSettingsInputs.NoPreserveExtra.cfg @@ -0,0 +1,12 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + AcceptNull = TRUE + ReportError = TRUE + ValidateInput = TRUE + SkipMissing = TRUE + PreserveExtra = FALSE +INVARIANTS AcceptEmpty ReportFailure RejectInvalid SkipAbsent KeepExtra + +CONSTANT ReportOnce = TRUE +INVARIANT OneNotice diff --git a/docs/architecture/tla/McpSettingsInputs.NoReportError.cfg b/docs/architecture/tla/McpSettingsInputs.NoReportError.cfg new file mode 100644 index 0000000000..a9c6dec872 --- /dev/null +++ b/docs/architecture/tla/McpSettingsInputs.NoReportError.cfg @@ -0,0 +1,12 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + AcceptNull = TRUE + ReportError = FALSE + ValidateInput = TRUE + SkipMissing = TRUE + PreserveExtra = TRUE +INVARIANTS AcceptEmpty ReportFailure RejectInvalid SkipAbsent KeepExtra + +CONSTANT ReportOnce = TRUE +INVARIANT OneNotice diff --git a/docs/architecture/tla/McpSettingsInputs.NoSkipMissing.cfg b/docs/architecture/tla/McpSettingsInputs.NoSkipMissing.cfg new file mode 100644 index 0000000000..d10b5c9a5f --- /dev/null +++ b/docs/architecture/tla/McpSettingsInputs.NoSkipMissing.cfg @@ -0,0 +1,12 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + AcceptNull = TRUE + ReportError = TRUE + ValidateInput = TRUE + SkipMissing = FALSE + PreserveExtra = TRUE +INVARIANTS AcceptEmpty ReportFailure RejectInvalid SkipAbsent KeepExtra + +CONSTANT ReportOnce = TRUE +INVARIANT OneNotice diff --git a/docs/architecture/tla/McpSettingsInputs.NoValidateInput.cfg b/docs/architecture/tla/McpSettingsInputs.NoValidateInput.cfg new file mode 100644 index 0000000000..f824963458 --- /dev/null +++ b/docs/architecture/tla/McpSettingsInputs.NoValidateInput.cfg @@ -0,0 +1,12 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + AcceptNull = TRUE + ReportError = TRUE + ValidateInput = FALSE + SkipMissing = TRUE + PreserveExtra = TRUE +INVARIANTS AcceptEmpty ReportFailure RejectInvalid SkipAbsent KeepExtra + +CONSTANT ReportOnce = TRUE +INVARIANT OneNotice diff --git a/docs/architecture/tla/McpSettingsInputs.cfg b/docs/architecture/tla/McpSettingsInputs.cfg new file mode 100644 index 0000000000..6f3ad9b703 --- /dev/null +++ b/docs/architecture/tla/McpSettingsInputs.cfg @@ -0,0 +1,12 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + AcceptNull = TRUE + ReportError = TRUE + ValidateInput = TRUE + SkipMissing = TRUE + PreserveExtra = TRUE +INVARIANTS AcceptEmpty ReportFailure RejectInvalid SkipAbsent KeepExtra + +CONSTANT ReportOnce = TRUE +INVARIANT OneNotice diff --git a/docs/architecture/tla/McpSettingsInputs.tla b/docs/architecture/tla/McpSettingsInputs.tla new file mode 100644 index 0000000000..d3f12a903f --- /dev/null +++ b/docs/architecture/tla/McpSettingsInputs.tla @@ -0,0 +1,61 @@ +---- MODULE McpSettingsInputs ---- +EXTENDS Naturals +\* Review #2762: added #15, #16, #20, #22, #23. The review came before this model. +\* Source: installMcp, removeMcp, and Hub settings writers read a file under the write lock. +\* Sink: safeWriteJson and the caller result. The parser and file errors are oracles. +\* Failure: installation rejects an empty server map, or removal hides a file error. +\* Failure: an invalid file changes, an absent server causes a write, or extra keys disappear. +\* Invariants: AcceptEmpty, ReportFailure, RejectInvalid, SkipAbsent, KeepExtra. +\* Expect: each removed guard fails its invariant. No independent finding is expected. +\* Property tests: SimpleInstaller.spec.ts and mcp-server-toggle.integration.spec.ts. +\* Gap: the test runner and assertion strength require mutation tests, not this input model. +\* Result: fixed and all five variants were checked. The fixed model passes and each variant fails. +\* Replay: null install, removal errors, and absent-server writes fail on old code and pass on the fix. +\* Missing and malformed writer cases preserve the file and row. Unknown keys and allow lists survive. +\* Review: added 5, covered 0, gap 1 for test strength. No independent defect was found. +\* Cost: one agent, shared with the settings review. This model does not prove the code. +\* Review #2762 through 293de2b9d6 #8: covered 1 by KeepExtra; native delete assertion now checks it. +\* Finding #16: added 1. Source: manager reports removal failure; sink: handler returns the failed result. +\* Expect: the handler must not show the manager's error again. Other diagnostics use native assertions. +\* Result: fixed passes in 61 states; all six failure variants fail. Cost: notice count adds no fixed states. +CONSTANTS ReportOnce +CONSTANTS AcceptNull, ReportError, ValidateInput, SkipMissing, PreserveExtra +VARIABLES phase, input, writer, extra, written, error, accepted, kept +vars == << phase, input, writer, extra, written, error, accepted, kept>> +\* Simplification expectation: derive notices from the selected input, writer, phase, and guard constants. +\* Before completion notices is zero; Apply deterministically assigns the expression below. +\* Expect 61 states and the same six failed variants. Result: both expectations hold. +\* State dumps match after dropping notices. Cost: remove one variable; 27 native input tests pass. +\* No independent defect found. The model does not prove the code. +notices == IF phase = "done" /\ writer = "remove" + /\ (input = "ioError" \/ (input = "invalid" /\ ValidateInput)) + THEN IF ReportOnce THEN 1 ELSE 2 + ELSE 0 +Init == phase = "select" /\ input = "valid" /\ writer = "install" /\ extra = FALSE + /\ written = FALSE /\ error = FALSE /\ accepted = FALSE /\ kept = TRUE +Select == + /\ phase = "select" /\ phase' = "apply" + /\ input' \in {"valid", "nullServers", "invalid", "ioError", "absent"} + /\ writer' \in {"install", "update", "remove"} /\ extra' \in BOOLEAN + /\ UNCHANGED << written, error, accepted, kept>> +Apply == + /\ phase = "apply" /\ phase' = "done" + /\ LET invalid == input = "invalid" + bad == input = "ioError" \/ (invalid /\ ValidateInput) + emptyDenied == input = "nullServers" /\ (writer # "install" \/ ~AcceptNull) + noChange == writer = "remove" /\ input = "absent" /\ SkipMissing + writes == ~bad /\ ~emptyDenied /\ ~noChange + IN /\ written' = writes + /\ error' = (bad /\ (writer # "remove" \/ ReportError)) + /\ accepted' = (~bad /\ ~emptyDenied) + /\ kept' = (~writes \/ ~extra \/ PreserveExtra) + /\ UNCHANGED <> +Next == Select \/ Apply +Spec == Init /\ [][Next]_vars +OneNotice == notices <= 1 +AcceptEmpty == phase = "done" /\ writer = "install" /\ input \in {"valid", "nullServers"} => accepted +ReportFailure == phase = "done" /\ input \in {"ioError", "invalid"} => error +RejectInvalid == phase = "done" /\ input = "invalid" => ~written +SkipAbsent == phase = "done" /\ writer = "remove" /\ input = "absent" => ~written +KeepExtra == kept +==== diff --git a/docs/architecture/tla/McpSettingsWriters.NoMerge.cfg b/docs/architecture/tla/McpSettingsWriters.NoMerge.cfg new file mode 100644 index 0000000000..c13384da12 --- /dev/null +++ b/docs/architecture/tla/McpSettingsWriters.NoMerge.cfg @@ -0,0 +1,10 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + SuppressMerged = FALSE + OrderApply = TRUE + Merge = FALSE + RequireServer = TRUE + UpdateSnapshot = TRUE + ObserveWatcher = TRUE +INVARIANTS AppliedEdit RecreatedVisible OrderedApply RemovedStays KeepToggle NoPhantom CurrentTimeout diff --git a/docs/architecture/tla/McpSettingsWriters.NoObserveWatcher.cfg b/docs/architecture/tla/McpSettingsWriters.NoObserveWatcher.cfg new file mode 100644 index 0000000000..2214f68b19 --- /dev/null +++ b/docs/architecture/tla/McpSettingsWriters.NoObserveWatcher.cfg @@ -0,0 +1,10 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + SuppressMerged = FALSE + OrderApply = TRUE + Merge = TRUE + RequireServer = TRUE + UpdateSnapshot = TRUE + ObserveWatcher = FALSE +INVARIANTS AppliedEdit RecreatedVisible OrderedApply RemovedStays KeepToggle NoPhantom CurrentTimeout diff --git a/docs/architecture/tla/McpSettingsWriters.NoRequireServer.cfg b/docs/architecture/tla/McpSettingsWriters.NoRequireServer.cfg new file mode 100644 index 0000000000..61736718b3 --- /dev/null +++ b/docs/architecture/tla/McpSettingsWriters.NoRequireServer.cfg @@ -0,0 +1,10 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + SuppressMerged = FALSE + OrderApply = TRUE + Merge = TRUE + RequireServer = FALSE + UpdateSnapshot = TRUE + ObserveWatcher = TRUE +INVARIANTS AppliedEdit RecreatedVisible OrderedApply RemovedStays KeepToggle NoPhantom CurrentTimeout diff --git a/docs/architecture/tla/McpSettingsWriters.NoUpdateSnapshot.cfg b/docs/architecture/tla/McpSettingsWriters.NoUpdateSnapshot.cfg new file mode 100644 index 0000000000..81222504af --- /dev/null +++ b/docs/architecture/tla/McpSettingsWriters.NoUpdateSnapshot.cfg @@ -0,0 +1,10 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + SuppressMerged = FALSE + OrderApply = TRUE + Merge = TRUE + RequireServer = TRUE + UpdateSnapshot = FALSE + ObserveWatcher = TRUE +INVARIANTS AppliedEdit RecreatedVisible OrderedApply RemovedStays KeepToggle NoPhantom CurrentTimeout diff --git a/docs/architecture/tla/McpSettingsWriters.SuppressMerged.cfg b/docs/architecture/tla/McpSettingsWriters.SuppressMerged.cfg new file mode 100644 index 0000000000..853204fea0 --- /dev/null +++ b/docs/architecture/tla/McpSettingsWriters.SuppressMerged.cfg @@ -0,0 +1,10 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + SuppressMerged = TRUE + OrderApply = TRUE + Merge = TRUE + RequireServer = TRUE + UpdateSnapshot = TRUE + ObserveWatcher = TRUE +INVARIANTS AppliedEdit RecreatedVisible OrderedApply RemovedStays KeepToggle NoPhantom CurrentTimeout diff --git a/docs/architecture/tla/McpSettingsWriters.UnorderedApply.cfg b/docs/architecture/tla/McpSettingsWriters.UnorderedApply.cfg new file mode 100644 index 0000000000..6caaf4bb10 --- /dev/null +++ b/docs/architecture/tla/McpSettingsWriters.UnorderedApply.cfg @@ -0,0 +1,10 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + SuppressMerged = FALSE + OrderApply = FALSE + Merge = TRUE + RequireServer = TRUE + UpdateSnapshot = TRUE + ObserveWatcher = TRUE +INVARIANTS AppliedEdit RecreatedVisible OrderedApply RemovedStays KeepToggle NoPhantom CurrentTimeout diff --git a/docs/architecture/tla/McpSettingsWriters.cfg b/docs/architecture/tla/McpSettingsWriters.cfg new file mode 100644 index 0000000000..eff850acde --- /dev/null +++ b/docs/architecture/tla/McpSettingsWriters.cfg @@ -0,0 +1,10 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + SuppressMerged = FALSE + OrderApply = TRUE + Merge = TRUE + RequireServer = TRUE + UpdateSnapshot = TRUE + ObserveWatcher = TRUE +INVARIANTS AppliedEdit RecreatedVisible OrderedApply RemovedStays KeepToggle NoPhantom CurrentTimeout diff --git a/docs/architecture/tla/McpSettingsWriters.tla b/docs/architecture/tla/McpSettingsWriters.tla new file mode 100644 index 0000000000..db2bfffce2 --- /dev/null +++ b/docs/architecture/tla/McpSettingsWriters.tla @@ -0,0 +1,96 @@ +---- MODULE McpSettingsWriters ---- +EXTENDS Naturals +\* Source: Hub mutations, SimpleInstaller, and file-change events read settings. +\* Sink: safeWriteJson commits the locked merge; watcher applies update the runtime rows. +\* Failures: a sibling write loses a toggle, a tool edit restores a removed row, or a timeout stays stale. +\* Failures: suppression hides an external edit or recreation, or an old watcher apply wins. +\* Invariants: KeepToggle, NoPhantom, RemovedStays, CurrentTimeout, AppliedEdit, RecreatedVisible, OrderedApply. +\* Supplied code-reading follow-up: retain whole-apply serialization and accept same-source action delay. +\* A watcher holds the queue through connectToServer. Disable and delete wait for completion or timeout. +\* This model checks ordering, not a bound on connection latency. No prompt-action invariant is claimed. +\* The held sibling connection test records the accepted delay. This is not a new review round. +\* Scope: one sibling mutation and one watcher history. Parsing and I/O remain oracles. +\* Review #2762 round 3: added 4, covered 0, gap 0 for #2, #3, #8, #18. Review was supplied first. +\* Gaps #5, #6, #17, #21: test strength and dead code require real-code checks. +\* Gap #7: PR splitting is a process choice. Gap #19: PR text requires a document check. +\* History: lock-held merges, missing-row checks, and runtime updates passed their regression cases. +\* Result before simplification: 96 states. All six failure variants failed as expected. +\* Replay: merged siblings, recreation, and held watcher applies fail on old code and pass on the fix. +\* Simplification: remove ObserveEdit because it is identical to AppliedEdit. No transition changes. +\* Expect: the same states and failure variants remain. No new defect is expected. +\* Property test: src/services/mcp/__tests__/mcp-server-toggle.integration.spec.ts. +\* Cost: one agent, shared with the refresh review. Simplification result: 96 states. All variants fail as expected. +\* Before the follow-up, the complete MCP suite passed 463 tests. This model does not prove the code. The supplied review has no individual thread URLs. +\* Review #2762, new commits through 293de2b9d6, #1-3: added 3; review supplied before the model. +\* Expect: a stale row misses disable/revoke; expanded comparison replaces a row; global cleanup loses watchers. +\* Source: queued toggle and watcher apply. Sink: the current row, its identity, and its watchers. +\* Real-code replay: mcp-server-toggle.integration.spec.ts holds an apply while requesting disable or revoke. +\* The repeat-apply test uses an env variable and checks row and watcher identity. +\* Before this split: fixed passes in 384 states; all nine failure variants fail. +\* The four apply phases are now checked separately in McpSettingsApply. +\* Findings #6 and #7: native queue and row identity assertions now cover failed, chained, and project operations. +\* Findings #9 and #10: queue waits are logged; project delete, project reload, and refresh use the source queue. +\* Gap #11: real VS Code link-target watcher delivery needs an extension-host test. +\* No independent model defect found. This model does not prove the code. +\* Native cases also keep same-name watchers apart by source and expand OAuth config only at its readers. +\* The one-source model cannot check native variable substitution; the real HTTP regression checks it. +\* Simplification expectation: independent projections have 96 writer states and four apply states. +\* No writer action reads apply state, and no apply action reads writer state; their actions commute. +\* Each combined action projects to the same action or a stutter. No cross-history invariant or fairness is checked. +\* Keep all nine failure variants across the two checks. No new defect is expected. +\* Sources: lamport.azurewebsites.net/pubs/auxiliary.pdf and refactoring.com/catalog/consolidateConditionalExpression.html. +\* Source change: consolidate new/changed connection setup; preserve explicit cleanup and diagnostic text. +\* Result: writer passes in 96 states; six writer variants fail. Native MCP tests pass 491 cases. +\* State dumps match the writer projection of all 384 prior states. Cost: two separate checks instead of one. +\* This is an independent projection, not an EXTENDS helper. No independent defect found. +CONSTANTS Merge, RequireServer, UpdateSnapshot, ObserveWatcher, SuppressMerged, OrderApply +VARIABLES disk, snapshot, phase, toggled, removed, watchPhase, seenEdit, visible, timeoutCurrent, applied +vars == <> +Init == + /\ disk = [disabled |-> FALSE, exists |-> TRUE] + /\ snapshot = disk /\ phase = "read" /\ toggled = FALSE + /\ removed = FALSE /\ watchPhase = "idle" /\ seenEdit = FALSE /\ visible = TRUE + /\ timeoutCurrent = TRUE /\ applied = "old" +Read == /\ phase = "read" /\ phase' = "write" /\ snapshot' = disk + /\ UNCHANGED <> +Toggle == /\ ~toggled /\ toggled' = TRUE /\ disk' = [disk EXCEPT !.disabled = TRUE] + /\ UNCHANGED <> +Sibling == /\ phase = "write" /\ phase' = "done" + /\ disk' = IF Merge THEN disk ELSE snapshot + /\ UNCHANGED <> +MissingTool == /\ phase = "read" /\ phase' = "done" + /\ disk' = [disk EXCEPT !.exists = ~RequireServer] + /\ snapshot' = [snapshot EXCEPT !.exists = FALSE] + /\ UNCHANGED <> +RemoveSibling == /\ phase = "write" /\ ~removed + /\ disk' = [disk EXCEPT !.exists = FALSE] /\ removed' = TRUE + /\ UNCHANGED <> +ObserveMerged == + /\ watchPhase = "idle" /\ watchPhase' = "merged" + /\ seenEdit' = (~SuppressMerged /\ ObserveWatcher) + /\ UNCHANGED <> +DeleteFile == + /\ watchPhase = "merged" /\ watchPhase' = "deleted" /\ visible' = FALSE + /\ UNCHANGED <> +RecreateFile == + /\ watchPhase = "deleted" /\ watchPhase' = "recreated" /\ visible' = ~SuppressMerged + /\ UNCHANGED <> +WriteTimeout == + /\ watchPhase = "idle" /\ watchPhase' = "written" + /\ timeoutCurrent' = UpdateSnapshot /\ applied' = "new" + /\ UNCHANGED <> +FinishOldApply == + /\ watchPhase = "written" /\ watchPhase' = "applied" + /\ applied' = IF OrderApply THEN applied ELSE "old" + /\ UNCHANGED <> +Next == Read \/ Toggle \/ Sibling \/ MissingTool \/ RemoveSibling + \/ ObserveMerged \/ DeleteFile \/ RecreateFile \/ WriteTimeout \/ FinishOldApply +Spec == Init /\ [][Next]_vars +KeepToggle == toggled => disk.disabled +NoPhantom == ~snapshot.exists => ~disk.exists +RemovedStays == removed => ~disk.exists +CurrentTimeout == watchPhase \in {"written", "applied"} => timeoutCurrent +AppliedEdit == watchPhase = "merged" => seenEdit +RecreatedVisible == watchPhase = "recreated" => visible +OrderedApply == watchPhase = "applied" => applied = "new" +==== diff --git a/docs/architecture/tla/McpToolAbort.Constant.cfg b/docs/architecture/tla/McpToolAbort.Constant.cfg new file mode 100644 index 0000000000..b4400d7f74 --- /dev/null +++ b/docs/architecture/tla/McpToolAbort.Constant.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANT Callback = "constant" +INVARIANT LiveAbort diff --git a/docs/architecture/tla/McpToolAbort.Inverted.cfg b/docs/architecture/tla/McpToolAbort.Inverted.cfg new file mode 100644 index 0000000000..e9dbe098bb --- /dev/null +++ b/docs/architecture/tla/McpToolAbort.Inverted.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANT Callback = "inverted" +INVARIANT LiveAbort diff --git a/docs/architecture/tla/McpToolAbort.cfg b/docs/architecture/tla/McpToolAbort.cfg new file mode 100644 index 0000000000..f55467ccc4 --- /dev/null +++ b/docs/architecture/tla/McpToolAbort.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANT Callback = "live" +INVARIANT LiveAbort diff --git a/docs/architecture/tla/McpToolAbort.tla b/docs/architecture/tla/McpToolAbort.tla new file mode 100644 index 0000000000..8fc99bb01d --- /dev/null +++ b/docs/architecture/tla/McpToolAbort.tla @@ -0,0 +1,26 @@ +---- MODULE McpToolAbort ---- +\* Source: Task.abort. UseMcpToolTool.handle passes a callback to McpHub.callTool. +\* Sink: the callback result after sign-in, before the retried tools/call. +\* Failure: a constant or inverted callback permits a stopped task, or blocks an active task. +\* Invariant: LiveAbort reads the current task flag for each callback invocation. +\* Scope: task status changes and callback reads. OAuth outcomes are separate model inputs. +\* Expect: the live callback holds; constant and inverted callbacks fail. +\* Order: PR #2762 finding #2 was read first. Review: added 1, covered 0, gap 0. +\* Property test: src/core/tools/__tests__/useMcpToolTool.spec.ts reads false, true, false. +\* Result: fixed holds in six states. Constant and Inverted each fail. +\* Replay: both callback tests fail for constant and inverted code mutations and pass after restore. +\* Cost: one agent, one boolean and one read result. No production defect was found. +CONSTANT Callback +VARIABLES aborted, read, value +vars == <> +Init == aborted = FALSE /\ read = FALSE /\ value = FALSE +Change == /\ aborted' = ~aborted /\ read' = FALSE /\ UNCHANGED value +Read == /\ read' = TRUE + /\ value' = CASE Callback = "live" -> aborted + [] Callback = "inverted" -> ~aborted + [] OTHER -> FALSE + /\ UNCHANGED aborted +Next == Change \/ Read +Spec == Init /\ [][Next]_vars +LiveAbort == read => value = aborted +==== diff --git a/src/core/task-persistence/__tests__/TaskHistoryStore.deleteSemantics.spec.ts b/src/core/task-persistence/__tests__/TaskHistoryStore.deleteSemantics.spec.ts index 875c7dcb9a..8d884c502f 100644 --- a/src/core/task-persistence/__tests__/TaskHistoryStore.deleteSemantics.spec.ts +++ b/src/core/task-persistence/__tests__/TaskHistoryStore.deleteSemantics.spec.ts @@ -70,7 +70,8 @@ describe("TaskHistoryStore best-effort deletion semantics", () => { let onWrite: ReturnType beforeEach(async () => { - storagePath = await fs.mkdtemp(path.join(os.tmpdir(), "task-history-delete-semantics-")) + // Fault hooks must use the same resolved paths as the JSON delete helper. + storagePath = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "task-history-delete-semantics-"))) stores = [] onWrite = vi.fn().mockResolvedValue(undefined) vi.mocked(withFileLock).mockImplementation(actualFileLock.withFileLock) diff --git a/src/core/task-persistence/__tests__/TaskHistoryStore.realConcurrency.spec.ts b/src/core/task-persistence/__tests__/TaskHistoryStore.realConcurrency.spec.ts index e637a7630e..92d9a1bca0 100644 --- a/src/core/task-persistence/__tests__/TaskHistoryStore.realConcurrency.spec.ts +++ b/src/core/task-persistence/__tests__/TaskHistoryStore.realConcurrency.spec.ts @@ -339,7 +339,10 @@ describe("TaskHistoryStore real cross-host locking", () => { }) it("serializes deletion after settlement reads disk without recreating the record", async () => { - const storagePath = await fs.mkdtemp(path.join(os.tmpdir(), "task-history-delete-during-settlement-")) + // The read barrier and delete helper must use the same resolved file path. + const storagePath = await fs.realpath( + await fs.mkdtemp(path.join(os.tmpdir(), "task-history-delete-during-settlement-")), + ) const storeA = new TaskHistoryStore(storagePath) const storeB = new TaskHistoryStore(storagePath) const action = createAction("action-a", "action A") diff --git a/src/core/tools/UseMcpToolTool.ts b/src/core/tools/UseMcpToolTool.ts index 0bd53af3c2..bf95d59b4a 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 0aad69c172..eb315eb1fc 100644 --- a/src/core/tools/__tests__/useMcpToolTool.spec.ts +++ b/src/core/tools/__tests__/useMcpToolTool.spec.ts @@ -302,7 +302,19 @@ 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), + ) + const isAborted: unknown = callToolMock.mock.calls[0][4] + if (typeof isAborted !== "function") throw new Error("Missing task abort callback") + for (const aborted of [false, true, false]) { + Object.defineProperty(mockTask, "abort", { value: aborted, configurable: true }) + expect(isAborted()).toBe(aborted) + } expect(mockTask.say).toHaveBeenCalledWith("mcp_server_request_started") expect(mockTask.say).toHaveBeenCalledWith("mcp_server_response", "Browser session started", []) }) @@ -699,7 +711,19 @@ 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), + ) + const isAborted: unknown = callToolMock.mock.calls[0][4] + if (typeof isAborted !== "function") throw new Error("Missing task abort callback") + for (const aborted of [false, true, false]) { + Object.defineProperty(mockTask, "abort", { value: aborted, configurable: true }) + expect(isAborted()).toBe(aborted) + } }) }) diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index b364b5baa7..6aa2f53907 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -6725,7 +6725,10 @@ describe("webviewMessageHandler no-floating-promises coverage", () => { removeInstalledMarketplaceItem: vi .fn() .mockResolvedValueOnce(undefined) - .mockRejectedValueOnce(new Error("remove failed")), + .mockImplementationOnce(async () => { + vscode.window.showErrorMessage("remove failed") + throw new Error("remove failed") + }), } const managerArgument = marketplaceManager as unknown as NonNullable< Parameters[2] @@ -6741,11 +6744,13 @@ describe("webviewMessageHandler no-floating-promises coverage", () => { { type: "removeInstalledMarketplaceItem", mpItem: item, mpInstallOptions: options }, managerArgument, ) + vi.mocked(vscode.window.showErrorMessage).mockClear() await webviewMessageHandler( provider, { type: "removeInstalledMarketplaceItem", mpItem: item, mpInstallOptions: options }, managerArgument, ) + expect(vscode.window.showErrorMessage).toHaveBeenCalledTimes(1) await webviewMessageHandler(provider, { type: "removeInstalledMarketplaceItem", mpItem: item, @@ -6875,12 +6880,16 @@ describe("Project MCP Settings", () => { const expectedRooDir = path.join("/test/workspace", ".roo") const expectedMcpPath = path.join(expectedRooDir, "mcp.json") - // Check that fs.mkdir was called with the correct path - expect(mockedFs.mkdir).toHaveBeenCalledWith(expectedRooDir, { recursive: true }) + // safeWriteJson owns directory creation after it checks the resolved target. + expect(mockedFs.mkdir).not.toHaveBeenCalled() expect(pathUtils.getWorkspacePath).toHaveBeenCalled() // Verify file was created with default content - expect(safeWriteJson).toHaveBeenCalledWith(expectedMcpPath, { mcpServers: {} }, { prettyPrint: true }) + expect(safeWriteJson).toHaveBeenCalledWith( + expectedMcpPath, + { mcpServers: {} }, + { prettyPrint: true, allowedRoot: "/test/workspace", merge: expect.any(Function) }, + ) // Check that openFile was called expect(openFileSpy).toHaveBeenCalledWith(expectedMcpPath) @@ -6900,28 +6909,28 @@ describe("Project MCP Settings", () => { expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("errors.no_workspace") }) - test("handles openProjectMcpSettings file creation error", async () => { - await provider.resolveWebviewView(mockWebviewView) - const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] + test.each(["Failed to create directory", "MCP settings path is outside the workspace"])( + "handles openProjectMcpSettings error: %s", + async (error) => { + await provider.resolveWebviewView(mockWebviewView) + const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] - // Mock workspace folders - ;(vscode.workspace as any).workspaceFolders = [{ uri: { fsPath: "/test/workspace" } }] - const pathUtils = await import("../../../utils/path") - vi.mocked(pathUtils.getWorkspacePath).mockReturnValue("/test/workspace") + // Mock workspace folders + ;(vscode.workspace as any).workspaceFolders = [{ uri: { fsPath: "/test/workspace" } }] + const pathUtils = await import("../../../utils/path") + vi.mocked(pathUtils.getWorkspacePath).mockReturnValue("/test/workspace") - // Mock fs functions to fail - const fs = await import("fs/promises") - const mockedFs = vi.mocked(fs) - mockedFs.mkdir.mockRejectedValue(new Error("Failed to create directory")) + vi.mocked(safeWriteJson).mockRejectedValueOnce(new Error(error)) - // Trigger openProjectMcpSettings - await messageHandler({ - type: "openProjectMcpSettings", - }) + // Trigger openProjectMcpSettings + await messageHandler({ + type: "openProjectMcpSettings", + }) - // Verify the translated error key is surfaced in test mode - expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("errors.create_json") - }) + // Verify the translated error key is surfaced in test mode + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("errors.create_json") + }, + ) }) describe("getTelemetryProperties", () => { diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index e1cc7dc844..13a918fc90 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -1,6 +1,9 @@ // npx vitest core/webview/__tests__/webviewMessageHandler.spec.ts import type { Mock } from "vitest" +import { safeWriteJson, SKIP_JSON_WRITE } from "../../../utils/safeWriteJson" + +vi.mock("../../../utils/safeWriteJson", () => ({ safeWriteJson: vi.fn(), SKIP_JSON_WRITE: Symbol("skip-json-write") })) // Mock dependencies - must come before imports vi.mock("../../../api/providers/fetchers/modelCache") @@ -1878,18 +1881,33 @@ describe("webviewMessageHandler - message dialog preferences", () => { }) describe("webviewMessageHandler - mcpEnabled", () => { - let mockMcpHub: any + let mockMcpHub: { handleMcpEnabledChange: Mock<(enabled: boolean) => Promise> } beforeEach(() => { vi.clearAllMocks() // Create a mock McpHub instance mockMcpHub = { - handleMcpEnabledChange: vi.fn().mockResolvedValue(undefined), + handleMcpEnabledChange: vi.fn<(enabled: boolean) => Promise>().mockResolvedValue(undefined), } // Ensure provider exposes getMcpHub and returns our mock - ;(mockClineProvider as any).getMcpHub = vi.fn().mockReturnValue(mockMcpHub) + mockClineProvider.getMcpHub = vi.fn().mockReturnValue(mockMcpHub) + }) + + it.each([true, false])("saves mcpEnabled=%s before the Hub reads it", async (enabled) => { + let stored = !enabled + vi.mocked(mockClineProvider.contextProxy.setValue).mockImplementationOnce(async (key, value) => { + expect(key).toBe("mcpEnabled") + stored = Boolean(value) + }) + mockMcpHub.handleMcpEnabledChange.mockImplementationOnce(async () => { + expect(stored).toBe(enabled) + }) + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { mcpEnabled: enabled }, + }) }) it("delegates enable=true to McpHub and posts updated state", async () => { @@ -1898,7 +1916,7 @@ describe("webviewMessageHandler - mcpEnabled", () => { updatedSettings: { mcpEnabled: true }, }) - expect((mockClineProvider as any).getMcpHub).toHaveBeenCalledTimes(1) + expect(mockClineProvider.getMcpHub).toHaveBeenCalledTimes(1) expect(mockMcpHub.handleMcpEnabledChange).toHaveBeenCalledTimes(1) expect(mockMcpHub.handleMcpEnabledChange).toHaveBeenCalledWith(true) expect(mockClineProvider.postStateToWebview).toHaveBeenCalledTimes(1) @@ -1910,21 +1928,21 @@ describe("webviewMessageHandler - mcpEnabled", () => { updatedSettings: { mcpEnabled: false }, }) - expect((mockClineProvider as any).getMcpHub).toHaveBeenCalledTimes(1) + expect(mockClineProvider.getMcpHub).toHaveBeenCalledTimes(1) expect(mockMcpHub.handleMcpEnabledChange).toHaveBeenCalledTimes(1) expect(mockMcpHub.handleMcpEnabledChange).toHaveBeenCalledWith(false) expect(mockClineProvider.postStateToWebview).toHaveBeenCalledTimes(1) }) it("handles missing McpHub instance gracefully and still posts state", async () => { - ;(mockClineProvider as any).getMcpHub = vi.fn().mockReturnValue(undefined) + mockClineProvider.getMcpHub = vi.fn().mockReturnValue(undefined) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { mcpEnabled: true }, }) - expect((mockClineProvider as any).getMcpHub).toHaveBeenCalledTimes(1) + expect(mockClineProvider.getMcpHub).toHaveBeenCalledTimes(1) expect(mockClineProvider.postStateToWebview).toHaveBeenCalledTimes(1) }) }) @@ -3318,3 +3336,49 @@ describe("updateSettings with the display settings", () => { expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("constructor", "x") }) }) + +// Every MCP write action must show the rejected path reason to the user. +it.each([ + ["deleteMcpServer", "deleteServer"], + ["updateMcpTimeout", "updateServerTimeout"], + ["toggleMcpServer", "toggleServerDisabled"], + ["toggleToolAlwaysAllow", "toggleToolAlwaysAllow"], + ["toggleToolEnabledForPrompt", "toggleToolEnabledForPrompt"], +] as const)("shows a write failure for %s", async (type, method) => { + const failure = vi.fn().mockRejectedValueOnce(new Error("MCP settings path is outside the workspace")) + // The Hub double supplies only the mutation used by this message. + mockClineProvider.getMcpHub = vi.fn().mockReturnValue({ [method]: failure }) + vi.mocked(vscode.window.showErrorMessage).mockClear() + await webviewMessageHandler(mockClineProvider, { + type, + timeout: 30, + serverName: "local", + source: "project", + toolName: "tool", + disabled: true, + }) + expect(failure).toHaveBeenCalledTimes(1) + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(expect.stringContaining("outside the workspace")) +}) + +// The existence check can finish before another writer creates the file. +it.each([null, { mcpServers: { existing: { command: "keep" } }, extra: true }])( + "keeps a competing settings file during default creation: %j", + async (existing) => { + const folders = vscode.workspace.workspaceFolders + Object.assign(vscode.workspace, { workspaceFolders: [{ uri: { fsPath: "/mock/workspace" } }] }) + vi.mocked(fsUtils.fileExistsAtPath).mockResolvedValueOnce(false) + vi.mocked(safeWriteJson).mockClear().mockResolvedValueOnce(undefined) + try { + await webviewMessageHandler(mockClineProvider, { type: "openProjectMcpSettings" }) + expect(safeWriteJson).toHaveBeenCalledTimes(1) + const [, incoming, options] = vi.mocked(safeWriteJson).mock.calls[0] + expect(options?.merge).toBeTypeOf("function") + expect(options?.merge?.(existing, incoming)).toEqual( + existing === null ? { mcpServers: {} } : SKIP_JSON_WRITE, + ) + } finally { + Object.assign(vscode.workspace, { workspaceFolders: folders }) + } + }, +) diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 6641ff259f..b2ffc07c75 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -1,4 +1,4 @@ -import { safeWriteJson } from "../../utils/safeWriteJson" +import { safeWriteJson, SKIP_JSON_WRITE } from "../../utils/safeWriteJson" import * as path from "path" import * as os from "os" import * as fs from "fs/promises" @@ -145,6 +145,12 @@ export const webviewMessageHandler = async ( const updateGlobalState = async (key: K, value: GlobalState[K]) => await provider.contextProxy.setValue(key, value) + const reportMcpWriteError = (message: string, error: unknown, logMessage?: string) => { + const errorMessage = `${message}: ${error instanceof Error ? error.message : String(error)}` + provider.log(logMessage ?? errorMessage) + void vscode.window.showErrorMessage(errorMessage) + } + const getCurrentCwd = () => { return provider.getCurrentTask()?.cwd || provider.cwd } @@ -889,11 +895,6 @@ export const webviewMessageHandler = async ( Terminal.setExecaShellPath(value as string | undefined) } else if (key === "mcpEnabled") { newValue = value ?? true - const mcpHub = provider.getMcpHub() - - if (mcpHub) { - await mcpHub.handleMcpEnabledChange(newValue as boolean) - } } else if (key === "experiments") { if (!value) { continue @@ -910,6 +911,9 @@ export const webviewMessageHandler = async ( } await provider.contextProxy.setValue(key as keyof RooCodeSettings, newValue) + if (key === "mcpEnabled") { + await provider.getMcpHub()?.handleMcpEnabledChange(newValue as boolean) + } } } catch (error) { failed = true @@ -2007,11 +2011,18 @@ export const webviewMessageHandler = async ( const mcpPath = path.join(rooDir, "mcp.json") try { - await fs.mkdir(rooDir, { recursive: true }) const exists = await fileExistsAtPath(mcpPath) if (!exists) { - await safeWriteJson(mcpPath, { mcpServers: {} }, { prettyPrint: true }) + await safeWriteJson( + mcpPath, + { mcpServers: {} }, + { + prettyPrint: true, + allowedRoot: workspaceFolder, + merge: (existing, incoming) => (existing === null ? incoming : SKIP_JSON_WRITE), + }, + ) } await openFile(mcpPath) @@ -2034,9 +2045,7 @@ export const webviewMessageHandler = async ( // Refresh the webview state await provider.postStateToWebview() } catch (error) { - const errorMessage = error instanceof Error ? error.message : String(error) - provider.log(`Failed to delete MCP server: ${errorMessage}`) - // Error messages are already handled by McpHub.deleteServer + reportMcpWriteError("Failed to delete MCP server", error) } break } @@ -2061,7 +2070,9 @@ export const webviewMessageHandler = async ( Boolean(message.alwaysAllow), ) } catch (error) { - provider.log( + reportMcpWriteError( + "Failed to change tool auto-approve", + error, `Failed to toggle auto-approve for tool ${message.toolName}: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`, ) } @@ -2078,7 +2089,9 @@ export const webviewMessageHandler = async ( Boolean(message.isEnabled), ) } catch (error) { - provider.log( + reportMcpWriteError( + "Failed to change tool prompt setting", + error, `Failed to toggle enabled for prompt for tool ${message.toolName}: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`, ) } @@ -2094,7 +2107,9 @@ export const webviewMessageHandler = async ( message.source as "global" | "project", ) } catch (error) { - provider.log( + reportMcpWriteError( + "Failed to change MCP server", + error, `Failed to toggle MCP server ${message.serverName}: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`, ) } @@ -2658,10 +2673,11 @@ export const webviewMessageHandler = async ( message.source as "global" | "project", ) } catch (error) { - provider.log( + reportMcpWriteError( + t("common:errors.update_server_timeout"), + error, `Failed to update timeout for ${message.serverName}: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`, ) - vscode.window.showErrorMessage(t("common:errors.update_server_timeout")) } } break @@ -3725,10 +3741,7 @@ export const webviewMessageHandler = async ( } catch (error) { console.error(`Error removing marketplace item: ${error}`) - // Show error message to user - vscode.window.showErrorMessage( - `Failed to remove marketplace item: ${error instanceof Error ? error.message : String(error)}`, - ) + // MarketplaceManager shows the removal error once. // Send error message to webview await provider.postMessageToWebview({ diff --git a/src/eslint-suppressions.json b/src/eslint-suppressions.json index e07b00bd6a..c45a72474e 100644 --- a/src/eslint-suppressions.json +++ b/src/eslint-suppressions.json @@ -976,7 +976,7 @@ }, "core/webview/__tests__/webviewMessageHandler.spec.ts": { "@typescript-eslint/no-explicit-any": { - "count": 35 + "count": 29 } }, "core/webview/messageEnhancer.ts": { @@ -1196,7 +1196,7 @@ }, "services/marketplace/SimpleInstaller.ts": { "@typescript-eslint/no-explicit-any": { - "count": 7 + "count": 5 } }, "services/marketplace/__tests__/MarketplaceManager.spec.ts": { @@ -1216,7 +1216,7 @@ }, "services/mcp/McpHub.ts": { "@typescript-eslint/no-explicit-any": { - "count": 7 + "count": 5 } }, "services/mcp/McpOAuthClientProvider.ts": { @@ -1231,7 +1231,7 @@ }, "services/mcp/__tests__/McpHub.spec.ts": { "@typescript-eslint/no-explicit-any": { - "count": 150 + "count": 142 } }, "services/mcp/__tests__/McpOAuthClientProvider.spec.ts": { @@ -1239,11 +1239,6 @@ "count": 18 } }, - "services/mcp/__tests__/SecretStorageService.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, "services/mcp/utils/__tests__/oauth.spec.ts": { "@typescript-eslint/no-explicit-any": { "count": 9 @@ -1256,7 +1251,7 @@ }, "services/mcp/utils/oauth.ts": { "@typescript-eslint/no-explicit-any": { - "count": 2 + "count": 1 } }, "services/mdm/__tests__/MdmService.spec.ts": { diff --git a/src/i18n/locales/ca/mcp.json b/src/i18n/locales/ca/mcp.json index 2bfbec328b..2ff24bf0b4 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 be492a0268..ed32e53c7d 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 e309bbd7b8..27be123169 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 a65d37a500..bf3f1ec508 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 ba05cc0e9c..6dcda367de 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 2536e79922..e014d9c1c6 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 cd9e0c3b36..8774952ad4 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 7927818cb3..c69291cc4e 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 e7850e6640..00f58c0afd 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 5422f14506..4e456d6c3c 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 a0898b3139..5b9826ae8c 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 44242522ad..28e121b353 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 ff019a6a40..f52a7d5c69 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 b1296fcbb8..138449325b 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 f753324d3c..f444fe8366 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 ca67e58fd2..ff4b901809 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 0fba9e23c8..40a8ded28f 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 b5468882d1..b5283d7fe7 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/marketplace/SimpleInstaller.ts b/src/services/marketplace/SimpleInstaller.ts index b1735c0214..471966c1e5 100644 --- a/src/services/marketplace/SimpleInstaller.ts +++ b/src/services/marketplace/SimpleInstaller.ts @@ -1,8 +1,12 @@ import * as vscode from "vscode" import * as path from "path" import * as fs from "fs/promises" +import { existsSync } from "fs" import * as yaml from "yaml" +import { z } from "zod" +import { safeWriteJson, SKIP_JSON_WRITE } from "../../utils/safeWriteJson" import type { MarketplaceItem, InstallMarketplaceItemOptions, McpParameter } from "@roo-code/types" +import { getErrorCode } from "../../utils/errorCode" import { GlobalFileNames } from "../../shared/globalFileNames" import { ensureSettingsDirectoryExists } from "../../utils/globalContext" import type { CustomModesManager } from "../../core/config/CustomModesManager" @@ -226,43 +230,34 @@ export class SimpleInstaller { const filePath = await this.getMcpFilePath(target) const mcpData = JSON.parse(contentToUse) - // Read existing file or create new structure - let existingData: any = { mcpServers: {} } - try { - const existing = await fs.readFile(filePath, "utf-8") - existingData = JSON.parse(existing) || { mcpServers: {} } - } catch (error: any) { - if (error.code === "ENOENT") { - // File doesn't exist, use default structure - existingData = { mcpServers: {} } - } else if (error instanceof SyntaxError) { - // JSON parsing error - don't overwrite the file! - const fileName = target === "project" ? ".roo/mcp.json" : "mcp-settings.json" - throw new Error( - `Cannot install MCP server: The ${fileName} file contains invalid JSON. ` + - `Please fix the syntax errors in the file before installing new servers.`, - ) - } else { - // Other unexpected errors - re-throw - throw error - } - } - - // Ensure mcpServers object exists - if (!existingData.mcpServers) { - existingData.mcpServers = {} - } - - // Use the item id as the server name const serverName = item.id - - // Add or update the single server - existingData.mcpServers[serverName] = mcpData - - // Write back to file - await fs.mkdir(path.dirname(filePath), { recursive: true }) - const jsonContent = JSON.stringify(existingData, null, 2) - await fs.writeFile(filePath, jsonContent, "utf-8") + let jsonContent = "" + + // Read the latest settings under the same lock as the write. + await safeWriteJson( + filePath, + {}, + { + prettyPrint: true, + allowedRoot: target === "project" ? vscode.workspace.workspaceFolders?.[0]?.uri.fsPath : undefined, + merge: (existing) => { + if (existing === null && existsSync(filePath)) { + const fileName = target === "project" ? ".roo/mcp.json" : "mcp-settings.json" + throw new Error( + `Cannot install MCP server: The ${fileName} file contains invalid JSON. ` + + "Please fix the syntax errors in the file before installing new servers.", + ) + } + const latest = z + .object({ mcpServers: z.record(z.string(), z.unknown()).nullish() }) + .passthrough() + .parse(existing ?? {}) + const updated = { ...latest, mcpServers: { ...latest.mcpServers, [serverName]: mcpData } } + jsonContent = JSON.stringify(updated, null, 2) + return updated + }, + }, + ) // Calculate approximate line number where the new server was added let line: number | undefined @@ -328,18 +323,31 @@ export class SimpleInstaller { const filePath = await this.getMcpFilePath(target) try { - const existing = await fs.readFile(filePath, "utf-8") - const existingData = JSON.parse(existing) - - if (existingData?.mcpServers) { - const serverName = item.id - delete existingData.mcpServers[serverName] - - // Always write back the file, even if empty - await fs.writeFile(filePath, JSON.stringify(existingData, null, 2), "utf-8") - } - } catch { - // File doesn't exist or other error, nothing to remove + await fs.readFile(filePath, "utf-8") + await safeWriteJson( + filePath, + {}, + { + prettyPrint: true, + allowedRoot: target === "project" ? vscode.workspace.workspaceFolders?.[0]?.uri.fsPath : undefined, + merge: (existing) => { + const parsed = z + .object({ mcpServers: z.record(z.string(), z.unknown()).nullish() }) + .passthrough() + .safeParse(existing) + if (!parsed.success) + throw new Error( + "Invalid MCP settings structure: expected an object with an mcpServers object", + ) + const latest = parsed.data + if (!latest.mcpServers || !Object.hasOwn(latest.mcpServers, item.id)) return SKIP_JSON_WRITE + delete latest.mcpServers[item.id] + return latest + }, + }, + ) + } catch (error: unknown) { + if (getErrorCode(error) !== "ENOENT") throw error } } diff --git a/src/services/marketplace/__tests__/MarketplaceManager.spec.ts b/src/services/marketplace/__tests__/MarketplaceManager.spec.ts index 003c258e5d..8d06aaeba6 100644 --- a/src/services/marketplace/__tests__/MarketplaceManager.spec.ts +++ b/src/services/marketplace/__tests__/MarketplaceManager.spec.ts @@ -1,5 +1,7 @@ // npx vitest services/marketplace/__tests__/MarketplaceManager.spec.ts +import * as vscode from "vscode" +import { t } from "../../../i18n" import type { MarketplaceItem } from "@roo-code/types" import { MarketplaceManager } from "../MarketplaceManager" @@ -274,6 +276,22 @@ describe("MarketplaceManager", () => { }) describe("removeInstalledMarketplaceItem", () => { + it("shows the reason when removal fails", async () => { + const item: MarketplaceItem = { + id: "test", + name: "Test", + description: "Test", + type: "mode", + content: "test", + } + vi.spyOn(manager["installer"], "removeItem").mockRejectedValueOnce(new Error("outside the workspace")) + await expect(manager.removeInstalledMarketplaceItem(item)).rejects.toThrow("outside the workspace") + expect(vscode.window.showErrorMessage).toHaveBeenCalledTimes(1) + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + t("marketplace:installation.removeError", { itemName: "Test", errorMessage: "outside the workspace" }), + ) + }) + it("should remove a mode item", async () => { const item: MarketplaceItem = { id: "test-mode", diff --git a/src/services/marketplace/__tests__/SimpleInstaller.projectPath.integration.spec.ts b/src/services/marketplace/__tests__/SimpleInstaller.projectPath.integration.spec.ts new file mode 100644 index 0000000000..f0ca7d261e --- /dev/null +++ b/src/services/marketplace/__tests__/SimpleInstaller.projectPath.integration.spec.ts @@ -0,0 +1,56 @@ +import * as fs from "fs/promises" +import * as path from "path" +import { tmpdir } from "os" +import * as vscode from "vscode" +import { SimpleInstaller } from "../SimpleInstaller" +import type { MarketplaceItem } from "@roo-code/types" + +vi.mock("vscode", () => ({ workspace: { workspaceFolders: [] }, Uri: { file: (fsPath: string) => ({ fsPath }) } })) + +// Invariant: JsonWriteMetadata.WorkspaceOnly. Both marketplace writers check the resolved path. +it + .skipIf(process.platform === "win32") + .each(["install", "remove"].flatMap((operation) => [true, false].map((inside) => ({ operation, inside }))))( + "checks $operation through a project symlink, inside=$inside", + async ({ operation, inside }) => { + const directory = await fs.mkdtemp(path.join(tmpdir(), "mcp-install-boundary-")) + try { + const workspace = path.join(directory, "workspace") + await fs.mkdir(path.join(workspace, ".roo"), { recursive: true }) + Object.assign(vscode.workspace, { + workspaceFolders: [{ uri: vscode.Uri.file(workspace), name: "test", index: 0 }], + }) + const target = path.join(inside ? workspace : directory, "target.json") + const before = JSON.stringify({ custom: true, mcpServers: { example: { command: "old" } } }) + await fs.writeFile(target, before) + await fs.symlink(target, path.join(workspace, ".roo", "mcp.json")) + // Project operations use the workspace API and do not read the extension context. + const installer = new SimpleInstaller({} as vscode.ExtensionContext) + const item: MarketplaceItem = { + id: "example", + name: "Example", + description: "Test", + type: "mcp", + url: "https://example.com", + content: '{"command":"new"}', + } + const pending = + operation === "install" + ? installer.installItem(item, { target: "project" }) + : installer.removeItem(item, { target: "project" }) + if (!inside) { + await expect(pending).rejects.toThrow("outside the workspace") + expect(await fs.readFile(target, "utf8")).toBe(before) + } else { + await pending + const saved = JSON.parse(await fs.readFile(target, "utf8")) + expect(saved.custom).toBe(true) + if (operation === "install") expect(saved.mcpServers.example.command).toBe("new") + else expect(saved.mcpServers).not.toHaveProperty("example") + } + } finally { + Object.assign(vscode.workspace, { workspaceFolders: [] }) + await fs.rm(directory, { recursive: true, force: true }) + } + }, +) diff --git a/src/services/marketplace/__tests__/SimpleInstaller.spec.ts b/src/services/marketplace/__tests__/SimpleInstaller.spec.ts index 94684056d4..b4fa5ce506 100644 --- a/src/services/marketplace/__tests__/SimpleInstaller.spec.ts +++ b/src/services/marketplace/__tests__/SimpleInstaller.spec.ts @@ -2,6 +2,8 @@ import { SimpleInstaller } from "../SimpleInstaller" import * as fs from "fs/promises" +import { existsSync } from "fs" +import { safeWriteJson } from "../../../utils/safeWriteJson" import * as yaml from "yaml" import * as vscode from "vscode" import * as os from "os" @@ -10,12 +12,36 @@ import type { CustomModesManager } from "../../../core/config/CustomModesManager import * as path from "path" import { fileExistsAtPath } from "../../../utils/fs" +vi.mock("fs", () => ({ existsSync: vi.fn() })) + vi.mock("fs/promises", () => ({ readFile: vi.fn(), writeFile: vi.fn(), mkdir: vi.fn(), rm: vi.fn(), })) +// Keep filesystem assertions while applying the lock-held merge to the latest read. +vi.mock("../../../utils/safeWriteJson", () => ({ + SKIP_JSON_WRITE: Symbol.for("skip-json-write-test"), + safeWriteJson: vi.fn( + async ( + filePath: string, + data: unknown, + options?: import("../../../utils/safeWriteJson").SafeWriteJsonOptions, + ) => { + let existing: unknown = null + try { + existing = JSON.parse(await fs.readFile(filePath, "utf-8")) + } catch (error: unknown) { + const missing = error && typeof error === "object" && "code" in error && error.code === "ENOENT" + if (!(error instanceof SyntaxError) && !missing) throw error + } + const merged = options?.merge ? options.merge(existing, data) : data + if (merged !== Symbol.for("skip-json-write-test")) + await fs.writeFile(filePath, JSON.stringify(merged), "utf-8") + }, + ), +})) vi.mock("os") vi.mock("vscode", () => ({ workspace: { @@ -47,6 +73,8 @@ describe("SimpleInstaller", () => { } as any installer = new SimpleInstaller(mockContext, mockCustomModesManager) vi.clearAllMocks() + mockFs.readFile.mockReset() + vi.mocked(existsSync).mockReturnValue(false) // Mock mkdir to always succeed mockFs.mkdir.mockResolvedValue(undefined as any) @@ -151,6 +179,61 @@ describe("SimpleInstaller", () => { }), } + // Invariant: McpSettingsWriters.KeepToggle. Each writer uses the locked settings value. + it.each(["install", "remove"])("keeps a sibling toggle during %s", async (writer) => { + const before = { + mcpServers: { sibling: { command: "node", disabled: false }, "test-mcp": { command: "node" } }, + } + const latest = { mcpServers: { ...before.mcpServers, sibling: { command: "node", disabled: true } } } + mockFs.readFile.mockResolvedValue(JSON.stringify(before)) + const write = vi.mocked(safeWriteJson).getMockImplementation()! + vi.mocked(safeWriteJson).mockImplementationOnce(async (...args) => { + mockFs.readFile.mockResolvedValue(JSON.stringify(latest)) + await write(...args) + }) + if (writer === "install") await installer.installItem(mockMcpItem, { target: "project" }) + else await installer.removeItem(mockMcpItem, { target: "project" }) + const written: unknown = JSON.parse(String(mockFs.writeFile.mock.calls[0][1])) + expect(written).toMatchObject({ mcpServers: { sibling: { disabled: true } } }) + if (writer === "remove") expect(written).not.toHaveProperty("mcpServers.test-mcp") + }) + + it.each([null, undefined])("installs with an empty mcpServers value %s", async (mcpServers) => { + mockFs.readFile.mockResolvedValue(JSON.stringify({ custom: true, mcpServers })) + await installer.installItem(mockMcpItem, { target: "project" }) + expect(JSON.parse(String(mockFs.writeFile.mock.calls[0][1]))).toMatchObject({ + custom: true, + mcpServers: { "test-mcp": { command: "test-server" } }, + }) + }) + + it.each(["permission", "malformed", "missing", "absent"])("handles removal with %s settings", async (input) => { + if (input === "permission") + mockFs.readFile.mockRejectedValue(Object.assign(new Error("denied"), { code: "EACCES" })) + else if (input === "missing") + mockFs.readFile.mockRejectedValue(Object.assign(new Error("missing"), { code: "ENOENT" })) + else mockFs.readFile.mockResolvedValue(input === "malformed" ? "{" : JSON.stringify({ mcpServers: {} })) + const removing = installer.removeItem(mockMcpItem, { target: "project" }) + if (input === "permission" || input === "malformed") await expect(removing).rejects.toThrow() + else await removing + expect(mockFs.writeFile).not.toHaveBeenCalled() + }) + + // Invariant: McpSettingsWriters.RemovedStays. A deleted document cannot restore old siblings. + it("does not restore an old snapshot when settings disappear before the lock", async () => { + mockFs.readFile.mockResolvedValue(JSON.stringify({ mcpServers: { old: { command: "node" } } })) + const write = vi.mocked(safeWriteJson).getMockImplementation()! + vi.mocked(safeWriteJson).mockImplementationOnce(async (...args) => { + mockFs.readFile.mockRejectedValue(Object.assign(new Error("missing"), { code: "ENOENT" })) + await write(...args) + }) + await installer.installItem(mockMcpItem, { target: "project" }) + const written: unknown = JSON.parse(String(mockFs.writeFile.mock.calls[0][1])) + expect(written).toMatchObject({ mcpServers: { "test-mcp": { command: "test-server" } } }) + expect(written).not.toHaveProperty("mcpServers.old") + expect(mockFs.readFile).toHaveBeenCalledTimes(1) + }) + it("should install MCP when mcp.json file does not exist", async () => { const notFoundError = new Error("File not found") as any notFoundError.code = "ENOENT" @@ -172,6 +255,7 @@ describe("SimpleInstaller", () => { const invalidJson = '{ "mcpServers": { invalid json' mockFs.readFile.mockResolvedValueOnce(invalidJson) + vi.mocked(existsSync).mockReturnValue(true) await expect(installer.installItem(mockMcpItem, { target: "project" })).rejects.toThrow( "Cannot install MCP server: The .roo/mcp.json file contains invalid JSON", diff --git a/src/services/mcp/McpHub.ts b/src/services/mcp/McpHub.ts index 818729c46b..37f85bc8ee 100644 --- a/src/services/mcp/McpHub.ts +++ b/src/services/mcp/McpHub.ts @@ -37,12 +37,19 @@ 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 { McpOAuthFlow, type McpOAuthFlowOutcome } from "./McpOAuthFlow" +import { McpOAuthClientProvider, UnsafeOAuthEndpointError } from "./McpOAuthClientProvider" import { arePathsEqual, getWorkspacePath } from "../../utils/path" import { injectVariables } from "../../utils/config" -import { safeWriteJson } from "../../utils/safeWriteJson" +import { safeWriteJson, SKIP_JSON_WRITE } from "../../utils/safeWriteJson" import { sanitizeMcpName, toolNamesMatch } from "../../utils/mcp-name" import { ToolRouter } from "../tools/ToolRouter" @@ -164,6 +171,13 @@ const McpSettingsSchema = z.object({ mcpServers: z.record(z.string(), ServerConfigSchema), }) +// Writers preserve fields that this extension does not read. +const McpSettingsDocumentSchema = z + .object({ + mcpServers: z.record(z.string(), z.record(z.string(), z.unknown())), + }) + .passthrough() + export class McpHub { private readonly serverListEvents = new EventEmitter() private serverListKey?: string @@ -196,13 +210,15 @@ export class McpHub { isConnecting: boolean = false private refCount: number = 0 // Reference counter for active clients private configChangeDebounceTimers: Map = new Map() - private isProgrammaticUpdate: boolean = false - private flagResetTimer?: NodeJS.Timeout + private configOperations = new Map<"global" | "project", Promise>() 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 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() constructor(provider: ClineProvider, secretStorage?: SecretStorageService) { this.providerRef = new WeakRef(provider) @@ -216,8 +232,8 @@ export class McpHub { this.watchProjectMcpFile().catch(console.error) this.setupWorkspaceFoldersWatcher() this.initializationPromise = Promise.all([ - this.initializeGlobalMcpServers(), - this.initializeProjectMcpServers(), + this.withConfigOperation("global", () => this.initializeMcpServers("global")), + this.withConfigOperation("project", () => this.initializeMcpServers("project")), ]).then(() => {}) } @@ -344,11 +360,6 @@ export class McpHub { * Debounced wrapper for handling config file changes */ private debounceConfigChange(filePath: string, source: "global" | "project"): void { - // Skip processing if this is a programmatic update to prevent unnecessary server restarts - if (this.isProgrammaticUpdate) { - return - } - const key = `${source}-${filePath}` // Clear existing timer if any @@ -366,7 +377,37 @@ export class McpHub { this.configChangeDebounceTimers.set(key, timer) } - private async handleConfigFileChange(filePath: string, source: "global" | "project"): Promise { + /** + * Serializes watcher applies and local writes for each settings source. + * A watcher holds this queue through connection setup. Same-source edits, disables, + * and deletions wait for setup to finish or time out, so an older apply cannot restore them. + */ + private async withConfigOperation(source: "global" | "project", operation: () => Promise): Promise { + const previous = this.configOperations.get(source) ?? Promise.resolve() + const queuedAt = Date.now() + const current = previous + .catch(() => {}) + .then(async () => { + const waited = Date.now() - queuedAt + if (waited >= 1000) + console.info( + `[MCP] ${source} settings operation waited ${waited} ms for connection setup or a prior edit`, + ) + await operation() + }) + this.configOperations.set(source, current) + try { + await current + } finally { + if (this.configOperations.get(source) === current) this.configOperations.delete(source) + } + } + + private handleConfigFileChange(filePath: string, source: "global" | "project"): Promise { + return this.withConfigOperation(source, () => this.applyConfigFileChange(filePath, source)) + } + + private async applyConfigFileChange(filePath: string, source: "global" | "project"): Promise { try { const content = await fs.readFile(filePath, "utf-8") let config: any @@ -386,6 +427,7 @@ export class McpHub { const errorMessages = result.error.issues .map((err) => `${err.path.join(".")}: ${err.message}`) .join("\n") + console.error(t("mcp:errors.invalid_settings_validation", { errorMessages })) vscode.window.showErrorMessage(t("mcp:errors.invalid_settings_validation", { errorMessages })) return } @@ -439,8 +481,10 @@ export class McpHub { // Watch for file deletion const deleteDisposable = this.projectMcpWatcher.onDidDelete(async () => { // Clean up all project MCP servers when the file is deleted - await this.cleanupProjectMcpServers() - await this.notifyWebviewOfServerChanges() + await this.withConfigOperation("project", async () => { + await this.cleanupProjectMcpServers() + await this.notifyWebviewOfServerChanges() + }) vscode.window.showInformationMessage(t("mcp:info.project_config_deleted")) }) @@ -450,37 +494,8 @@ export class McpHub { } private async updateProjectMcpServers(): Promise { - try { - const projectMcpPath = await this.getProjectMcpPath() - if (!projectMcpPath) return - - const content = await fs.readFile(projectMcpPath, "utf-8") - let config: any - - try { - config = JSON.parse(content) - } catch (parseError) { - const errorMessage = t("mcp:errors.invalid_settings_syntax") - console.error(errorMessage, parseError) - vscode.window.showErrorMessage(errorMessage) - return - } - - // Validate configuration structure - const result = McpSettingsSchema.safeParse(config) - if (result.success) { - await this.updateServerConnections(result.data.mcpServers || {}, "project") - } else { - // Format validation errors for better user feedback - const errorMessages = result.error.issues - .map((err) => `${err.path.join(".")}: ${err.message}`) - .join("\n") - console.error("Invalid project MCP settings format:", errorMessages) - vscode.window.showErrorMessage(t("mcp:errors.invalid_settings_validation", { errorMessages })) - } - } catch (error) { - this.showErrorMessage(t("mcp:errors.failed_update_project"), error) - } + const projectMcpPath = await this.getProjectMcpPath() + if (projectMcpPath) await this.handleConfigFileChange(projectMcpPath, "project") } private async cleanupProjectMcpServers(): Promise { @@ -649,10 +664,6 @@ export class McpHub { } } - private async initializeGlobalMcpServers(): Promise { - await this.initializeMcpServers("global") - } - // Get project-level MCP configuration path private async getProjectMcpPath(): Promise { const workspacePath = this.providerRef.deref()?.cwd ?? getWorkspacePath() @@ -667,24 +678,19 @@ export class McpHub { } } - // Initialize project-level MCP servers - private async initializeProjectMcpServers(): Promise { - await this.initializeMcpServers("project") - } - /** - * 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", @@ -715,13 +721,28 @@ export class McpHub { return state.mcpEnabled ?? true } + private async expandServerConfig>(config: C) { + return injectVariables(config, { + env: process.env, + workspaceFolder: vscode.workspace.workspaceFolders?.[0]?.uri.fsPath ?? "", + }) + } + private async connectToServer( 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 = this.deleteConnection(name, source, preservedFlow) + const revision = this.connectionRemovals.get(connectionKey(name, source)) + const isCurrentAttempt = () => + !this.isDisposed && + preservedFlow?.phase !== "ended" && + this.connectionRemovals.get(connectionKey(name, source)) === revision + await removal + if (!isCurrentAttempt()) return // Register the sanitized name for O(1) lookup const sanitizedName = sanitizeMcpName(name) @@ -729,6 +750,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) @@ -760,13 +782,11 @@ export class McpHub { ) let transport: StdioClientTransport | SSEClientTransport | StreamableHTTPClientTransport + let skippedOAuthDiscovery = false let streamableHttpAuthProvider: McpOAuthClientProvider | undefined // Inject variables to the config (environment, magic variables,...) - const configInjected = (await injectVariables(config, { - env: process.env, - workspaceFolder: vscode.workspace.workspaceFolders?.[0]?.uri.fsPath ?? "", - })) as typeof config + const configInjected = await this.expandServerConfig(config) if (configInjected.type === "stdio") { // On Windows, wrap commands with cmd.exe to handle non-exe executables like npx.ps1 @@ -799,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() } @@ -831,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") { @@ -860,6 +878,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, @@ -878,8 +897,10 @@ export class McpHub { if (!skipDiscovery && !oauthClientId) { try { await authProvider.registerClientIfNeeded() - } catch { - // Registration may not be supported — the SDK will attempt its own. + } catch (error) { + console.error("[MCP OAuth] Client registration failed:", error) + if (error instanceof UnsafeOAuthEndpointError) throw error + // The SDK can retry a supported registration endpoint. } } @@ -890,62 +911,41 @@ 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" - - const reauthKey = `${name}:${source}` - 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, + 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 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() } @@ -979,19 +979,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 { @@ -1009,7 +1007,7 @@ export class McpHub { type: "connected", server: { name, - config: JSON.stringify(configInjected), + config: JSON.stringify(config), status: "connecting", disabled: configInjected.disabled, source, @@ -1020,6 +1018,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 @@ -1035,10 +1039,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, config) return } @@ -1047,14 +1050,7 @@ export class McpHub { // waitUntilReady() resolves immediately and the MCP panel can load. connection.server.status = "connecting" - void this._initiateOAuthFlow( - name, - source, - config, - streamableHttpAuthProvider, - transport as StreamableHTTPClientTransport, - connection, - ) + void this._initiateOAuthFlow(name, source, config, streamableHttpAuthProvider, connection) return } @@ -1067,95 +1063,237 @@ 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() + // 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.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.tryNotifyWebview() } catch (error) { await pendingAuthProvider?.close() // Update status with error const connection = this.findConnection(name, source) - if (connection) { - connection.server.status = "disconnected" - this.appendErrorMessage(connection, error instanceof Error ? error.message : `${error}`) + if (isCurrentAttempt()) { + if (connection) { + connection.server.status = "disconnected" + this.appendErrorMessage(connection, error instanceof Error ? error.message : `${error}`) + } else if (error instanceof UnsafeOAuthEndpointError) { + this.addStoppedConnection(name, config, source, error.message) + } } throw error } } - /** - * 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( + /** 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 && + !connection.server.disabled && + this.findConnection(connection.server.name, connection.server.source) === connection + ) + } + + /** Replaces a cancelled reconnect attempt with an error row, unless a later removal owns the name. */ + private stopOAuthReconnect( name: string, source: "global" | "project", config: z.infer, - authProvider: McpOAuthClientProvider, - transport: StreamableHTTPClientTransport, + revision: number | undefined, + ): void { + if (this.connectionRemovals.get(connectionKey(name, source)) !== revision) return + const current = this.findConnection(name, source) + if (current && current.server.status !== "connecting") return + // Detach first, then publish the error row before resource cleanup can yield. + 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, - ): Promise { - const serverUrl = "url" in config ? config.url : undefined - const oauthClientId = config.type === "streamable-http" ? config.oauth?.clientId : undefined - if (!serverUrl || !this.secretStorage) { - return + config: z.infer, + flow?: McpOAuthFlow, + ): Promise { + const isFlowActive = () => flow?.phase !== "ended" + const canContinue = () => isFlowActive() && this.isCurrentOAuthConnection(connection) + if (!canContinue()) return false + 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 = connectionKey(name, source) + const removal = this.deleteConnection(name, source, flow) + const revision = this.connectionRemovals.get(key) + await removal + if ( + this.isDisposed || + !isFlowActive() || + connection.server.disabled || + this.connectionRemovals.get(key) !== revision + ) + return false + const reconnect = this.connectToServer(name, validatedConfig, source, flow) + const reconnectRevision = this.connectionRemovals.get(key) + // 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" && + isFlowActive() && + replacement.server.status === "connected" && + this.isCurrentOAuthConnection(replacement) + ) + } - // 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, + 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 + } - // 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() + /** Starts or joins the OAuth attempt owned by this connection. */ + private _initiateOAuthFlow( + name: string, + source: "global" | "project", + config: z.infer, + authProvider: McpOAuthClientProvider, + 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, connection, flow) + .catch(async (error: unknown) => { + console.error(`[McpHub] OAuth flow failed for "${name}":`, error) + await this._failOAuthFlow(connection, flow, error) + }) + .finally(() => flow.finish("failed")) + return flow.promise + } + + private async performOAuthFlow( + name: string, + source: "global" | "project", + config: z.infer, + authProvider: McpOAuthClientProvider, + connection: ConnectedMcpConnection, + flow: McpOAuthFlow, + ): Promise { + const expanded = await this.expandServerConfig(config) + const serverUrl = "url" in expanded ? expanded.url : undefined + const oauthClientId = expanded.type === "streamable-http" ? expanded.oauth?.clientId : undefined + // 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( + serverUrl, + () => { + tokenChangedDuringRead = true + }, + oauthClientId, + ), + ) + let tokenToUse: Awaited> + try { + tokenToUse = await this.secretStorage.getOAuthData(serverUrl, oauthClientId) + if (flow.phase !== "ended" && 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) { - await authProvider.close() - await this.deleteConnection(name, source) - await this.connectToServer(name, config, source) - await this.notifyWebviewOfServerChanges() + if (tokenToUse && this.isFreshToken(tokenToUse)) { + const tokenKey = JSON.stringify([serverUrl, oauthClientId, tokenToUse.tokens?.access_token]) + const retryKey = connectionKey(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._failOAuthFlow(connection, flow, t("mcp:oauth.flow.retriesExhausted", { name })) + return + } + 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)) + 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, @@ -1169,253 +1307,150 @@ export class McpHub { config, serverUrl, authProvider, - transport, connection, progress, cancellationToken, oauthClientId, + flow, ), ) } + 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), + ) + } + private _runOAuthFlow( name: string, source: "global" | "project", config: z.infer, serverUrl: string, authProvider: McpOAuthClientProvider, - transport: StreamableHTTPClientTransport, connection: ConnectedMcpConnection, progress: vscode.Progress<{ message?: string; increment?: number }>, cancellationToken: vscode.CancellationToken, - oauthClientId?: string, + oauthClientId: string | undefined, + flow: McpOAuthFlow, ): 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) - } - - return new Promise((resolve) => { - let disposed = false - - const cleanup = (disposable?: vscode.Disposable) => { - if (disposed) return - disposed = true - clearTimeout(timeoutHandle) - unsubscribe() - disposable?.dispose() - 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(cancellationDisposable) - 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(cancellationDisposable) - 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) { - console.error(`[McpHub] OAuth token watcher failed for "${name}":`, err) - } - } - - const unsubscribe = this.secretStorage!.onDidChange( + if (!this.isCurrentOAuthConnection(connection)) return Promise.resolve() + 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"), fail) + } + flow.addCleanup( + this.secretStorage!.onDidChange( serverUrl, () => { - void onTokensChanged() + if (flow.phase !== "waiting") return + void this.secretStorage!.getOAuthData(serverUrl, oauthClientId).then( + (data) => { + if (data && this.isFreshToken(data)) { + run(() => this.reconnectOAuthConnection(connection, config, flow)) + } + }, + (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, - ) - - // --- Timeout --- - const timeoutHandle = setTimeout(() => { - if (disposed) return - cleanup(cancellationDisposable) - 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. - this._oauthWatchers.set(watcherKey, { unsubscribe, abortHandle: timeoutHandle }) - - // --- Cancellation (progress bar's Cancel button) --- - const cancellationDisposable = cancellationToken.onCancellationRequested(() => { - if (disposed) return - // Don't pass cancellationDisposable 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. - 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(cancellationDisposable) - try { - await this._completeOAuthFlow( - authProvider, - transport, - connection, - name, - 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). + ), + ) + 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, connection, flow)) + } else { const authenticateLabel = t("mcp:oauth.flow.authenticateButton") - void (async () => { - const choice = await vscode.window.showInformationMessage( + void Promise.resolve( + vscode.window.showInformationMessage( t("mcp:oauth.flow.clickAuthenticate", { name }), authenticateLabel, - ) - - if (disposed) return - + ), + ).then((choice) => { + if (flow.phase !== "waiting") 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(cancellationDisposable) - await authProvider.close() - await this.deleteConnection(name, source) - const validatedFastPathConfig = this.validateServerConfig(config, name) - await this.connectToServer(name, validatedFastPathConfig, source) - await 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(cancellationDisposable) - try { - await this._completeOAuthFlow(authProvider, transport, connection, name, source, cancellationToken) - } catch { - // _completeOAuthFlow handles its own error state - } - resolve() - })() - }) + 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, - ): 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")) - let cancelListener: vscode.Disposable | undefined - const cancellationPromise = new Promise((_, reject) => { - if (cancellationToken.isCancellationRequested) { - reject(cancelledError) - return - } - cancelListener = cancellationToken.onCancellationRequested(() => reject(cancelledError)) - }) - + flow: McpOAuthFlow, + ): Promise { + const canContinue = () => flow.phase !== "ended" && this.isCurrentOAuthConnection(connection) + if (!canContinue()) return false 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). - 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 })) - } 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}`) + const authorization = async () => { + await authProvider.openBrowser() + if (!canContinue()) return undefined + return authProvider.waitForAuthCode() } - await this.notifyWebviewOfServerChanges() - } finally { - cancelListener?.dispose() + // 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, canContinue) + if (!canContinue()) return false + const connected = await this.reconnectOAuthConnection( + connection, + JSON.parse(connection.server.config), + flow, + ) + if (connected && flow.phase !== "ended") { + const { name } = connection.server + void vscode.window.showInformationMessage(t("mcp:oauth.flow.connected", { name })) + } + return connected + } catch (error) { + await this._failOAuthFlow(connection, flow, error) + return false } } @@ -1595,49 +1630,37 @@ export class McpHub { } } - async deleteConnection(name: string, source?: "global" | "project"): Promise { - // Cancel any active OAuth token watchers for this connection - const watcherKey = `${name}:${source}` - const watcher = this._oauthWatchers.get(watcherKey) - if (watcher) { - watcher.unsubscribe() - clearTimeout(watcher.abortHandle) - this._oauthWatchers.delete(watcherKey) + 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") } - - // Clean up file watchers for this server - 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) - + this.removeFileWatchersForServer(name, source) + const connections = this.connections.filter( + (connection) => connection.server.name === name && (!source || connection.server.source === source), + ) + for (const serverSource of source ? [source] : (["global", "project"] as const)) { + const key = connectionKey(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( @@ -1648,7 +1671,6 @@ export class McpHub { if (manageConnectingState) { this.isConnecting = true } - this.removeAllFileWatchers() // Filter connections by source const currentConnections = this.connections.filter( (conn) => conn.server.source === source || (!conn.server.source && source === "global"), @@ -1656,8 +1678,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) } @@ -1677,28 +1702,17 @@ export class McpHub { continue } - if (!currentConnection) { - // New server + if (!currentConnection || !deepEqual(JSON.parse(currentConnection.server.config), validatedConfig)) { try { - // Only setup file watcher for enabled servers - if (!validatedConfig.disabled) { - this.setupFileWatcher(name, validatedConfig, source) - } + if (currentConnection) await this.deleteConnection(name, source) await this.connectToServer(name, validatedConfig, source) } catch (error) { - this.showErrorMessage(`Failed to connect to new MCP server ${name}`, error) - } - } else if (!deepEqual(JSON.parse(currentConnection.server.config), config)) { - // Existing server with changed config - try { - // Only setup file watcher for enabled servers - if (!validatedConfig.disabled) { - this.setupFileWatcher(name, validatedConfig, source) - } - await this.deleteConnection(name, source) - await this.connectToServer(name, validatedConfig, source) - } catch (error) { - this.showErrorMessage(`Failed to reconnect MCP server ${name}`, error) + this.showErrorMessage( + currentConnection + ? `Failed to reconnect MCP server ${name}` + : `Failed to connect to new MCP server ${name}`, + error, + ) } } // If server exists with same config, do nothing @@ -1714,12 +1728,13 @@ export class McpHub { config: z.infer, source: "global" | "project" = "global", ) { + const key = connectionKey(name, source) // Initialize an empty array for this server if it doesn't exist - if (!this.fileWatchers.has(name)) { - this.fileWatchers.set(name, []) + if (!this.fileWatchers.has(key)) { + this.fileWatchers.set(key, []) } - const watchers = this.fileWatchers.get(name) || [] + const watchers = this.fileWatchers.get(key) || [] // Only stdio type has args if (config.type === "stdio") { @@ -1767,7 +1782,7 @@ export class McpHub { // Update the fileWatchers map with all watchers for this server if (watchers.length > 0) { - this.fileWatchers.set(name, watchers) + this.fileWatchers.set(key, watchers) } } } @@ -1777,11 +1792,14 @@ export class McpHub { this.fileWatchers.clear() } - private removeFileWatchersForServer(serverName: string) { - const watchers = this.fileWatchers.get(serverName) - if (watchers) { - watchers.forEach((watcher) => watcher.close()) - this.fileWatchers.delete(serverName) + private removeFileWatchersForServer(serverName: string, source?: "global" | "project") { + for (const serverSource of source ? [source] : (["global", "project"] as const)) { + const key = connectionKey(serverName, serverSource) + const watchers = this.fileWatchers.get(key) + if (watchers) { + watchers.forEach((watcher) => watcher.close()) + this.fileWatchers.delete(key) + } } } @@ -1804,8 +1822,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 = connectionKey(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 { @@ -1814,7 +1843,13 @@ export class McpHub { // Clear OAuth tokens for streamable-http servers on restart if (validatedConfig.type === "streamable-http" && this.secretStorage) { - await this.secretStorage.deleteOAuthData(validatedConfig.url, validatedConfig.oauth?.clientId) + const expandedConfig = await this.expandServerConfig(validatedConfig) + await this.secretStorage.deleteOAuthData(expandedConfig.url, expandedConfig.oauth?.clientId) + } + + if (this.connectionRemovals.get(key) !== revision) { + this.isConnecting = false + return } // Try to connect again using validated config @@ -1833,43 +1868,20 @@ export class McpHub { } public async refreshAllConnections(): Promise { - if (this.isConnecting) { - return - } - - // Check if MCP is globally enabled - const mcpEnabled = await this.isMcpEnabled() - if (!mcpEnabled) { - // Clear all existing connections - const existingConnections = [...this.connections] - for (const conn of existingConnections) { - await this.deleteConnection(conn.server.name, conn.server.source) - } - - // Still initialize servers to track them, but they won't connect - await this.initializeMcpServers("global") - await this.initializeMcpServers("project") - - await this.notifyWebviewOfServerChanges() - return - } - + if (this.isConnecting) return this.isConnecting = true - try { - // Clear all existing connections first - const existingConnections = [...this.connections] - for (const conn of existingConnections) { - await this.deleteConnection(conn.server.name, conn.server.source) + for (const source of ["global", "project"] as const) { + await this.withConfigOperation(source, async () => { + const connections = this.connections.filter( + (connection) => (connection.server.source ?? "global") === source, + ) + for (const connection of connections) await this.deleteConnection(connection.server.name, source) + // Initialization also keeps placeholder rows when MCP is disabled. + await this.initializeMcpServers(source) + }) } - - // Re-initialize all servers from scratch - // This ensures proper initialization including fetching tools, resources, etc. - await this.initializeMcpServers("global") - await this.initializeMcpServers("project") - await delay(100) - await this.notifyWebviewOfServerChanges() } catch (error) { this.showErrorMessage("Failed to refresh MCP servers", error) @@ -1957,55 +1969,80 @@ 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", ): Promise { try { // Find the connection to determine if it's a global or project server - const connection = this.findConnection(serverName, source) + let connection = this.findConnection(serverName, source) if (!connection) { throw new Error(`Server ${serverName}${source ? ` with source ${source}` : ""} not found`) } 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 + // 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 + } + connection = this.findConnection(serverName, serverSource) + if (!connection) return - // Update the connection object - if (connection) { - try { - connection.server.disabled = disabled - - // If disabling a connected server, disconnect it - if (disabled && connection.server.status === "connected") { - // Clean up file watchers when disabling - this.removeFileWatchersForServer(serverName) - await this.deleteConnection(serverName, serverSource) - // Re-add as a disabled connection - // Re-read config from file to get updated disabled state - const updatedConfig = await this.readServerConfigFromFile(serverName, serverSource) - await this.connectToServer(serverName, updatedConfig, serverSource) - } else if (!disabled && connection.server.status === "disconnected") { - // If enabling a disabled server, connect it - // Re-read config from file to get updated disabled state - const updatedConfig = await this.readServerConfigFromFile(serverName, serverSource) - await this.deleteConnection(serverName, serverSource) - // When re-enabling, file watchers will be set up in connectToServer - await this.connectToServer(serverName, updatedConfig, serverSource) - } else if (connection.server.status === "connected") { - // Only refresh capabilities if connected - connection.server.tools = await this.fetchToolsList(serverName, serverSource) - connection.server.resources = await this.fetchResourcesList(serverName, serverSource) - connection.server.resourceTemplates = await this.fetchResourceTemplatesList( - serverName, - serverSource, - ) - } - } catch (error) { - console.error(`Failed to refresh capabilities for ${serverName}:`, error) + try { + connection.server.disabled = disabled + + // 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, serverSource) + await this.deleteConnection(serverName, serverSource) + // Re-add as a disabled connection + // Re-read config from file to get updated disabled state + const updatedConfig = await this.readServerConfigFromFile(serverName, serverSource) + await this.connectToServer(serverName, updatedConfig, serverSource) + } else if (!disabled && connection.server.status === "disconnected") { + // If enabling a disabled server, connect it + // Re-read config from file to get updated disabled state + const updatedConfig = await this.readServerConfigFromFile(serverName, serverSource) + await this.deleteConnection(serverName, serverSource) + // When re-enabling, file watchers will be set up in connectToServer + await this.connectToServer(serverName, updatedConfig, serverSource) + } else if (connection.server.status === "connected") { + // Only refresh capabilities if connected + connection.server.tools = await this.fetchToolsList(serverName, serverSource) + connection.server.resources = await this.fetchResourcesList(serverName, serverSource) + connection.server.resourceTemplates = await this.fetchResourceTemplatesList( + serverName, + serverSource, + ) } + } catch (error) { + console.error(`Failed to refresh capabilities for ${serverName}:`, error) } await this.notifyWebviewOfServerChanges() @@ -2051,7 +2088,7 @@ export class McpHub { // Validate the config structure if (!config || typeof config !== "object") { - throw new Error("Invalid config structure") + throw new Error("Invalid config structure: expected an object with an mcpServers object") } if (!config.mcpServers || typeof config.mcpServers !== "object") { @@ -2072,80 +2109,66 @@ export class McpHub { * @param configUpdate The configuration updates to apply * @param source Whether to update the global or project config */ - private async updateServerConfig( + private updateServerConfig( serverName: string, - configUpdate: Record, + configUpdate: Record, source: "global" | "project" = "global", ): Promise { - // Determine which config file to update - let configPath: string - if (source === "project") { - const projectMcpPath = await this.getProjectMcpPath() - if (!projectMcpPath) { - throw new Error("Project MCP configuration file not found") - } - configPath = projectMcpPath - } else { - configPath = await this.getMcpSettingsFilePath() - } - - // Ensure the settings file exists and is accessible - try { - await fs.access(configPath) - } catch (error) { - console.error("Settings file not accessible:", error) - 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], + return this.mutateServerConfig(serverName, source, (current) => ({ ...configUpdate, - } - - // Ensure required fields exist - if (!serverConfig.alwaysAllow) { - serverConfig.alwaysAllow = [] - } - - config.mcpServers[serverName] = serverConfig + alwaysAllow: configUpdate.alwaysAllow ?? current.alwaysAllow ?? [], + })) + } - // Write the entire config back - const updatedConfig = { - mcpServers: config.mcpServers, - } + /** Reads and changes one server under the file lock, then updates the local readers. */ + private async mutateServerConfig( + serverName: string, + source: "global" | "project", + update: (current: Readonly>) => Record, + ): Promise { + return this.withConfigOperation(source, () => this.applyServerConfigMutation(serverName, source, update)) + } - // Set flag to prevent file watcher from triggering server restart - if (this.flagResetTimer) { - clearTimeout(this.flagResetTimer) - } - this.isProgrammaticUpdate = true + private async applyServerConfigMutation( + serverName: string, + source: "global" | "project", + update: (current: Readonly>) => Record, + ): Promise { + const configPath = source === "project" ? await this.getProjectMcpPath() : await this.getMcpSettingsFilePath() + if (!configPath) throw new Error("Project MCP configuration file not found") + const normalizedPath = process.platform === "win32" ? configPath.replace(/\\/g, "/") : configPath try { - await safeWriteJson(configPath, updatedConfig, { prettyPrint: true }) - } finally { - // Reset flag after watcher debounce period (non-blocking) - this.flagResetTimer = setTimeout(() => { - this.isProgrammaticUpdate = false - this.flagResetTimer = undefined - }, 600) + await fs.access(normalizedPath) + } catch { + throw new Error("Settings file not accessible") } + + let appliedUpdate: Record = {} + await safeWriteJson( + normalizedPath, + {}, + { + prettyPrint: true, + allowedRoot: source === "project" ? (this.providerRef.deref()?.cwd ?? getWorkspacePath()) : undefined, + merge: (existing) => { + const parsed = McpSettingsDocumentSchema.safeParse(existing) + if (!parsed.success) + throw new Error("Invalid config structure: expected an object with an mcpServers object") + const config = parsed.data + const current = config.mcpServers[serverName] + if (!current) throw new Error(`Server ${serverName} not found in config`) + appliedUpdate = update(current) + config.mcpServers[serverName] = { ...current, ...appliedUpdate } + return config + }, + }, + ) + const connection = this.findConnection(serverName, source) + if (connection) + connection.server.config = JSON.stringify({ + ...JSON.parse(connection.server.config || "{}"), + ...appliedUpdate, + }) } public async updateServerTimeout( @@ -2170,7 +2193,12 @@ export class McpHub { } } - public async deleteServer(serverName: string, source?: "global" | "project"): Promise { + public deleteServer(serverName: string, source?: "global" | "project"): Promise { + const serverSource = this.findConnection(serverName, source)?.server.source ?? source ?? "global" + return this.withConfigOperation(serverSource, () => this.applyServerDeletion(serverName, source)) + } + + private async applyServerDeletion(serverName: string, source?: "global" | "project"): Promise { try { // Find the connection to determine if it's a global or project server const connection = this.findConnection(serverName, source) @@ -2202,32 +2230,30 @@ export class McpHub { throw new Error("Settings file not accessible") } - 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 = {} - } - - // Remove the server from the settings - if (config.mcpServers[serverName]) { - delete config.mcpServers[serverName] - - // Write the entire config back - const updatedConfig = { - mcpServers: config.mcpServers, - } - - await safeWriteJson(configPath, updatedConfig, { prettyPrint: true }) - - // Update server connections with the correct source - await this.updateServerConnections(config.mcpServers, serverSource) - + let deleted = false + let servers: Record> = {} + await safeWriteJson( + configPath, + {}, + { + prettyPrint: true, + allowedRoot: + serverSource === "project" ? (this.providerRef.deref()?.cwd ?? getWorkspacePath()) : undefined, + merge: (existing) => { + const parsed = McpSettingsDocumentSchema.safeParse(existing) + if (!parsed.success) + throw new Error("Invalid config structure: expected an object with an mcpServers object") + const config = parsed.data + servers = config.mcpServers + deleted = Object.hasOwn(servers, serverName) + if (!deleted) return SKIP_JSON_WRITE + delete servers[serverName] + return { ...config, mcpServers: servers } + }, + }, + ) + if (deleted) { + await this.updateServerConnections(servers, serverSource) vscode.window.showInformationMessage(t("mcp:info.server_deleted", { serverName })) } else { vscode.window.showWarningMessage(t("mcp:info.server_not_found", { serverName })) @@ -2262,6 +2288,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") { @@ -2283,8 +2310,10 @@ export class McpHub { timeout = 60 * 1000 } - try { - return await connection.client.request( + const retryKey = connectionKey(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: { @@ -2297,51 +2326,44 @@ 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) connection.server.status = "connecting" - const reauthKey = `${serverName}:${source || connection.server.source || "global"}` - 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, + ) // 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") { - throw new Error(`Failed to reconnect to server ${serverName} after OAuth`) + const newConnection = this.findConnection(serverName, source ?? connection.server.source) + if ( + outcome !== "connected" || + !newConnection || + newConnection.type !== "connected" || + newConnection.server.status !== "connected" || + !this.isCurrentOAuthConnection(newConnection) + ) { + 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( @@ -2379,72 +2401,15 @@ export class McpHub { throw new Error(`Server ${serverName} with source ${source} not found`) } - // Determine the correct config path based on the source - let configPath: string - if (source === "project") { - // Get project MCP config path - const projectMcpPath = await this.getProjectMcpPath() - if (!projectMcpPath) { - throw new Error("Project MCP configuration file not found") + await this.mutateServerConfig(serverName, source, (current) => { + const list = z.array(z.string()).optional().parse(current[listName]) ?? [] + return { + [listName]: addTool ? [...new Set([...list, toolName])] : list.filter((name) => name !== toolName), } - configPath = projectMcpPath - } else { - // Get global MCP settings path - configPath = await this.getMcpSettingsFilePath() - } - - // Normalize path for cross-platform compatibility - // Use a consistent path format for both reading and writing - const normalizedPath = process.platform === "win32" ? configPath.replace(/\\/g, "/") : configPath - - // Read the appropriate config file - const content = await fs.readFile(normalizedPath, "utf-8") - const config = JSON.parse(content) - - if (!config.mcpServers) { - config.mcpServers = {} - } - - if (!config.mcpServers[serverName]) { - config.mcpServers[serverName] = { - type: "stdio", - command: "node", - args: [], // Default to an empty array; can be set later if needed - } - } - - if (!config.mcpServers[serverName][listName]) { - config.mcpServers[serverName][listName] = [] - } - - const targetList = config.mcpServers[serverName][listName] - const toolIndex = targetList.indexOf(toolName) - - if (addTool && toolIndex === -1) { - targetList.push(toolName) - } else if (!addTool && toolIndex !== -1) { - targetList.splice(toolIndex, 1) - } - - // Set flag to prevent file watcher from triggering server restart - if (this.flagResetTimer) { - clearTimeout(this.flagResetTimer) - } - this.isProgrammaticUpdate = true - try { - await safeWriteJson(normalizedPath, config, { prettyPrint: true }) - } finally { - // Reset flag after watcher debounce period (non-blocking) - this.flagResetTimer = setTimeout(() => { - this.isProgrammaticUpdate = false - this.flagResetTimer = undefined - }, 600) - } - - if (connection) { - connection.server.tools = await this.fetchToolsList(serverName, source) - await this.notifyWebviewOfServerChanges() - } + }) + const current = this.findConnection(serverName, source) + if (current) current.server.tools = await this.fetchToolsList(serverName, source) + await this.notifyWebviewOfServerChanges() } async toggleToolAlwaysAllow( @@ -2549,21 +2514,8 @@ export class McpHub { this.configChangeDebounceTimers.clear() - // Clear flag reset timer and reset programmatic update flag - if (this.flagResetTimer) { - clearTimeout(this.flagResetTimer) - this.flagResetTimer = undefined - } - - 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) - } - this._oauthWatchers.clear() - this.reauthPromises.clear() + for (const flow of this.oauthFlows.values()) flow.finish("removed") + this.oauthTokenRetries.clear() this.removeAllFileWatchers() @@ -2592,3 +2544,8 @@ export class McpHub { this.disposables.forEach((d) => d.dispose()) } } + +/** Keeps connection ownership and retry counters in the same source namespace. */ +function connectionKey(name: string, source: "global" | "project"): string { + return `${name}:${source}` +} diff --git a/src/services/mcp/McpOAuthClientProvider.ts b/src/services/mcp/McpOAuthClientProvider.ts index 794f53dcda..8b8d8b14cc 100644 --- a/src/services/mcp/McpOAuthClientProvider.ts +++ b/src/services/mcp/McpOAuthClientProvider.ts @@ -17,7 +17,7 @@ import { selectMcpOAuthGrantTypes, type McpOAuthGrantType, } from "./oauthMetadata" -import { SecretStorageService } from "./SecretStorageService" +import { SecretStorageService, getMcpOAuthStorageKey } from "./SecretStorageService" import { startCallbackServer, stopCallbackServer } from "./utils/callbackServer" import { fetchOAuthAuthServerMetadata } from "./utils/oauth" @@ -85,8 +85,10 @@ export class McpOAuthClientProvider implements OAuthClientProvider { // Client info is kept in-memory only (not persisted) to avoid stale registrations // when the redirect URI port changes between sessions. private _clientInfo?: OAuthClientInformationFull - private _closed = false - private _refreshPromise: Promise | null = null + private static readonly _sharedRefreshes = new WeakMap< + SecretStorageService, + Map> + >() /** Stored by redirectToAuthorization(); opened on-demand via openBrowser(). */ private _pendingAuthorizationUrl: URL | null = null /** Resource used by the authorization request and subsequent token requests. */ @@ -160,9 +162,13 @@ export class McpOAuthClientProvider implements OAuthClientProvider { } // Extract auth-method preferences. - // Only pick methods we actually implement: "none" or "client_secret_post". + // Supported methods: "none", "client_secret_post", and "client_secret_basic". const authMethods: string[] = authServerMeta?.token_endpoint_auth_methods_supported ?? [] - const tokenEndpointAuthMethod = authMethods.includes("none") ? "none" : "client_secret_post" + const tokenEndpointAuthMethod = authMethods.includes("none") + ? "none" + : authMethods.includes("client_secret_basic") && !authMethods.includes("client_secret_post") + ? "client_secret_basic" + : "client_secret_post" const grantTypes = selectMcpOAuthGrantTypes(authServerMeta?.grant_types_supported) const configuredScope = options?.scope const scopeConfigured = configuredScope !== undefined @@ -241,7 +247,7 @@ export class McpOAuthClientProvider implements OAuthClientProvider { // Guard against concurrent callers (e.g. redirectToAuthorization + registerClientIfNeeded // called in parallel) both passing the "server not yet started" check and each launching // their own startCallbackServer(), which would bind two ports and lose one handle. - if (this._server && !this._closed) return Promise.resolve() + if (this._server) return Promise.resolve() if (!this._ensureServerPromise) { this._ensureServerPromise = this._doStartCallbackServer().finally(() => { this._ensureServerPromise = null @@ -251,7 +257,6 @@ export class McpOAuthClientProvider implements OAuthClientProvider { } private async _doStartCallbackServer(): Promise { - this._closed = false // A new listener belongs to a new authorization attempt, so an earlier failure no longer applies. this._unreportedAuthCodeFailure = null if (this._listenerCleanup) { @@ -343,6 +348,13 @@ 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. + // 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). this._clientInfo = { @@ -354,12 +366,15 @@ export class McpOAuthClientProvider implements OAuthClientProvider { if (!this._authServerMeta?.registration_endpoint) return // DCR not supported + assertSafeTokenEndpoint(this._authServerMeta.registration_endpoint as string) + // For Dynamic Client Registration, we MUST have a stable redirect URI. // Ensure the callback server is started so we have a real port. await this._ensureCallbackServer() const response = await fetch(this._authServerMeta.registration_endpoint as string, { method: "POST", + redirect: "manual", headers: { "Content-Type": "application/json", Accept: "application/json", @@ -374,7 +389,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 @@ -385,10 +411,16 @@ 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) { - // 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) { - await this._secretStorage.deleteOAuthData(this._serverUrl, this._configuredClientId) + // Without discovery the issuer is unknown. Keep the data for a later attempt. + if (!this._authServerMeta) { + console.warn("[MCP OAuth] Token refresh deferred: authorization server discovery is not available") + return undefined + } + + // Keep credentials when this provider has different or older discovery data. + // Only the issuer that issued the refresh token may receive it. + if (data.issuer !== this._authServerMeta.issuer) { + console.warn("[MCP OAuth] Token refresh deferred: stored and discovered issuers differ") return undefined } @@ -397,41 +429,48 @@ export class McpOAuthClientProvider implements OAuthClientProvider { if (!this._effectiveResourceIndicator && !this._resourceDisabled) { this._effectiveResourceIndicator = data.resource_indicator ?? null } - if (this._refreshPromise) { - return this._refreshPromise + // Providers in this window share one refresh for the same stored credential. + let refreshes = McpOAuthClientProvider._sharedRefreshes.get(this._secretStorage) + if (!refreshes) { + refreshes = new Map() + McpOAuthClientProvider._sharedRefreshes.set(this._secretStorage, refreshes) } - - // Use the client_id stored alongside the tokens — it is the one the - // auth server bound the refresh token to. `this._clientInfo.client_id` - // may differ if a fresh DCR was performed (e.g. after stale token - // cleanup removed the cached data). - const clientIdForRefresh = data.client_info?.client_id ?? this._clientInfo?.client_id - - this._refreshPromise = this.refreshAccessToken(data.tokens.refresh_token, clientIdForRefresh).finally( - () => { - this._refreshPromise = null - }, - ) - - try { - 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) - // Fall through to return undefined, which triggers full re-auth + const credential = JSON.stringify([ + getMcpOAuthStorageKey(this._serverUrl, this._configuredClientId), + data.issuer, + data.tokens.refresh_token, + ]) + let refresh = refreshes.get(credential) + if (!refresh) { + refresh = this.refreshAccessToken(data.tokens.refresh_token, data.client_info) + .catch(async (error: unknown) => { + console.error(`Failed to refresh MCP OAuth token for ${this._serverUrl}:`, error) + // Delete only the stored token that the server rejected. + if (error instanceof RefreshTokenRejectedError) { + 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) + } + } + return undefined + }) + .finally(() => { + refreshes.delete(credential) + }) + refreshes.set(credential, refresh) } + return refresh } return undefined } - async saveTokens(tokens: OAuthTokens, clientIdOverride?: string): Promise { + async saveTokens(tokens: OAuthTokens, clientInfoOverride?: OAuthClientInformationFull): Promise { const expires_at = tokens.expires_in ? Date.now() + tokens.expires_in * 1000 : Date.now() + 3600 * 1000 // default 1 hour when server omits expires_in - const clientInfo = - clientIdOverride && this._clientInfo - ? { ...this._clientInfo, client_id: clientIdOverride } - : this._clientInfo + const clientInfo = clientInfoOverride ?? this._clientInfo await this._secretStorage.saveOAuthData( this._serverUrl, { @@ -453,6 +492,10 @@ export class McpOAuthClientProvider implements OAuthClientProvider { // openBrowser(), which McpHub calls only after the user confirms the toast. await this._ensureCallbackServer() + // 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). // 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. @@ -526,6 +569,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 { @@ -583,7 +630,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") } @@ -591,6 +638,7 @@ export class McpOAuthClientProvider implements OAuthClientProvider { throw new Error("No client information — registerClientIfNeeded() must be called first") } + assertSafeTokenEndpoint(this._authServerMeta.token_endpoint as string) const codeVerifier = await this.codeVerifier() // Build the token request body per RFC 6749 §4.1.3 + RFC 7636 §4.5. @@ -608,14 +656,13 @@ export class McpOAuthClientProvider implements OAuthClientProvider { params.resource = this._effectiveResourceIndicator } - // Include client_secret in the body when the auth method is client_secret_post. - if (this._tokenEndpointAuthMethod === "client_secret_post" && this._clientInfo.client_secret) { - params.client_secret = this._clientInfo.client_secret - } + const authHeaders = tokenClientAuthentication(params, this._clientInfo, this._tokenEndpointAuthMethod) const response = await fetch(this._authServerMeta.token_endpoint as string, { method: "POST", + redirect: "manual", headers: { + ...authHeaders, "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json", }, @@ -627,6 +674,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) } @@ -634,18 +683,22 @@ export class McpOAuthClientProvider implements OAuthClientProvider { * Refreshes the access token using a refresh token. * * @param refreshToken The refresh token to use. - * @param clientIdOverride Optional client_id to use instead of `this._clientInfo.client_id`. - * This is used when the stored tokens were issued to a different client_id than the - * current in-memory registration (e.g. after a port change caused a new DCR). + * @param clientInfoOverride The registration stored with the refresh token. * @returns The new tokens. */ - async refreshAccessToken(refreshToken: string, clientIdOverride?: string): Promise { + async refreshAccessToken( + refreshToken: string, + clientInfoOverride?: OAuthClientInformationFull, + ): Promise { if (!this._authServerMeta?.token_endpoint) { throw new Error("No token_endpoint in auth server metadata — cannot refresh token") } - const clientId = clientIdOverride ?? this._clientInfo?.client_id - if (!clientId) { + assertSafeTokenEndpoint(this._authServerMeta.token_endpoint as string) + + const clientInfo = clientInfoOverride ?? this._clientInfo + const clientId = clientInfo?.client_id + if (!clientInfo || !clientId) { throw new Error("No client information — registerClientIfNeeded() must be called first") } @@ -660,13 +713,13 @@ export class McpOAuthClientProvider implements OAuthClientProvider { params.resource = this._effectiveResourceIndicator } - if (this._tokenEndpointAuthMethod === "client_secret_post" && this._clientInfo?.client_secret) { - params.client_secret = this._clientInfo.client_secret - } + const authHeaders = tokenClientAuthentication(params, clientInfo, this._tokenEndpointAuthMethod) const response = await fetch(this._authServerMeta.token_endpoint as string, { method: "POST", + redirect: "manual", headers: { + ...authHeaders, "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json", }, @@ -675,7 +728,15 @@ export class McpOAuthClientProvider implements OAuthClientProvider { if (!response.ok) { const errorBody = await response.text().catch(() => "") - throw new Error(`Token refresh failed: HTTP ${response.status} ${errorBody}`) + let errorCode: unknown + try { + const body: unknown = JSON.parse(errorBody) + if (body && typeof body === "object" && "error" in body) errorCode = body.error + } catch { + // A non-JSON response is not an OAuth rejection. + } + if (response.status === 400 && errorCode === "invalid_grant") throw new RefreshTokenRejectedError() + throw new Error(`Token refresh failed: HTTP ${response.status}`) } const tokens = (await response.json()) as OAuthTokens @@ -683,7 +744,11 @@ export class McpOAuthClientProvider implements OAuthClientProvider { ...tokens, refresh_token: tokens.refresh_token ?? refreshToken, } - await this.saveTokens(mergedTokens, clientId) + const current = await this._secretStorage.getOAuthData(this._serverUrl, this._configuredClientId) + if (current?.tokens.refresh_token !== refreshToken) { + throw new Error("OAuth token refresh is no longer current") + } + await this.saveTokens(mergedTokens, clientInfo) return mergedTokens } @@ -697,8 +762,7 @@ export class McpOAuthClientProvider implements OAuthClientProvider { // A closed flow must not report its failure to a later flow. this._unreportedAuthCodeFailure = null const server = this._server - if (!this._closed && server) { - this._closed = true + if (server) { const cancel = this._cancelCallbackServer ?? (() => {}) // Detach before cancelling so the rejection handler does not record the cancellation. this._server = null @@ -753,3 +817,38 @@ function getCallbackAddress(redirectUri?: string): { } return { port, host: url.hostname, path: url.pathname } } + +/** A token endpoint rejected the refresh grant with a structured HTTP 400 response. */ +class RefreshTokenRejectedError extends Error { + constructor() { + super("OAuth refresh grant rejected") + } +} + +export class UnsafeOAuthEndpointError extends Error {} + +/** Checks transport before a token request sends credentials. */ +function assertSafeTokenEndpoint(value: string): void { + const endpoint = new URL(value) + const loopbackHttp = + endpoint.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(endpoint.hostname) + if ((endpoint.protocol !== "https:" && !loopbackHttp) || endpoint.username || endpoint.password) { + throw new UnsafeOAuthEndpointError("Unsafe OAuth endpoint") + } +} + +/** Uses the same registration and method for code exchange and refresh. */ +function tokenClientAuthentication( + params: Record, + client: OAuthClientInformationFull, + fallback: string, +): Record { + const method = client.token_endpoint_auth_method ?? fallback + if (!client.client_secret) return {} + if (method === "client_secret_post") params.client_secret = client.client_secret + if (method !== "client_secret_basic") return {} + const encode = (value: string) => new URLSearchParams({ value }).toString().slice("value=".length) + return { + Authorization: `Basic ${Buffer.from(`${encode(client.client_id)}:${encode(client.client_secret)}`).toString("base64")}`, + } +} diff --git a/src/services/mcp/McpOAuthFlow.ts b/src/services/mcp/McpOAuthFlow.ts new file mode 100644 index 0000000000..d464d1faba --- /dev/null +++ b/src/services/mcp/McpOAuthFlow.ts @@ -0,0 +1,75 @@ +export type McpOAuthFlowOutcome = "connected" | "cancelled" | "timed-out" | "removed" | "failed" + +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 { + private currentPhase: McpOAuthFlowPhase = "waiting" + private waitingTimeout?: ReturnType + get phase(): McpOAuthFlowPhase { + return this.currentPhase + } + readonly promise: Promise + private resolve!: (outcome: McpOAuthFlowOutcome) => void + private readonly cleanups: Cleanup[] = [] + + constructor() { + this.promise = new Promise((resolve) => { + this.resolve = resolve + }) + } + + addCleanup(cleanup: Cleanup): () => void { + let active = true + const dispose: Cleanup = (outcome) => { + if (!active) return + active = false + const index = this.cleanups.indexOf(dispose) + if (index !== -1) this.cleanups.splice(index, 1) + cleanup(outcome) + } + 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: "authenticating" | "ended"): void { + this.clearWaitingTimeout() + this.currentPhase = phase + } + + claim(): boolean { + if (this.phase !== "waiting") return false + this.transitionTo("authenticating") + return true + } + + finish(outcome: McpOAuthFlowOutcome): void { + if (this.phase === "ended") return + this.transitionTo("ended") + for (const cleanup of this.cleanups.splice(0).reverse()) { + try { + cleanup(outcome) + } catch (error) { + console.error("[McpHub] OAuth flow cleanup failed:", error) + } + } + this.resolve(outcome) + } +} diff --git a/src/services/mcp/SecretStorageService.ts b/src/services/mcp/SecretStorageService.ts index 10d4d3e483..8551e7bff2 100644 --- a/src/services/mcp/SecretStorageService.ts +++ b/src/services/mcp/SecretStorageService.ts @@ -24,6 +24,24 @@ export interface StoredMcpOAuthData { client_info?: OAuthClientInformationFull } +/** Returns the shared identity for storage and pending refresh requests. */ +export function getMcpOAuthStorageKey(serverUrl: string, clientId?: string): string { + const namespace = "mcp.oauth." + const url = new URL(serverUrl) + const normalizedPath = url.pathname.replace(/\/$/, "") + const encodedPath = Buffer.from(normalizedPath).toString("base64url") + + if (clientId) { + const encodedClientId = Buffer.from(clientId).toString("base64url") + const encodedResource = Buffer.from(`${normalizedPath}${url.search}`).toString("base64url") + return `${namespace}${url.protocol}//${url.host}.p-${encodedResource}.c-${encodedClientId}.data` + } + + // Dynamic registrations keep the legacy key for backward compatibility. + const pathSuffix = normalizedPath ? `.${encodedPath}` : "" + return `${namespace}${url.host}${pathSuffix}.data` +} + /** * Thin wrapper around VS Code SecretStorage for persisting MCP OAuth tokens. * Tokens are stored per server path and optional static client ID. Dynamic @@ -31,30 +49,13 @@ export interface StoredMcpOAuthData { */ export class SecretStorageService { private readonly _storage: vscode.SecretStorage - private readonly _namespace = "mcp.oauth." constructor(context: vscode.ExtensionContext) { this._storage = context.secrets } - private _key(serverUrl: string, clientId?: string): string { - const url = new URL(serverUrl) - const normalizedPath = url.pathname.replace(/\/$/, "") - const encodedPath = Buffer.from(normalizedPath).toString("base64url") - - if (clientId) { - const encodedClientId = Buffer.from(clientId).toString("base64url") - const encodedResource = Buffer.from(`${normalizedPath}${url.search}`).toString("base64url") - return `${this._namespace}${url.protocol}//${url.host}.p-${encodedResource}.c-${encodedClientId}.data` - } - - // Dynamic registrations keep the legacy key for backward compatibility. - const pathSuffix = normalizedPath ? `.${encodedPath}` : "" - return `${this._namespace}${url.host}${pathSuffix}.data` - } - async getOAuthData(serverUrl: string, clientId?: string): Promise { - const raw = await this._storage.get(this._key(serverUrl, clientId)) + const raw = await this._storage.get(getMcpOAuthStorageKey(serverUrl, clientId)) if (!raw) return undefined try { return JSON.parse(raw) as StoredMcpOAuthData @@ -64,16 +65,16 @@ export class SecretStorageService { } async saveOAuthData(serverUrl: string, data: StoredMcpOAuthData, clientId?: string): Promise { - await this._storage.store(this._key(serverUrl, clientId), JSON.stringify(data)) + await this._storage.store(getMcpOAuthStorageKey(serverUrl, clientId), JSON.stringify(data)) } async hasOAuthData(serverUrl: string, clientId?: string): Promise { - const raw = await this._storage.get(this._key(serverUrl, clientId)) + const raw = await this._storage.get(getMcpOAuthStorageKey(serverUrl, clientId)) return raw !== undefined } async deleteOAuthData(serverUrl: string, clientId?: string): Promise { - await this._storage.delete(this._key(serverUrl, clientId)) + await this._storage.delete(getMcpOAuthStorageKey(serverUrl, clientId)) } /** @@ -84,7 +85,7 @@ export class SecretStorageService { * @returns A dispose function — call it to stop listening. */ onDidChange(serverUrl: string, callback: () => void, clientId?: string): () => void { - const key = this._key(serverUrl, clientId) + const key = getMcpOAuthStorageKey(serverUrl, clientId) const disposable = this._storage.onDidChange((e) => { if (e.key === key) { callback() diff --git a/src/services/mcp/__tests__/McpHub.spec.ts b/src/services/mcp/__tests__/McpHub.spec.ts index 35ff10d64b..1a255e78a1 100644 --- a/src/services/mcp/__tests__/McpHub.spec.ts +++ b/src/services/mcp/__tests__/McpHub.spec.ts @@ -11,8 +11,10 @@ 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 } 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 = { @@ -136,7 +138,9 @@ vi.mock("@modelcontextprotocol/sdk/client/streamableHttp.js", () => ({ StreamableHTTPClientTransport: vi.fn(), })) -vi.mock("../McpOAuthClientProvider", () => ({ +vi.mock("../McpOAuthClientProvider", async (importOriginal) => ({ + UnsafeOAuthEndpointError: (await importOriginal()) + .UnsafeOAuthEndpointError, McpOAuthClientProvider: { create: vi.fn(), isKnownNonOAuth: vi.fn().mockReturnValue(false), @@ -569,10 +573,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(), @@ -593,14 +598,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) }) }) @@ -640,7 +648,7 @@ describe("McpHub", () => { }) // Mock the config file read BEFORE creating McpHub to avoid racing - // the constructor's initializeGlobalMcpServers() + // the constructor's initial global load vi.mocked(fs.readFile).mockResolvedValue( JSON.stringify({ mcpServers: { @@ -672,7 +680,7 @@ describe("McpHub", () => { it("should create disconnected connections for disabled servers", async () => { // Mock the config file read BEFORE creating McpHub to avoid racing - // the constructor's initializeGlobalMcpServers() + // the constructor's initial global load vi.mocked(fs.readFile).mockResolvedValue( JSON.stringify({ mcpServers: { @@ -1510,7 +1518,7 @@ describe("McpHub", () => { type: "connected", server: { name: "test-server", - config: "test-server-config", + config: JSON.stringify(mockConfig.mcpServers["test-server"]), status: "connected", source: "global", }, @@ -1558,7 +1566,7 @@ describe("McpHub", () => { type: "connected", server: { name: "test-server", - config: "test-server-config", + config: JSON.stringify(mockConfig.mcpServers["test-server"]), status: "connected", source: "global", }, @@ -1605,7 +1613,7 @@ describe("McpHub", () => { type: "connected", server: { name: "test-server", - config: "test-server-config", + config: JSON.stringify(mockConfig.mcpServers["test-server"]), status: "connected", source: "global", }, @@ -2900,10 +2908,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, @@ -2916,10 +2929,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) }) @@ -2932,14 +2948,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({ @@ -2970,7 +2979,6 @@ describe("McpHub", () => { source, config, mockAuthProvider, - mockTransport, mockConnection, ) @@ -2998,17 +3006,10 @@ 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((mcpHub as any).deleteConnection).toHaveBeenCalledWith(serverName, source, expect.any(McpOAuthFlow)) expect((mcpHub as any).connectToServer).toHaveBeenCalled() }) @@ -3017,18 +3018,11 @@ 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() - 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() }) @@ -3054,7 +3048,6 @@ describe("McpHub", () => { source, config, mockAuthProvider, - mockTransport, mockConnection, ) @@ -3071,13 +3064,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 = { @@ -3093,28 +3081,15 @@ describe("McpHub", () => { }) await expect( - (mcpHub as any)._initiateOAuthFlow( - serverName, - source, - config, - mockAuthProvider, - mockTransport, - mockConnection, - ), - ).resolves.toBeUndefined() + (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() - // 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. - // 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) + // The ended flow leaves no registry entry. + expect((mcpHub as any).oauthFlows.has(mockConnection)).toBe(false) }) it("should disconnect and flag error when OAuth flow times out", async () => { @@ -3128,7 +3103,6 @@ describe("McpHub", () => { source, config, mockAuthProvider, - mockTransport, mockConnection, ) @@ -3140,6 +3114,36 @@ 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, 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() @@ -3158,14 +3162,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() }) @@ -3180,18 +3183,11 @@ 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() - 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() }) @@ -3200,15 +3196,8 @@ 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, - ), - ).resolves.toBeUndefined() + (mcpHub as any)._initiateOAuthFlow(serverName, source, config, mockAuthProvider, mockConnection), + ).resolves.toBe("failed") }) it("should record the callback error and disconnect when waitForAuthCode rejects", async () => { @@ -3216,14 +3205,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() @@ -3267,13 +3249,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)) @@ -3303,7 +3284,6 @@ describe("McpHub", () => { source, config, mockAuthProvider, - mockTransport, mockConnection, ) mcpHub["isDisposed"] = true @@ -3337,7 +3317,6 @@ describe("McpHub", () => { source, config, mockAuthProvider, - mockTransport, mockConnection, ) @@ -3367,7 +3346,6 @@ describe("McpHub", () => { source, config, mockAuthProvider, - mockTransport, mockConnection, ) @@ -3376,13 +3354,13 @@ 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 () => { // This covers the race: onDidChange fires BEFORE getOAuthData resolves. // The flag causes a second read which finds the now-valid token. - let resolveGetOAuthData!: (value: any) => void + let resolveGetOAuthData!: (value: unknown) => void mockSecretStorage.getOAuthData // First call (during the race window) — delayed, returns undefined .mockImplementationOnce( @@ -3405,64 +3383,598 @@ describe("McpHub", () => { source, config, mockAuthProvider, - mockTransport, mockConnection, ) - // Now let the first getOAuthData resolve with undefined + // Wait for the storage read after config expansion, then release it. + await vi.waitFor(() => expect(typeof resolveGetOAuthData).toBe("function")) resolveGetOAuthData(undefined) 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 () => { - vi.useFakeTimers() - vsc.window.showInformationMessage.mockImplementation(() => { - return new Promise(() => {}) + 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() }) - // Start first flow (intentionally not awaited — the second call orphans it) - ;(mcpHub as any)._initiateOAuthFlow( - serverName, - source, - config, - mockAuthProvider, - mockTransport, - mockConnection, + 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(() => {})) + 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 + }) - // Flush microtasks: getOAuthData resolves, then withProgress fires synchronously - // (registering the watcher) — no tick-counting needed. + 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) - expect((mcpHub as any)._oauthWatchers.size).toBe(1) - const firstEntry = (mcpHub as any)._oauthWatchers.get(`${serverName}:${source}`) + const flow = mcpHub["oauthFlows"].get(mockConnection) + const subscriptions = mockSecretStorage.onDidChange.mock.calls.length + 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) + await vi.advanceTimersByTimeAsync(OAUTH_FLOW_TIMEOUT_MS) + await Promise.all([first, second]) + expect(mcpHub["oauthFlows"].size).toBe(0) + }) - // Start second flow for the same server — should tear down the first watcher - const secondFlow = (mcpHub as any)._initiateOAuthFlow( - serverName, - source, - config, - mockAuthProvider, - mockTransport, - mockConnection, + it("keeps a replacement flow when an old toast resolves", async () => { + vi.useFakeTimers() + let resolveFirstToast!: (choice?: string) => void + vsc.window.showInformationMessage.mockImplementationOnce( + () => + new Promise((resolve) => { + resolveFirstToast = resolve + }), ) - + vsc.window.showInformationMessage.mockImplementation(() => new Promise(() => {})) + 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, replacement) + await vi.advanceTimersByTimeAsync(0) + const currentFlow = mcpHub["oauthFlows"].get(replacement) + resolveFirstToast(t("mcp:oauth.flow.authenticateButton")) 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 + 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 + 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 { + oauthFlows: Map + _initiateOAuthFlow: ( + name: string, + source: "global" | "project", + config: unknown, + authProvider: 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) + + // The integration spec checks the error row on a real hub. + expect(hub.connectToServer).toHaveBeenCalled() + expect(closeMock).toHaveBeenCalled() + expect(hub.oauthFlows.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 { + oauthFlows: Map + _initiateOAuthFlow: ( + name: string, + source: "global" | "project", + config: unknown, + authProvider: 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) + + // The integration spec checks the error row on a real hub. + expect(hub.connectToServer).toHaveBeenCalled() + expect(hub.oauthFlows.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 { + oauthFlows: 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.oauthFlows.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.oauthFlows.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, + hasMetadata = true, + ): 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, + 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.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(() => { + 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("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, + ) + } + 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() + } + }) + + // 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() + 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 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) + 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 + 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 185bf4c461..812d0338f8 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,16 +50,18 @@ mockFetch.mockResolvedValue({ grant_types_supported: ["authorization_code", "refresh_token"], }), }) +mockFetch.mockImplementation(defaultAuthServerFetch) import { McpOAuthClientProvider } from "../McpOAuthClientProvider" -import { SecretStorageService, StoredMcpOAuthData } from "../SecretStorageService" +import { SecretStorageService, StoredMcpOAuthData, getMcpOAuthStorageKey } from "../SecretStorageService" import { startCallbackServer, stopCallbackServer } from "../utils/callbackServer" import { discoverOAuthProtectedResourceMetadata } from "@modelcontextprotocol/sdk/client/auth.js" import * as vscode from "vscode" function createMockSecretStorage(): SecretStorageService { const store = new Map() - const key = (url: string, clientId?: string) => `${url}:${clientId ?? "dynamic"}` + const key = getMcpOAuthStorageKey + // The storage double supplies getOAuthData, saveOAuthData, and deleteOAuthData. return { getOAuthData: vi.fn(async (url: string, clientId?: string) => { const raw = store.get(key(url, clientId)) @@ -166,6 +169,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() }) @@ -173,6 +179,90 @@ describe("McpOAuthClientProvider", () => { global.fetch = originalFetch }) + it.each(["none", "client_secret_post", "client_secret_basic"])( + "uses %s for exchange and refresh", + async (method) => { + const provider = await McpOAuthClientProvider.create("https://example.com/mcp", createMockSecretStorage()) + await provider.saveClientInformation({ + client_id: "client: +&", + client_secret: "secret: +&", + token_endpoint_auth_method: method, + redirect_uris: [], + }) + await provider.saveCodeVerifier("verifier") + for (const grant of ["exchange", "refresh"]) { + mockFetch.mockResolvedValueOnce( + new Response( + JSON.stringify({ access_token: "fresh", refresh_token: "refresh", token_type: "Bearer" }), + ), + ) + if (grant === "exchange") await provider.exchangeCodeForTokens("code") + else await provider.refreshAccessToken("refresh") + const request = mockFetch.mock.calls.at(-1)?.[1] as RequestInit + const body = new URLSearchParams(String(request.body)) + expect(body.get("client_secret")).toBe(method === "client_secret_post" ? "secret: +&" : null) + expect(new Headers(request.headers).get("Authorization")).toBe( + method === "client_secret_basic" + ? `Basic ${Buffer.from("client%3A+%2B%26:secret%3A+%2B%26").toString("base64")}` + : null, + ) + } + await provider.close() + }, + ) + + it.each(["client_secret_post", "client_secret_basic"])( + "uses discovered %s when the registration omits a method", + async (method) => { + mockFetch.mockResolvedValueOnce({ + ok: true, + json: async () => ({ + ...(await defaultAuthServerFetch().json()), + token_endpoint_auth_methods_supported: [method], + }), + }) + const provider = await McpOAuthClientProvider.create("https://example.com/mcp", createMockSecretStorage()) + await provider.saveClientInformation({ client_id: "client", client_secret: "secret", redirect_uris: [] }) + const registration = provider["_clientInfo"] + if (!registration) throw new Error("Expected a client registration") + delete registration.token_endpoint_auth_method + await provider.saveCodeVerifier("verifier") + mockFetch.mockResolvedValueOnce( + new Response(JSON.stringify({ access_token: "fresh", token_type: "Bearer" })), + ) + await provider.exchangeCodeForTokens("code") + const request = mockFetch.mock.calls.at(-1)?.[1] as RequestInit + expect(new URLSearchParams(String(request.body)).get("client_secret")).toBe( + method === "client_secret_post" ? "secret" : null, + ) + expect(new Headers(request.headers).has("Authorization")).toBe(method === "client_secret_basic") + await provider.close() + }, + ) + + it.each(["http://remote.example/register", "https://auth.example.com/register"])( + "checks registration transport for %s", + async (endpoint) => { + setupCallbackServerMock() + const provider = await McpOAuthClientProvider.create("https://example.com/mcp", createMockSecretStorage()) + const metadata = provider["_authServerMeta"] + if (!metadata) throw new Error("Expected authorization server metadata") + metadata.registration_endpoint = endpoint + mockFetch.mockClear() + mockFetch.mockResolvedValueOnce( + new Response(JSON.stringify({ client_id: "registered", redirect_uris: [] })), + ) + if (endpoint.startsWith("http:")) { + await expect(provider.registerClientIfNeeded()).rejects.toThrow() + expect(mockFetch).not.toHaveBeenCalled() + } else { + await provider.registerClientIfNeeded() + expect(mockFetch).toHaveBeenCalledWith(endpoint, expect.objectContaining({ redirect: "manual" })) + } + await provider.close() + }, + ) + describe("static negative cache", () => { it("isKnownNonOAuth returns false for unknown servers", () => { expect(McpOAuthClientProvider.isKnownNonOAuth("https://unknown.com/mcp")).toBe(false) @@ -334,12 +424,118 @@ 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('{"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() + 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() @@ -496,7 +692,7 @@ describe("McpOAuthClientProvider", () => { it.each([ ["a different issuer", "https://evil.example.com"], ["no issuer (saved by an older version)", undefined], - ])("should not refresh and should clear stored data when stored data has %s", async (_label, issuer) => { + ])("keeps stored data and does not refresh when stored data has %s", async (_label, issuer) => { setupCallbackServerMock() const secretStorage = createMockSecretStorage() const provider = await McpOAuthClientProvider.create("https://example.com/mcp", secretStorage) @@ -510,7 +706,7 @@ describe("McpOAuthClientProvider", () => { expect(await provider.tokens()).toBeUndefined() expect(mockFetch).not.toHaveBeenCalled() - expect(await secretStorage.getOAuthData("https://example.com/mcp")).toBeUndefined() + expect(await secretStorage.getOAuthData("https://example.com/mcp")).toBeDefined() }) it("should refresh tokens when access token is expired but refresh token exists", async () => { @@ -542,7 +738,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({ @@ -555,7 +752,7 @@ describe("McpOAuthClientProvider", () => { await provider.close() }) - it("should use a rotated refresh token when the server returns one", async () => { + it.each(["open", "closed"])("saves a rotated token with the callback %s", async (listener) => { setupCallbackServerMock() const secretStorage = createMockSecretStorage() const provider = await McpOAuthClientProvider.create("https://example.com/mcp", secretStorage) @@ -580,9 +777,11 @@ describe("McpOAuthClientProvider", () => { }), }) + if (listener === "closed") await provider.close() 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", ) @@ -770,7 +969,402 @@ describe("McpOAuthClientProvider", () => { expect(await provider.tokens()).toBeUndefined() expect(mockFetch).not.toHaveBeenCalled() - expect(await secretStorage.getOAuthData(serverUrl, clientId)).toBeUndefined() + expect(await secretStorage.getOAuthData(serverUrl, clientId)).toBeDefined() + }) + + 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() + }) + + // Invariant: McpOAuthRefreshToken.ExactRejection. Only a parsed HTTP 400 invalid_grant deletes data. + it.each([ + [400, '{"error":"invalid_grant"}', true], + [500, '{"error":"invalid_grant"}', false], + [400, '{"error":"server_error","error_description":"invalid_grant"}', false], + [400, "invalid_grant", false], + ])("checks refresh rejection status %s and body %s", async (status, body, rejected) => { + const storage = createMockSecretStorage() + const provider = await McpOAuthClientProvider.create("https://example.com/mcp", storage) + await storage.saveOAuthData("https://example.com/mcp", { + tokens: { access_token: "expired", refresh_token: "old", token_type: "Bearer" }, + expires_at: 0, + issuer: "https://auth.example.com", + client_info: { client_id: "registered", redirect_uris: [] }, + }) + mockFetch.mockResolvedValueOnce({ ok: false, status, text: async () => body }) + expect(await provider.tokens()).toBeUndefined() + expect(vi.mocked(storage.deleteOAuthData).mock.calls.length > 0).toBe(rejected) + await provider.close() + }) + + // Invariant: McpOAuthRefreshToken.FreshSave. A pending refresh cannot restore deleted or newer data. + it.each(["close", "delete", "replace", "accept"])("guards a refresh after %s", async (action) => { + const storage = createMockSecretStorage() + const provider = await McpOAuthClientProvider.create("https://example.com/mcp", storage) + const data: StoredMcpOAuthData = { + tokens: { access_token: "expired", refresh_token: "old", token_type: "Bearer" }, + expires_at: 0, + issuer: "https://auth.example.com", + client_info: { client_id: "registered", redirect_uris: [] }, + } + await storage.saveOAuthData("https://example.com/mcp", data) + const response = deferred() + mockFetch.mockReturnValueOnce(response.promise) + const refreshing = provider.tokens() + await vi.waitFor(() => + expect(mockFetch).toHaveBeenLastCalledWith( + "https://auth.example.com/token", + expect.objectContaining({ method: "POST" }), + ), + ) + if (action === "close") await provider.close() + if (action === "delete") await storage.deleteOAuthData("https://example.com/mcp") + if (action === "replace") + await storage.saveOAuthData("https://example.com/mcp", { + ...data, + tokens: { ...data.tokens, access_token: "newer", refresh_token: "newer" }, + }) + vi.mocked(storage.saveOAuthData).mockClear() + response.resolve(new Response(JSON.stringify({ access_token: "refreshed", token_type: "Bearer" }))) + await refreshing + expect(vi.mocked(storage.saveOAuthData).mock.calls.length).toBe( + action === "accept" || action === "close" ? 1 : 0, + ) + await provider.close() + }) + + // Invariant: SharedRefresh. Both providers receive the same rotation result. + it.each([false, true])("shares a rotating refresh across providers, reverse order %s", async (reverse) => { + const storage = createMockSecretStorage() + const providers = await Promise.all( + [0, 1].map(() => McpOAuthClientProvider.create("https://example.com/mcp", storage)), + ) + const data: StoredMcpOAuthData = { + tokens: { access_token: "expired", refresh_token: "old", token_type: "Bearer" }, + expires_at: 0, + issuer: "https://auth.example.com", + client_info: { client_id: "registered", redirect_uris: [] }, + } + await storage.saveOAuthData("https://example.com/mcp", data) + mockFetch.mockClear() + const response = deferred() + mockFetch.mockReturnValueOnce(response.promise) + const results = (reverse ? [...providers].reverse() : providers).map((provider) => provider.tokens()) + await vi.waitFor(() => expect(mockFetch).toHaveBeenCalledTimes(1)) + response.resolve( + new Response(JSON.stringify({ access_token: "fresh", refresh_token: "rotated", token_type: "Bearer" })), + ) + expect(await Promise.all(results)).toEqual([ + expect.objectContaining({ access_token: "fresh" }), + expect.objectContaining({ access_token: "fresh" }), + ]) + expect(mockFetch).toHaveBeenCalledTimes(1) + expect((await storage.getOAuthData("https://example.com/mcp"))?.tokens.refresh_token).toBe("rotated") + await Promise.all(providers.map((provider) => provider.close())) + }) + + // Invariants: SharedRefresh and SettledResult. Every caller handles the shared result. + it.each( + [true, false].flatMap((sameProvider) => + ["ok", "retry", "rejected"].map((outcome) => ({ sameProvider, outcome })), + ), + )( + "shares $outcome and permits a later retry, same provider $sameProvider", + async ({ sameProvider, outcome }) => { + const storage = createMockSecretStorage() + const first = await McpOAuthClientProvider.create("https://example.com/mcp", storage) + const second = sameProvider + ? first + : await McpOAuthClientProvider.create("https://example.com/mcp", storage) + const data: StoredMcpOAuthData = { + tokens: { access_token: "expired", refresh_token: "old", token_type: "Bearer" }, + expires_at: 0, + issuer: "https://auth.example.com", + client_info: { client_id: "registered", redirect_uris: [] }, + } + await storage.saveOAuthData("https://example.com/mcp", data) + mockFetch.mockClear() + const response = deferred() + mockFetch.mockReturnValueOnce(response.promise) + const calls = Promise.allSettled([first.tokens(), second.tokens()]) + await vi.waitFor(() => expect(mockFetch).toHaveBeenCalledTimes(1)) + response.resolve( + outcome === "ok" + ? new Response( + JSON.stringify({ + access_token: "fresh", + refresh_token: "rotated", + token_type: "Bearer", + expires_in: 3600, + }), + ) + : new Response( + JSON.stringify({ error: outcome === "rejected" ? "invalid_grant" : "server_error" }), + { status: outcome === "rejected" ? 400 : 500 }, + ), + ) + expect(await calls).toEqual( + [0, 1].map(() => ({ + status: "fulfilled", + value: outcome === "ok" ? expect.objectContaining({ access_token: "fresh" }) : undefined, + })), + ) + const saved = await storage.getOAuthData("https://example.com/mcp") + if (outcome === "rejected") expect(saved).toBeUndefined() + else expect(saved?.tokens.refresh_token).toBe(outcome === "ok" ? "rotated" : "old") + await storage.saveOAuthData("https://example.com/mcp", data) + mockFetch.mockResolvedValueOnce( + new Response( + JSON.stringify({ access_token: "retry-result", token_type: "Bearer", expires_in: 3600 }), + ), + ) + expect(await second.tokens()).toMatchObject({ access_token: "retry-result" }) + expect(mockFetch).toHaveBeenCalledTimes(2) + await Promise.all([first.close(), second.close()]) + }, + ) + + // Invariant: CurrentCredentialResult. A newer stored token has its own pending request. + it("refreshes a replacement credential while the old refresh is pending", async () => { + const storage = createMockSecretStorage() + const provider = await McpOAuthClientProvider.create("https://example.com/mcp", storage) + const data: StoredMcpOAuthData = { + tokens: { access_token: "expired", refresh_token: "old", token_type: "Bearer" }, + expires_at: 0, + issuer: "https://auth.example.com", + client_info: { client_id: "registered", redirect_uris: [] }, + } + await storage.saveOAuthData("https://example.com/mcp", data) + mockFetch.mockClear() + const oldResponse = deferred() + mockFetch.mockReturnValueOnce(oldResponse.promise) + const oldCall = provider.tokens() + await vi.waitFor(() => expect(mockFetch).toHaveBeenCalledTimes(1)) + await storage.saveOAuthData("https://example.com/mcp", { + ...data, + tokens: { ...data.tokens, refresh_token: "replacement" }, + }) + mockFetch.mockResolvedValueOnce( + new Response( + JSON.stringify({ + access_token: "replacement-result", + refresh_token: "rotated", + token_type: "Bearer", + expires_in: 3600, + }), + ), + ) + const readsBeforeReplacement = vi.mocked(storage.getOAuthData).mock.calls.length + const replacementCall = provider.tokens() + // Wait for the storage read before releasing the older response. + await vi.waitFor(() => + expect(vi.mocked(storage.getOAuthData).mock.calls.length).toBeGreaterThan(readsBeforeReplacement), + ) + oldResponse.resolve(new Response(JSON.stringify({ access_token: "stale", token_type: "Bearer" }))) + expect(await replacementCall).toMatchObject({ access_token: "replacement-result" }) + expect(await oldCall).toBeUndefined() + expect(mockFetch).toHaveBeenCalledTimes(2) + expect((await storage.getOAuthData("https://example.com/mcp"))?.tokens.refresh_token).toBe("rotated") + await provider.close() + }) + + // Invariant: BoundRegistration. A refresh uses and saves one complete registration. + it("uses the registration saved with the refresh token", async () => { + const storage = createMockSecretStorage() + const provider = await McpOAuthClientProvider.create("https://example.com/mcp", storage) + const registration = { + client_id: "old-id", + client_secret: "old-secret", + token_endpoint_auth_method: "client_secret_post", + redirect_uris: [], + } + await provider.saveClientInformation({ ...registration, client_id: "new-id", client_secret: "new-secret" }) + await storage.saveOAuthData("https://example.com/mcp", { + tokens: { access_token: "expired", refresh_token: "old", token_type: "Bearer" }, + expires_at: 0, + issuer: "https://auth.example.com", + client_info: registration, + }) + mockFetch.mockClear() + mockFetch.mockResolvedValueOnce( + new Response(JSON.stringify({ access_token: "fresh", token_type: "Bearer" })), + ) + await provider.tokens() + const body = new URLSearchParams(mockFetch.mock.calls[0][1].body) + expect(body.get("client_id")).toBe("old-id") + expect(body.get("client_secret")).toBe("old-secret") + expect((await storage.getOAuthData("https://example.com/mcp"))?.client_info).toEqual(registration) + await provider.close() + }) + + // Invariants: BoundEndpoint and AvailableEndpoint. Accept advertised HTTPS or loopback HTTP endpoints. + it.each( + [ + ["https://auth.example.com/token", true], + ["http://auth.example.com/token", false], + ["https://other.example.com/token", true], + ["https://auth.example.com:444/token", true], + ["http://localhost:8080/token", true], + ["http://127.0.0.1:8080/token", true], + ["http://[::1]:8080/token", true], + ["http://localhost.evil.example/token", false], + ["https://user:secret@auth.example.com/token", false], + ["file:///tmp/token", false], + ].flatMap(([endpoint, accepted]) => + ["refresh", "exchange"].map((request) => ({ + endpoint: String(endpoint), + accepted: Boolean(accepted), + request, + })), + ), + )("guards $request endpoint $endpoint", async ({ endpoint, accepted, request }) => { + const storage = createMockSecretStorage() + setupCallbackServerMock() + const provider = await McpOAuthClientProvider.create("https://example.com/mcp", storage, undefined, { + clientId: "static", + }) + await storage.saveOAuthData( + "https://example.com/mcp", + { + tokens: { access_token: "expired", refresh_token: "secret", token_type: "Bearer" }, + expires_at: 0, + }, + "static", + ) + const metadata = provider["_authServerMeta"] + if (!metadata) throw new Error("Missing discovery metadata") + metadata.token_endpoint = endpoint + mockFetch.mockClear() + mockFetch.mockResolvedValueOnce( + new Response(JSON.stringify({ access_token: "fresh", token_type: "Bearer" })), + ) + provider["_codeVerifier"] = "verifier" + const refresh = + request === "refresh" ? provider.refreshAccessToken("secret") : provider.exchangeCodeForTokens("code") + if (accepted) await refresh + else await expect(refresh).rejects.toThrow("Unsafe OAuth endpoint") + expect(mockFetch.mock.calls.length).toBe(accepted ? 1 : 0) + if (accepted) + expect(mockFetch).toHaveBeenCalledWith(endpoint, expect.objectContaining({ redirect: "manual" })) + await provider.close() + }) + + it.each([ + ["https://accounts.google.com", "https://oauth2.googleapis.com/token"], + ["http://localhost:8080", "http://localhost:8080/token"], + ])("refreshes stored credentials for issuer %s at its advertised endpoint", async (issuer, endpoint) => { + const storage = createMockSecretStorage() + const serverUrl = "https://example.com/mcp" + vi.mocked(discoverOAuthProtectedResourceMetadata).mockResolvedValueOnce({ + resource: serverUrl, + authorization_servers: [issuer], + }) + mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({ issuer, token_endpoint: endpoint }) }) + setupCallbackServerMock() + const provider = await McpOAuthClientProvider.create(serverUrl, storage, undefined, { clientId: "static" }) + try { + await storage.saveOAuthData( + serverUrl, + { + tokens: { access_token: "expired", refresh_token: "secret", token_type: "Bearer" }, + expires_at: 0, + issuer, + }, + "static", + ) + mockFetch.mockClear() + mockFetch.mockResolvedValueOnce( + new Response(JSON.stringify({ access_token: "fresh", token_type: "Bearer" })), + ) + expect(await provider.tokens()).toMatchObject({ access_token: "fresh" }) + expect(mockFetch).toHaveBeenCalledWith(endpoint, expect.objectContaining({ redirect: "manual" })) + expect(storage.deleteOAuthData).not.toHaveBeenCalled() + } finally { + await provider.close() + } + }) + + it("reports deferred refresh without discovery and keeps its credential", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}) + const storage = createMockSecretStorage() + const provider = await McpOAuthClientProvider.create("https://example.com/mcp", storage, undefined, { + skipDiscovery: true, + }) + try { + await storage.saveOAuthData("https://example.com/mcp", { + tokens: { access_token: "expired", refresh_token: "secret", token_type: "Bearer" }, + expires_at: 0, + }) + expect(await provider.tokens()).toBeUndefined() + expect(warn).toHaveBeenCalledWith( + "[MCP OAuth] Token refresh deferred: authorization server discovery is not available", + ) + expect(storage.deleteOAuthData).not.toHaveBeenCalled() + } finally { + warn.mockRestore() + 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 () => { @@ -835,6 +1429,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")) @@ -1688,6 +2300,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 0000000000..6166220bfd --- /dev/null +++ b/src/services/mcp/__tests__/McpOAuthFlow.spec.ts @@ -0,0 +1,103 @@ +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(await flow.promise).toBe(outcome) + expect(cleanup).toHaveBeenCalledExactlyOnceWith(outcome) + }, + ) + + // 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) + 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("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) + expect(flow.claim()).toBe(true) + expect(vi.getTimerCount()).toBe(0) + await vi.advanceTimersByTimeAsync(300_000) + expect(expired).not.toHaveBeenCalled() + expect(flow.phase).toBe("authenticating") + } 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(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__/SecretStorageService.spec.ts b/src/services/mcp/__tests__/SecretStorageService.spec.ts index 9f1366774f..f306a629de 100644 --- a/src/services/mcp/__tests__/SecretStorageService.spec.ts +++ b/src/services/mcp/__tests__/SecretStorageService.spec.ts @@ -1,8 +1,8 @@ -import { describe, it, expect, vi, beforeEach } from "vitest" +import type * as vscode from "vscode" vi.mock("vscode", () => ({})) -import { SecretStorageService, StoredMcpOAuthData } from "../SecretStorageService" +import { SecretStorageService, StoredMcpOAuthData, getMcpOAuthStorageKey } from "../SecretStorageService" function createMockContext() { const store = new Map() @@ -29,7 +29,7 @@ function createMockContext() { }, } - return { secrets } as any + return { secrets } } describe("SecretStorageService", () => { @@ -38,7 +38,71 @@ describe("SecretStorageService", () => { beforeEach(() => { context = createMockContext() - service = new SecretStorageService(context) + // The context double provides the SecretStorage methods used by this service. + service = new SecretStorageService(context as unknown as vscode.ExtensionContext) + }) + + // Credential identity is an input oracle in McpCredentialOwnership. + describe("shared credential identity", () => { + const url = "https://example.com/mcp" + const cases: { + label: string + left: { url: string; clientId?: string } + right: { url: string; clientId?: string } + same: boolean + }[] = [ + { label: "dynamic URL aliases", left: { url }, right: { url: "https://EXAMPLE.com:443/mcp/" }, same: true }, + { + label: "legacy dynamic scheme and query", + left: { url }, + right: { url: "http://example.com/mcp?tenant=b" }, + same: true, + }, + { + label: "static URL aliases", + left: { url, clientId: "client" }, + right: { url: `${url}/`, clientId: "client" }, + same: true, + }, + { + label: "static scheme", + left: { url, clientId: "client" }, + right: { url: "http://example.com/mcp", clientId: "client" }, + same: false, + }, + { + label: "static query", + left: { url, clientId: "client" }, + right: { url: `${url}?tenant=b`, clientId: "client" }, + same: false, + }, + { label: "client ID", left: { url, clientId: "a" }, right: { url, clientId: "b" }, same: false }, + { label: "static and dynamic", left: { url, clientId: "client" }, right: { url }, same: false }, + { label: "host", left: { url }, right: { url: "https://other.example.com/mcp" }, same: false }, + { label: "path", left: { url }, right: { url: "https://example.com/other" }, same: false }, + { + label: "static root and dynamic path", + left: { url: "https://example.com/", clientId: "/mcp" }, + right: { url }, + same: false, + }, + ] + it.each(cases)("uses the same identity for every reader and writer: $label", async ({ left, right, same }) => { + const data: StoredMcpOAuthData = { tokens: { access_token: "stored", token_type: "Bearer" }, expires_at: 1 } + const leftKey = getMcpOAuthStorageKey(left.url, left.clientId) + expect(leftKey === getMcpOAuthStorageKey(right.url, right.clientId)).toBe(same) + await service.saveOAuthData(left.url, data, left.clientId) + expect(context.secrets.store).toHaveBeenLastCalledWith(leftKey, JSON.stringify(data)) + expect(await service.getOAuthData(right.url, right.clientId)).toEqual(same ? data : undefined) + expect(await service.hasOAuthData(right.url, right.clientId)).toBe(same) + const changed = vi.fn() + const unsubscribe = service.onDidChange(right.url, changed, right.clientId) + context.secrets._emit(leftKey) + expect(changed).toHaveBeenCalledTimes(same ? 1 : 0) + unsubscribe() + await service.deleteOAuthData(right.url, right.clientId) + expect(await service.getOAuthData(left.url, left.clientId)).toEqual(same ? undefined : data) + }) }) describe("getOAuthData", () => { @@ -60,7 +124,7 @@ describe("SecretStorageService", () => { it("should return undefined for malformed JSON", async () => { // Manually store garbage via the underlying mock (key uses base64url-encoded path) - context.secrets.store("mcp.oauth.example.com.L21jcA.data", "not-json") + await context.secrets.store("mcp.oauth.example.com.L21jcA.data", "not-json") const result = await service.getOAuthData("https://example.com/mcp") expect(result).toBeUndefined() 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 0000000000..39e0de2454 --- /dev/null +++ b/src/services/mcp/__tests__/mcp-oauth-flow.property.spec.ts @@ -0,0 +1,784 @@ +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 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 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") + 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", async (importOriginal) => ({ + ...(await importOriginal()), + 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; error?: string } + client: { request: Mock; close: Mock } + transport: { close: Mock } + authProvider?: unknown +} + +type FlowHandle = { + connection: TestConnection + authProvider: { close: Mock } + promise: Promise + resolved: boolean +} + +type FlowHub = { + callTool: McpHub["callTool"] + waitUntilReady: () => Promise + _runOAuthFlow: ( + name: string, + source: "global" | "project", + config: unknown, + serverUrl: string, + authProvider: unknown, + connection: unknown, + progress: unknown, + cancellationToken: unknown, + oauthClientId: string | undefined, + flow: unknown, + ) => Promise + createOAuthFlow: (connection: unknown, authProvider: unknown) => unknown + deleteConnection: (name: string, source?: string) => Promise + notifyWebviewOfServerChanges: Mock + findConnection: Mock + validateServerConfig: Mock + appendErrorMessage: Mock + oauthFlows: 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.error = message + }) + 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 = { + 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() })), + } + 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, + hub.createOAuthFlow(connection, authProvider), + ) + const handle: FlowHandle = { + connection, + authProvider, + 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() + }) + + // 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. + 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) + 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, + ) + : completeClaimedFlow(hub, provider, connection) + 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) + 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) + 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) + 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 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 + + for (let history = 0; history < histories; history++) { + const hub = await createFlowHub() + const flows: FlowHandle[] = [] + + 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") { + // 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") + } 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 stays registered. + expect(unresolved.length === 1).toBe(hub.oauthFlows.size === 1) + } + + // 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 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 () => { + 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/__tests__/mcp-oauth-ownership.integration.spec.ts b/src/services/mcp/__tests__/mcp-oauth-ownership.integration.spec.ts new file mode 100644 index 0000000000..fb2891ab27 --- /dev/null +++ b/src/services/mcp/__tests__/mcp-oauth-ownership.integration.spec.ts @@ -0,0 +1,739 @@ +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" +import { McpOAuthClientProvider } from "../McpOAuthClientProvider" +import { OAUTH_FLOW_TIMEOUT_MS } from "../constants" + +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 } +} + +type Row = { name: string; status: string; error?: string; disabled?: boolean } + +type HarnessOptions = { + unsafeRegistration?: boolean + variableUrl?: boolean + /** 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: options.unsafeRegistration + ? "http://unsafe.example/register" + : `${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 || options.unsafeRegistration ? undefined : { clientId: "static-client" } + if (options.knownNonOAuth) McpOAuthClientProvider.markNonOAuth(url) + const previousServerUrl = process.env.MCP_REVIEW_PATH + if (options.variableUrl) process.env.MCP_REVIEW_PATH = "mcp" + const config = { + type: "streamable-http", + url: options.variableUrl ? `${base}/\${env:MCP_REVIEW_PATH}` : 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: vi.fn(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 (options.variableUrl) { + if (previousServerUrl === undefined) delete process.env.MCP_REVIEW_PATH + else process.env.MCP_REVIEW_PATH = previousServerUrl + } + 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)(:|$)/)) + afterEach(() => nock.disableNetConnect()) + // Invariant: McpOAuthPanelSettle. A real toast approval controls the browser and token request. + it.each(["authenticate", "dismiss", "timeout"])("settles a real hub after toast %s", async (outcome) => { + const approve = outcome === "authenticate" + const timer = global.setTimeout + const timeout = vi + .spyOn(global, "setTimeout") + .mockImplementation((callback, delay, ...args) => + timer(callback, outcome === "timeout" && delay === OAUTH_FLOW_TIMEOUT_MS ? 200 : delay, ...args), + ) + const harness = await startHarness({ testMode: false }) + // The runtime overload returns a string label; the VS Code type exposes its MessageItem overload. + const choose = vi.fn(async (_message: string, ...items: string[]) => + approve ? items.find((item) => item === t("mcp:oauth.flow.authenticateButton")) : undefined, + ) + Object.assign(vscode.window, { showInformationMessage: choose }) + try { + const ready = harness.hub.waitUntilReady() + if (approve) await ready + if (!approve) { + await vi.waitFor(() => expect(vscode.window.showInformationMessage).toHaveBeenCalled()) + expect(harness.count("token")).toBe(0) + expect(vscode.env.openExternal).not.toHaveBeenCalled() + if (outcome === "dismiss") harness.cancel() + } + await harness.settle() + await ready + expect(harness.hub.connections[0]?.server.status).toBe(approve ? "connected" : "disconnected") + expect(harness.count("token")).toBe(approve ? 1 : 0) + expect(vscode.env.openExternal).toHaveBeenCalledTimes(approve ? 1 : 0) + } finally { + vi.mocked(vscode.window.showInformationMessage).mockReset() + await harness.close() + timeout.mockRestore() + } + }) + + it.each( + ["browser", "exchange", "reconnect"].flatMap((phase) => + [ + "accept", + "delete", + "disable", + "dispose", + "cancel", + ...(phase === "reconnect" ? ["cancel-delete"] : []), + ].map((action) => ({ phase, action })), + ), + )( + "$action during $phase does not restore a removed or disabled server", + async ({ phase, action }) => { + const entered = deferred() + const release = deferred() + const hold = async () => { + entered.resolve() + await release.promise + } + 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() + }, + }) + const { hub, panelRows } = harness + try { + await hub.waitUntilReady() + await entered.promise + 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") harness.cancel() + if (action === "cancel-delete") await hub.deleteConnection("local", "global") + release.resolve() + 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(harness.count("initialize")).toBe(before) + else expect(harness.count("initialize")).toBeGreaterThan(before) + } else { + expect(harness.count("initialize")).toBe(before) + if (action === "disable") expect(hub.connections[0]?.server.disabled).toBe(true) + 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("mcp:oauth.flow.cancelled")) + await vi.waitFor(() => + expect(panelRows.at(-1)?.[0]).toMatchObject({ + name: "local", + status: "disconnected", + error: hub.connections[0]?.server.error, + }), + ) + if (phase === "reconnect") { + harness.resetCancellation() + 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 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) + it("stops before SDK transport creation after unsafe registration", async () => { + const harness = await startHarness({ unsafeRegistration: true }) + try { + await harness.hub.waitUntilReady() + expect(harness.hub.connections[0].server.status).toBe("disconnected") + expect(harness.hub.connections[0].server.error).toContain("Unsafe OAuth endpoint") + expect(harness.count("initialize")).toBe(0) + expect(harness.count("token")).toBe(0) + } finally { + await harness.close() + } + }) + it.each([false, true])("retains the raw URL after OAuth with negative cache=%s", async (knownNonOAuth) => { + const harness = await startHarness({ variableUrl: true, knownNonOAuth }) + try { + await harness.hub.waitUntilReady() + await harness.settle() + expect(harness.hub.connections[0].server.status).toBe("connected") + expect(harness.count("token")).toBeGreaterThan(0) + expect(harness.values.has(harness.url)).toBe(true) + expect(harness.storage.getOAuthData.mock.calls.every(([key]) => key === harness.url)).toBe(true) + expect(JSON.parse(harness.hub.connections[0].server.config).url).toContain("${env:MCP_REVIEW_PATH}") + } finally { + await harness.close() + } + }) + it("keeps the raw config after a connect-time token retry", async () => { + const harness = await startHarness({ + variableUrl: true, + savedToken: "stale", + onRequest: async (_method, token) => (token === "stale" ? 401 : undefined), + }) + try { + await harness.hub.waitUntilReady() + await vi.waitFor(() => expect(harness.hub.connections[0]?.server.status).toBe("disconnected"), { + timeout: 20000, + }) + expect(JSON.parse(harness.hub.connections[0].server.config).url).toContain("${env:MCP_REVIEW_PATH}") + } finally { + await harness.close() + } + }, 30000) + // A raw config keeps its variables across initial sign-in and a tool-triggered retry. + it("expands OAuth identity at use while retaining the config template", async () => { + let rejected = false + const harness = await startHarness({ + variableUrl: true, + onRequest: async (method) => { + if (method === "tools/call" && !rejected) { + rejected = true + return 401 + } + return undefined + }, + }) + try { + await harness.hub.waitUntilReady() + await harness.settle() + await harness.hub.callTool("local", "example", {}, "global") + await harness.settle() + expect(harness.values.has(harness.url)).toBe(true) + expect([...harness.values.keys()].some((key) => key.includes("${env:MCP_REVIEW_PATH}"))).toBe(false) + expect(JSON.parse(harness.hub.connections[0].server.config).url).toContain("${env:MCP_REVIEW_PATH}") + } finally { + await harness.close() + } + }) +}) 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 0000000000..ce1f2777f3 --- /dev/null +++ b/src/services/mcp/__tests__/mcp-server-toggle.integration.spec.ts @@ -0,0 +1,846 @@ +import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "fs/promises" +import { tmpdir } from "os" +import { join } from "path" +import delay from "delay" +import * as vscode from "vscode" + +import type { ClineProvider } from "../../../core/webview/ClineProvider" +import { safeWriteJson } from "../../../utils/safeWriteJson" +import { McpHub } from "../McpHub" +import { SecretStorageService, getMcpOAuthStorageKey } from "../SecretStorageService" + +vi.mock("../../../utils/safeWriteJson", async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, safeWriteJson: vi.fn(actual.safeWriteJson) } +}) +vi.mock("delay", () => ({ default: vi.fn(async () => {}) })) +vi.mock("vscode", () => ({ + workspace: { + createFileSystemWatcher: vi.fn(() => ({ + onDidChange: vi.fn(), + onDidCreate: vi.fn(), + onDidDelete: vi.fn(), + dispose: vi.fn(), + })), + onDidSaveTextDocument: () => ({ dispose: vi.fn() }), + onDidChangeWorkspaceFolders: () => ({ dispose: vi.fn() }), + workspaceFolders: [], + }, + RelativePattern: vi.fn(), + Disposable: { from: vi.fn(() => ({ dispose: vi.fn() })) }, + 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( + onStarting?: (hub: McpHub, settings: string) => Promise, + initialSource: "global" | "project" = "global", +) { + 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 } } })) + let initialSettings = settings + if (initialSource === "project") { + await mkdir(join(directory, ".roo")) + initialSettings = join(directory, ".roo", "mcp.json") + await writeFile(initialSettings, await readFile(settings)) + await writeFile(settings, JSON.stringify({ mcpServers: {} })) + } + // The extension double supplies settings, panel updates, and the extension version. + const provider = { + cwd: directory, + 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 onStarting?.(hub, initialSettings) + await hub.waitUntilReady() + return { + hub, + saved: async () => JSON.parse(await readFile(settings, "utf8")).mcpServers, + settings, + directory, + 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) + + // Restart must clear the same expanded identity that connection setup uses. + it.each( + [false, true].flatMap((variableUrl) => + [false, true].map((variableClient) => ({ variableUrl, variableClient })), + ), + )( + "clears restart credentials with URL variable=$variableUrl and client variable=$variableClient", + async ({ variableUrl, variableClient }) => { + vi.stubEnv("MCP_RESTART_PATH", "mcp") + vi.stubEnv("MCP_RESTART_CLIENT", "registered-client") + try { + const config = { + type: "streamable-http", + url: variableUrl ? "https://example.com/${env:MCP_RESTART_PATH}" : "https://example.com/mcp", + oauth: { clientId: variableClient ? "${env:MCP_RESTART_CLIENT}" : "registered-client" }, + } + row().config = JSON.stringify(config) + row().disabled = false + const key = getMcpOAuthStorageKey("https://example.com/mcp", "registered-client") + const credentials = new Map([[key, "bad-token"]]) + const storage = { + deleteOAuthData: vi.fn(async (url: string, clientId?: string) => { + credentials.delete(getMcpOAuthStorageKey(url, clientId)) + }), + } satisfies Pick + // Restart only calls deleteOAuthData; mocked connection setup does not use other storage methods. + harness.hub["secretStorage"] = storage as unknown as SecretStorageService + const connect = vi.fn(harness.hub["connectToServer"]).mockResolvedValue(undefined) + harness.hub["connectToServer"] = connect + + await harness.hub.restartConnection("local", "global") + + expect(storage.deleteOAuthData).toHaveBeenCalledExactlyOnceWith( + "https://example.com/mcp", + "registered-client", + ) + expect(credentials.has(key)).toBe(false) + expect(connect).toHaveBeenCalledWith("local", expect.objectContaining(config), "global") + } finally { + vi.unstubAllEnvs() + } + }, + ) + + 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({}) + }) +}) + +// Invariants: McpSettingsWriters.KeepToggle, NoPhantom, CurrentTimeout, AppliedEdit. +describe("MCP settings writer properties", () => { + it.each(["delete", "tool"])("keeps a toggle that commits before the %s writer lock", async (writer) => { + const harness = await startHub() + try { + const before = await harness.saved() + before.local.disabled = false + before.local.customField = "keep" + before.sibling = { command: "node", disabled: true } + await writeFile(harness.settings, JSON.stringify({ mcpServers: before })) + await harness.hub.updateServerConnections(before, "global") + const write = vi.mocked(safeWriteJson).getMockImplementation()! + vi.mocked(safeWriteJson).mockImplementationOnce(async (...args) => { + const latest = await harness.saved() + latest.local.disabled = true + await writeFile(harness.settings, JSON.stringify({ mcpServers: latest })) + await write(...args) + }) + if (writer === "delete") await harness.hub.deleteServer("sibling", "global") + else await harness.hub.toggleToolAlwaysAllow("local", "global", "example", true) + expect((await harness.saved()).local).toMatchObject({ disabled: true, customField: "keep" }) + } finally { + await harness.close() + } + }) + + it.each([true, false])("does not create a missing server for tool add=%s", async (add) => { + const harness = await startHub() + try { + await writeFile(harness.settings, JSON.stringify({ mcpServers: {} })) + await expect(harness.hub.toggleToolAlwaysAllow("local", "global", "example", add)).rejects.toThrow( + "not found in config", + ) + expect(await harness.saved()).toEqual({}) + } finally { + await harness.close() + } + }) + + it.each([30, 120])("updates the runtime timeout to %s", async (timeout) => { + const harness = await startHub() + try { + await harness.hub.updateServerTimeout("local", timeout, "global") + expect(JSON.parse(harness.hub.connections[0].server.config).timeout).toBe(timeout) + expect((await harness.saved()).local.timeout).toBe(timeout) + } finally { + await harness.close() + } + }) + + it.each(["alwaysAllow", "disabledTools"])("merges concurrent %s edits from the locked value", async (listName) => { + const harness = await startHub() + try { + const edit = (tool: string) => + listName === "alwaysAllow" + ? harness.hub.toggleToolAlwaysAllow("local", "global", tool, true) + : harness.hub.toggleToolEnabledForPrompt("local", "global", tool, false) + await Promise.all([edit("first"), edit("second")]) + expect((await harness.saved()).local[listName]).toEqual(expect.arrayContaining(["first", "second"])) + expect(JSON.parse(harness.hub.connections[0].server.config)[listName]).toEqual( + expect.arrayContaining(["first", "second"]), + ) + } finally { + await harness.close() + } + }) + + it("checks its own completed settings write without reconnecting", async () => { + const harness = await startHub() + try { + const config = await harness.saved() + config.local.disabled = false + config.local.env = { MCP_REVIEW: "${env:PATH}" } + config.local.watchPaths = [join(harness.settings, "..", "watched")] + await writeFile(harness.settings, JSON.stringify({ mcpServers: config })) + await harness.hub.updateServerConnections(config, "global") + await harness.hub.updateServerTimeout("local", 120, "global") + const connection = harness.hub.connections[0] + const watchers = [...harness.hub["fileWatchers"].values()].flat() + expect(watchers.length).toBeGreaterThan(0) + const update = vi.spyOn(harness.hub, "updateServerConnections") + await harness.hub["handleConfigFileChange"](harness.settings, "global") + expect(update).toHaveBeenCalled() + expect(harness.hub.connections[0]).toBe(connection) + expect([...harness.hub["fileWatchers"].values()].flat()).toEqual(watchers) + expect(JSON.parse(harness.hub.connections[0].server.config).timeout).toBe(120) + } finally { + await harness.close() + } + }) + + // Invariants: AppliedEdit and RecreatedVisible. A local write must not hide disk content. + it.each(["merged", "recreated", "read-error"])("applies an external edit after %s", async (event) => { + const harness = await startHub() + try { + const config = await harness.saved() + config.local.alwaysAllow = ["external"] + config.sibling = { command: process.execPath, disabled: true } + await writeFile(harness.settings, JSON.stringify({ custom: true, mcpServers: config })) + await harness.hub.updateServerTimeout("local", 120, "global") + const content = await readFile(harness.settings, "utf8") + if (event !== "merged") { + await rm(harness.settings) + if (event === "read-error") await harness.hub["handleConfigFileChange"](harness.settings, "global") + else await harness.hub.deleteConnection("local", "global") + await writeFile(harness.settings, content) + } + await harness.hub["handleConfigFileChange"](harness.settings, "global") + expect(harness.hub.connections.map((connection) => connection.server.name)).toEqual( + expect.arrayContaining(["local", "sibling"]), + ) + expect( + JSON.parse( + harness.hub.connections.find((connection) => connection.server.name === "local")!.server.config, + ), + ).toMatchObject({ + alwaysAllow: ["external"], + timeout: 120, + }) + expect(JSON.parse(await readFile(harness.settings, "utf8"))).toHaveProperty("custom", true) + } finally { + await harness.close() + } + }) + + it.each(["disable", "revoke"])("updates the replacement row after queued %s", async (action) => { + const harness = await startHub() + let resume = () => {} + const held = new Promise((resolve) => { + resume = resolve + }) + let watching: Promise | undefined + let acting: Promise | undefined + try { + const config = await harness.saved() + config.local.disabled = false + config.local.alwaysAllow = ["example"] + await writeFile(harness.settings, JSON.stringify({ mcpServers: config })) + const original = harness.hub.updateServerConnections.bind(harness.hub) + const apply = vi.spyOn(harness.hub, "updateServerConnections").mockImplementationOnce(async (...args) => { + await held + await original(...args) + if (action === "revoke") { + const current = harness.hub.connections[0] + current.server.tools = [{ name: "example", alwaysAllow: true }] + if (current.type !== "connected") throw new Error("Expected a transport row") + vi.spyOn(current.client, "request").mockResolvedValue({ + tools: [{ name: "example", inputSchema: { type: "object" } }], + }) + } + }) + const old = harness.hub.connections[0] + watching = harness.hub["handleConfigFileChange"](harness.settings, "global") + await vi.waitFor(() => expect(apply).toHaveBeenCalled()) + const queuedApply = harness.hub["configOperations"].get("global") + acting = + action === "disable" + ? harness.hub.toggleServerDisabled("local", true, "global") + : harness.hub.toggleToolAlwaysAllow("local", "global", "example", false) + await vi.waitFor(() => expect(harness.hub["configOperations"].get("global")).not.toBe(queuedApply)) + resume() + await Promise.all([watching, acting]) + expect(harness.hub.connections[0]).not.toBe(old) + if (action === "disable") expect(harness.hub.connections[0].server.disabled).toBe(true) + else + expect(harness.hub.connections[0].server.tools).toEqual([ + expect.objectContaining({ name: "example", alwaysAllow: false }), + ]) + } finally { + resume() + await Promise.allSettled([watching, acting]) + await harness.close() + } + }) + + it("keeps unknown document keys when deleting a server", async () => { + const harness = await startHub() + try { + await writeFile( + harness.settings, + JSON.stringify({ custom: { keep: true }, mcpServers: await harness.saved() }), + ) + await harness.hub.deleteServer("local", "global") + expect(JSON.parse(await readFile(harness.settings, "utf8"))).toEqual({ + custom: { keep: true }, + mcpServers: {}, + }) + } finally { + await harness.close() + } + }) + + it.each(["global", "project"] as const)( + "recovers the %s queue and retains the newest operation", + async (source) => { + const harness = await startHub() + let resume = () => {} + const held = new Promise((resolve) => { + resume = resolve + }) + try { + const events: number[] = [] + const first = harness.hub["withConfigOperation"](source, async () => { + throw new Error("first failed") + }) + const rejected = expect(first).rejects.toThrow("first failed") + const second = harness.hub["withConfigOperation"](source, async () => { + events.push(2) + await held + }) + const third = harness.hub["withConfigOperation"](source, async () => { + events.push(3) + }) + await rejected + await vi.waitFor(() => expect(events).toEqual([2])) + expect(harness.hub["configOperations"].has(source)).toBe(true) + await harness.hub["withConfigOperation"](source === "global" ? "project" : "global", async () => { + events.push(0) + }) + expect(events).toEqual([2, 0]) + resume() + await Promise.all([second, third]) + expect(events).toEqual([2, 0, 3]) + expect(harness.hub["configOperations"].has(source)).toBe(false) + } finally { + resume() + await harness.close() + } + }, + ) + + it + .skipIf(process.platform === "win32") + .each( + ["timeout", "disable", "tool", "delete"].flatMap((writer) => + [true, false].map((inside) => ({ writer, inside })), + ), + )("checks a project $writer inside=$inside", async ({ writer, inside }) => { + const harness = await startHub() + const outside = await mkdtemp(join(tmpdir(), "mcp-outside-")) + try { + const target = join(inside ? harness.directory : outside, "mcp.json") + const content = JSON.stringify({ mcpServers: await harness.saved() }) + await writeFile(target, content) + await mkdir(join(harness.directory, ".roo")) + await symlink(target, join(harness.directory, ".roo", "mcp.json")) + await harness.hub.updateServerConnections(await harness.saved(), "project") + const operation = + writer === "timeout" + ? harness.hub.updateServerTimeout("local", 120, "project") + : writer === "disable" + ? harness.hub.toggleServerDisabled("local", true, "project") + : writer === "tool" + ? harness.hub.toggleToolAlwaysAllow("local", "project", "example", false) + : harness.hub.deleteServer("local", "project") + if (!inside) { + await expect(operation).rejects.toThrow("outside the workspace") + expect(await readFile(target, "utf8")).toBe(content) + } else { + await operation + const saved = JSON.parse(await readFile(target, "utf8")).mcpServers + if (writer === "timeout") expect(saved.local.timeout).toBe(120) + else if (writer === "disable") expect(saved.local.disabled).toBe(true) + else if (writer === "tool") expect(saved.local.alwaysAllow).not.toContain("example") + else expect(saved).not.toHaveProperty("local") + } + } finally { + await harness.close() + await rm(outside, { recursive: true, force: true }) + } + }) + + it.each([null, [], { mcpServers: [] }, { mcpServers: { local: null } }])( + "keeps invalid delete input %j", + async (input) => { + const harness = await startHub() + try { + const content = JSON.stringify(input) + await writeFile(harness.settings, content) + await expect(harness.hub.deleteServer("local", "global")).rejects.toThrow("Invalid config structure") + expect(await readFile(harness.settings, "utf8")).toBe(content) + } finally { + await harness.close() + } + }, + ) + + it("keeps global watchers when removing a project server with the same name", async () => { + const harness = await startHub() + try { + const config = await harness.saved() + config.local.disabled = false + config.local.watchPaths = [join(harness.directory, "watched")] + await harness.hub.updateServerConnections(config, "global") + const globalWatchers = [...harness.hub["fileWatchers"].values()].flat() + expect(globalWatchers.length).toBeGreaterThan(0) + await harness.hub.updateServerConnections(config, "project") + await harness.hub.deleteConnection("local", "project") + expect([...harness.hub["fileWatchers"].values()].flat()).toEqual(globalWatchers) + } finally { + await harness.close() + } + }) + + // Accepted contract: a same-source action waits until watcher connection setup finishes. + it.each(["disable", "delete"])("waits for a slow sibling connection before %s", async (action) => { + const harness = await startHub() + let resume = () => {} + const held = new Promise((resolve) => { + resume = resolve + }) + let watching: Promise | undefined + let acting: Promise | undefined + try { + const config = await harness.saved() + config.local.disabled = false + const row = harness.hub.connections[0].server + row.disabled = false + row.config = JSON.stringify(config.local) + const connect = harness.hub["connectToServer"].bind(harness.hub) + let started = false + harness.hub["connectToServer"] = vi.fn(async (name, ...args) => { + if (name !== "slow") return connect(name, ...args) + started = true + await held + }) + await writeFile( + harness.settings, + JSON.stringify({ + mcpServers: { + slow: { command: process.execPath, args: ["-e", ""] }, + ...config, + }, + }), + ) + watching = harness.hub["handleConfigFileChange"](harness.settings, "global") + await vi.waitFor(() => expect(started).toBe(true)) + let completed = false + acting = ( + action === "disable" + ? harness.hub.toggleServerDisabled("local", true, "global") + : harness.hub.deleteServer("local", "global") + ).then(() => { + completed = true + }) + await new Promise((resolve) => setTimeout(resolve, 50)) + const completedWhileConnecting = completed + resume() + await Promise.all([watching, acting]) + expect(completedWhileConnecting).toBe(false) + if (action === "disable") expect((await harness.saved()).local.disabled).toBe(true) + else expect(await harness.saved()).not.toHaveProperty("local") + } finally { + resume() + await Promise.allSettled([watching, acting]) + await harness.close() + } + }) + + // Invariant: OrderedApply. A write waits for the older watcher apply to finish. + it.each(["timeout", "delete"])("keeps a newer %s after an in-flight watcher apply", async (writer) => { + const harness = await startHub() + try { + const original = harness.hub.updateServerConnections.bind(harness.hub) + let release = () => {} + const held = new Promise((resolve) => { + release = resolve + }) + const apply = vi.spyOn(harness.hub, "updateServerConnections").mockImplementationOnce(async (...args) => { + await held + await original(...args) + }) + const watching = harness.hub["handleConfigFileChange"](harness.settings, "global") + await vi.waitFor(() => expect(apply).toHaveBeenCalled()) + let completed = false + const operation = + writer === "timeout" + ? harness.hub.updateServerTimeout("local", 120, "global") + : harness.hub.deleteServer("local", "global") + const writing = operation.then(() => { + completed = true + }) + await new Promise((resolve) => setTimeout(resolve, 50)) + const finishedBeforeApply = completed + release() + await Promise.all([watching, writing]) + expect(finishedBeforeApply).toBe(false) + if (writer === "timeout") { + expect(JSON.parse(harness.hub.connections[0].server.config).timeout).toBe(120) + expect((await harness.saved()).local.timeout).toBe(120) + } else { + expect(harness.hub.connections).toHaveLength(0) + expect(await harness.saved()).toEqual({}) + } + } finally { + await harness.close() + } + }) + + it.each(["missing", "malformed"].flatMap((input) => ["update", "delete"].map((writer) => ({ input, writer }))))( + "handles $input settings during $writer without changing the row", + async ({ input, writer }) => { + const harness = await startHub() + try { + const before = harness.hub.connections[0].server.config + if (input === "missing") await rm(harness.settings) + else await writeFile(harness.settings, "{") + const operation = + writer === "update" + ? harness.hub.updateServerTimeout("local", 120, "global") + : harness.hub.deleteServer("local", "global") + if (input === "missing" && writer === "delete") { + await operation + expect(await harness.saved()).toEqual({}) + } else await expect(operation).rejects.toThrow() + expect(harness.hub.connections[0].server.config).toBe(before) + if (input === "malformed") expect(await readFile(harness.settings, "utf8")).toBe("{") + } finally { + await harness.close() + } + }, + ) + + it("does not rewrite settings when a server is already absent", async () => { + const harness = await startHub() + try { + const content = '{ "custom": true, "mcpServers": {} }' + await writeFile(harness.settings, content) + await harness.hub.deleteServer("local", "global") + expect(await readFile(harness.settings, "utf8")).toBe(content) + } finally { + await harness.close() + } + }) + + it("processes an external edit immediately after a settings write", async () => { + const harness = await startHub() + try { + await harness.hub.updateServerTimeout("local", 120, "global") + const update = vi.spyOn(harness.hub, "updateServerConnections") + const config = await harness.saved() + config.local.timeout = 90 + await writeFile(harness.settings, JSON.stringify({ mcpServers: config })) + harness.hub["debounceConfigChange"](harness.settings, "global") + await vi.waitFor( + () => + expect(update).toHaveBeenCalledWith( + expect.objectContaining({ local: expect.objectContaining({ timeout: 90 }) }), + "global", + ), + { timeout: 2000 }, + ) + } finally { + await harness.close() + } + }) +}) + +// McpConnectionOwnership keeps separate removal revisions for each name and source. +it.each(["local", "local:project", "local:global"])("keeps removal sources separate for %s", async (name) => { + const harness = await startHub() + try { + await harness.hub.deleteConnection(name, "global") + const globalRevision = harness.hub["connectionRemovals"].get(`${name}:global`) + await harness.hub.deleteConnection(name, "project") + expect(harness.hub["connectionRemovals"].get(`${name}:global`)).toBe(globalRevision) + expect(harness.hub["connectionRemovals"].get(`${name}:project`)).toBe(1) + } finally { + await harness.close() + } +}) + +// Each refresh must use both source queues and replace every row exactly once. +it("refreshes both files with new rows after pending source work", async () => { + const harness = await startHub() + try { + const project = join(harness.directory, ".roo", "mcp.json") + await mkdir(join(harness.directory, ".roo")) + await writeFile(project, JSON.stringify({ mcpServers: { local: { command: "project", disabled: true } } })) + await harness.hub["updateProjectMcpServers"]() + const old = [...harness.hub.connections] + expect(old).toHaveLength(2) + let release!: () => void + const gate = new Promise((resolve) => { + release = resolve + }) + const pending = harness.hub["withConfigOperation"]("global", () => gate) + const refresh = harness.hub.refreshAllConnections() + await Promise.resolve() + expect(harness.hub.connections).toEqual(old) + release() + await pending + await refresh + expect(harness.hub.connections).toHaveLength(2) + expect(harness.hub.connections.map((entry) => entry.server.source).sort()).toEqual(["global", "project"]) + for (const entry of harness.hub.connections) expect(old).not.toContain(entry) + } finally { + await harness.close() + } +}) + +it("reloads project settings from the file", async () => { + const harness = await startHub() + try { + await mkdir(join(harness.directory, ".roo")) + const project = join(harness.directory, ".roo", "mcp.json") + for (const command of ["first", "second"]) { + await writeFile(project, JSON.stringify({ mcpServers: { local: { command, disabled: true } } })) + await harness.hub["updateProjectMcpServers"]() + const rows = harness.hub.connections.filter((entry) => entry.server.source === "project") + expect(rows).toHaveLength(1) + expect(JSON.parse(rows[0].server.config).command).toBe(command) + } + } finally { + await harness.close() + } +}) + +it("queues project deletion behind a pending apply", async () => { + const harness = await startHub() + try { + await mkdir(join(harness.directory, ".roo")) + const project = join(harness.directory, ".roo", "mcp.json") + await writeFile(project, JSON.stringify({ mcpServers: { local: { command: "project", disabled: true } } })) + await harness.hub["updateProjectMcpServers"]() + vi.stubEnv("NODE_ENV", "development") + Object.assign(vscode.workspace, { + workspaceFolders: [{ uri: { fsPath: harness.directory }, name: "test", index: 0 }], + }) + let deleted: (() => Promise) | undefined + vi.mocked(vscode.workspace.createFileSystemWatcher).mockReturnValueOnce({ + ignoreCreateEvents: false, + ignoreChangeEvents: false, + ignoreDeleteEvents: false, + onDidChange: vi.fn(), + onDidCreate: vi.fn(), + onDidDelete: vi.fn((listener) => { + deleted = listener as () => Promise + return { dispose: vi.fn() } + }), + dispose: vi.fn(), + }) + await harness.hub["watchProjectMcpFile"]() + let release!: () => void + const gate = new Promise((resolve) => { + release = resolve + }) + const pending = harness.hub["withConfigOperation"]("project", () => gate) + await rm(project) + const deletion = deleted!() + await Promise.resolve() + expect(harness.hub.connections.some((entry) => entry.server.source === "project")).toBe(true) + release() + await pending + await deletion + expect(harness.hub.connections.map((entry) => entry.server.source)).toEqual(["global"]) + } finally { + vi.unstubAllEnvs() + Object.assign(vscode.workspace, { workspaceFolders: [] }) + vi.restoreAllMocks() + await harness.close() + } +}) + +// Startup reads an old file while a watcher receives a newer empty file. +it.each(["global", "project"] as const)("applies an edit after the first %s load finishes", async (source) => { + const original = McpHub.prototype.updateServerConnections + let release!: () => void + const gate = new Promise((resolve) => { + release = resolve + }) + let held = false + const update = vi.spyOn(McpHub.prototype, "updateServerConnections").mockImplementation(async function ( + this: McpHub, + ...args: Parameters + ) { + const [, currentSource] = args + if (currentSource === source && !held) { + held = true + await gate + } + await original.call(this, ...args) + }) + let harness: Awaited> | undefined + try { + harness = await startHub(async (hub, settings) => { + await vi.waitFor(() => expect(held).toBe(true)) + await writeFile(settings, JSON.stringify({ mcpServers: {} })) + const edit = hub["handleConfigFileChange"](settings, source) + // If startup has no queue, the newer apply finishes before the old load. + await new Promise((resolve) => setTimeout(resolve, 30)) + release() + await edit + }, source) + expect(harness.hub.connections).toEqual([]) + } finally { + release() + update.mockRestore() + await harness?.close() + } +}) + +// A project reload must wait for earlier work in the same source queue. +it("queues project reload behind pending source work", async () => { + const harness = await startHub() + let release!: () => void + const gate = new Promise((resolve) => { + release = resolve + }) + try { + await mkdir(join(harness.directory, ".roo")) + const project = join(harness.directory, ".roo", "mcp.json") + await writeFile(project, JSON.stringify({ mcpServers: { local: { command: "project", disabled: true } } })) + // Resolve the location without I/O so the test can observe queue entry after one microtask. + harness.hub["getProjectMcpPath"] = async () => project + const apply = harness.hub["applyConfigFileChange"].bind(harness.hub) + let applied = false + harness.hub["applyConfigFileChange"] = async (...args) => { + applied = true + await apply(...args) + } + const pending = harness.hub["withConfigOperation"]("project", () => gate) + const reload = harness.hub["updateProjectMcpServers"]() + await Promise.resolve() + expect(applied).toBe(false) + release() + await pending + await reload + expect(applied).toBe(true) + expect(harness.hub.connections.filter((entry) => entry.server.source === "project")).toHaveLength(1) + } finally { + release() + await harness.close() + } +}) diff --git a/src/services/mcp/constants.ts b/src/services/mcp/constants.ts index 8107ee4a29..e662a8bc1d 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 diff --git a/src/services/mcp/utils/__tests__/callbackServer.listener.spec.ts b/src/services/mcp/utils/__tests__/callbackServer.listener.spec.ts index 119beb6140..442c79678c 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/__tests__/oauth.spec.ts b/src/services/mcp/utils/__tests__/oauth.spec.ts index 7f422410f5..70e87049bd 100644 --- a/src/services/mcp/utils/__tests__/oauth.spec.ts +++ b/src/services/mcp/utils/__tests__/oauth.spec.ts @@ -23,6 +23,8 @@ const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) describe("fetchOAuthAuthServerMetadata", () => { beforeEach(() => { vi.clearAllMocks() + mockFetch.mockReset() + vi.spyOn(console, "warn").mockImplementation(() => {}) }) afterEach(() => { @@ -33,6 +35,46 @@ describe("fetchOAuthAuthServerMetadata", () => { global.fetch = originalFetch }) + // Invariant: McpOAuthRefreshToken.BoundEndpoint. Discovery cannot claim another issuer. + it.each([ + ["https://auth.example.com", "https://other.example.com", false], + ["https://auth.example.com/realm/", "https://auth.example.com/realm", true], + ["https://auth.example.com/realm", "https://auth.example.com/realm/", true], + ["https://auth.example.com/realm", undefined, false], + ["https://auth.example.com/realm", "https://auth.example.com/other", false], + ])("binds discovery %s to issuer %s", async (advertised, issuer, accepted) => { + vi.mocked(discoverOAuthProtectedResourceMetadata).mockResolvedValueOnce({ + resource: "https://example.com/mcp", + authorization_servers: [advertised], + }) + mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({ issuer }) }) + const result = await fetchOAuthAuthServerMetadata("https://example.com/mcp") + expect(result !== null).toBe(accepted) + if (!accepted) + expect(console.warn).toHaveBeenCalledWith( + "[MCP OAuth] Discovery issuer does not match the requested issuer", + ) + }) + + it.each([ + ["https://auth.example.com/realm", true], + ["http://auth.example.com/realm", false], + ["http://127.0.0.1:8080/realm", true], + ["http://[::1]:8080/realm", true], + ["http://localhost:8080/realm", true], + ["http://localhost.evil.example/realm", false], + ["https://user:secret@auth.example.com/realm", false], + ["file:///tmp/realm", false], + ])("checks issuer transport %s", async (issuer, accepted) => { + vi.mocked(discoverOAuthProtectedResourceMetadata).mockResolvedValueOnce({ + resource: "https://example.com/mcp", + authorization_servers: [issuer], + }) + mockFetch.mockResolvedValueOnce(new Response(JSON.stringify({ issuer }))) + expect((await fetchOAuthAuthServerMetadata("https://example.com/mcp")) !== null).toBe(accepted) + expect(mockFetch).toHaveBeenCalledTimes(accepted ? 1 : 0) + }) + it("returns null when resource metadata has no authorization_servers", async () => { ;(discoverOAuthProtectedResourceMetadata as any).mockResolvedValue({ resource: "https://example.com/", diff --git a/src/services/mcp/utils/callbackServer.ts b/src/services/mcp/utils/callbackServer.ts index 2ef72a3159..f437e70579 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() + }) }) } diff --git a/src/services/mcp/utils/oauth.ts b/src/services/mcp/utils/oauth.ts index 3feb9290e4..f3e353de5e 100644 --- a/src/services/mcp/utils/oauth.ts +++ b/src/services/mcp/utils/oauth.ts @@ -70,6 +70,12 @@ export async function fetchOAuthAuthServerMetadata(serverUrl: string): Promise + const authServerMeta = (await response.json()) as Record + if ( + typeof authServerMeta.issuer !== "string" || + authServerMeta.issuer.replace(/\/+$/, "") !== authServers[0].replace(/\/+$/, "") + ) { + console.warn("[MCP OAuth] Discovery issuer does not match the requested issuer") + return null + } return { authServerMeta, resourceIndicator } } catch { return null diff --git a/src/utils/__tests__/fileLock.test.ts b/src/utils/__tests__/fileLock.test.ts index 92637fe7a0..0ff43a47d6 100644 --- a/src/utils/__tests__/fileLock.test.ts +++ b/src/utils/__tests__/fileLock.test.ts @@ -5,6 +5,7 @@ vi.mock("proper-lockfile", () => ({ lock: vi.fn() })) describe("file lock protocol", () => { beforeEach(() => vi.clearAllMocks()) + afterEach(() => vi.restoreAllMocks()) it("allows recovery to outwait staleness with bounded constant retries", async () => { vi.mocked(lockfile.lock).mockResolvedValue(async () => {}) @@ -31,4 +32,63 @@ describe("file lock protocol", () => { ).rejects.toBe(error) expect(release).toHaveBeenCalledOnce() }) + // Contract: the operation outcome survives cleanup, and one acquired lock is released once. + it.each( + [false, true].flatMap((operationFails) => + [false, true].map((releaseFails) => ({ operationFails, releaseFails })), + ), + )( + "preserves the outcome, operation fails $operationFails, release fails $releaseFails", + async ({ operationFails, releaseFails }) => { + const operationError = new Error("operation failed") + const releaseError = new Error("release failed") + const report = vi.spyOn(console, "error").mockImplementation(() => {}) + const release = vi.fn(async () => { + if (releaseFails) throw releaseError + }) + vi.mocked(lockfile.lock).mockResolvedValue(release) + const pending = withFileLock("history.json", async (lockedPath) => { + expect(lockedPath).toBe(vi.mocked(lockfile.lock).mock.calls[0][0]) + if (operationFails) throw operationError + return 42 + }) + if (operationFails) await expect(pending).rejects.toBe(operationError) + else await expect(pending).resolves.toBe(42) + expect(release).toHaveBeenCalledOnce() + expect(report).toHaveBeenCalledTimes(releaseFails ? 1 : 0) + if (releaseFails) + expect(report).toHaveBeenCalledWith(expect.stringContaining("Failed to release lock"), releaseError) + }, + ) + + it("does not run an operation when lock acquisition fails", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}) + const error = new Error("lock failed") + vi.mocked(lockfile.lock).mockRejectedValueOnce(error) + const operation = vi.fn(async () => 42) + await expect(withFileLock("history.json", operation)).rejects.toBe(error) + expect(operation).not.toHaveBeenCalled() + }) + it("holds the lock while the callback is pending", async () => { + const release = vi.fn(async () => {}) + vi.mocked(lockfile.lock).mockResolvedValue(release) + let resume!: () => void + const held = new Promise((resolve) => { + resume = resolve + }) + const operation = vi.fn(async () => { + await held + return 42 + }) + const pending = withFileLock("history.json", operation) + try { + await vi.waitFor(() => expect(operation).toHaveBeenCalledOnce()) + expect(release).not.toHaveBeenCalled() + } finally { + resume() + await pending + } + expect(release).toHaveBeenCalledOnce() + await expect(pending).resolves.toBe(42) + }) }) diff --git a/src/utils/__tests__/jsonFileLockIdentity.test.ts b/src/utils/__tests__/jsonFileLockIdentity.test.ts new file mode 100644 index 0000000000..66645adb4b --- /dev/null +++ b/src/utils/__tests__/jsonFileLockIdentity.test.ts @@ -0,0 +1,127 @@ +import * as fs from "fs/promises" +import { tmpdir } from "os" +import { join } from "path" + +import { safeWriteJson } from "../safeWriteJson" +import { deleteJsonFile, recoverMissingJsonFile } from "../jsonFileRecovery" + +vi.mock("fs/promises", async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, rename: vi.fn(actual.rename), realpath: vi.fn(actual.realpath) } +}) + +function deferred() { + let resolve!: () => void + const promise = new Promise((done) => { + resolve = done + }) + return { promise, resolve } +} + +// Invariant: JsonFileLockIdentity.SameFileSerialized. All aliases share the writer's lock. +describe("JSON file lock identity", () => { + const linkKinds = ["directory", "file"].filter((link) => link !== "file" || process.platform !== "win32") + afterEach(() => vi.restoreAllMocks()) + + it.skipIf(process.platform === "win32")("resolves a relative dangling file link from its real parent", async () => { + const directory = await fs.mkdtemp(join(tmpdir(), "json-relative-link-")) + try { + await fs.mkdir(join(directory, "real", "nested"), { recursive: true }) + await fs.symlink(join(directory, "real", "nested"), join(directory, "alias"), "junction") + await fs.symlink("../target.json", join(directory, "real", "nested", "link.json")) + await safeWriteJson(join(directory, "alias", "link.json"), { saved: true }) + expect(JSON.parse(await fs.readFile(join(directory, "real", "target.json"), "utf8"))).toEqual({ + saved: true, + }) + await expect(fs.stat(join(directory, "target.json"))).rejects.toMatchObject({ code: "ENOENT" }) + } finally { + await fs.rm(directory, { recursive: true, force: true }) + } + }) + + it.each(linkKinds)("restores a missing target through a %s symlink", async (link) => { + const directory = await fs.mkdtemp(join(tmpdir(), "json-lock-recovery-")) + try { + const realDirectory = join(directory, "real") + await fs.mkdir(realDirectory) + const target = join(realDirectory, "target.json") + const alias = + link === "directory" ? join(directory, "alias", "target.json") : join(realDirectory, "alias.json") + if (link === "directory") await fs.symlink(realDirectory, join(directory, "alias"), "junction") + else await fs.symlink("target.json", alias) + await fs.writeFile(join(realDirectory, ".target.json.bak_1_saved.tmp"), '{"committed":true}') + await expect(recoverMissingJsonFile(alias)).resolves.toBe(true) + expect(JSON.parse(await fs.readFile(target, "utf8"))).toEqual({ committed: true }) + if (link === "file") expect((await fs.lstat(alias)).isSymbolicLink()).toBe(true) + } finally { + await fs.rm(directory, { recursive: true, force: true }) + } + }) + + it.each( + ["write", "delete", "recover"].flatMap((operation) => ["EACCES", "EIO"].map((code) => ({ operation, code }))), + )("does not hide a path resolution error during $operation: $code", async ({ operation, code }) => { + const error = Object.assign(new Error("resolution failed"), { code }) + vi.mocked(fs.realpath).mockRejectedValueOnce(error) + const pending = + operation === "write" + ? safeWriteJson("unreadable.json", {}) + : operation === "delete" + ? deleteJsonFile("unreadable.json") + : recoverMissingJsonFile("unreadable.json") + await expect(pending).rejects.toBe(error) + }) + + it.each( + linkKinds.flatMap((link) => + [true, false].flatMap((exists) => ["delete", "recover"].map((operation) => ({ link, exists, operation }))), + ), + )("serializes $operation through a $link symlink, target exists $exists", async ({ link, exists, operation }) => { + const directory = await fs.mkdtemp(join(tmpdir(), "json-lock-identity-")) + const realDirectory = join(directory, "real") + await fs.mkdir(realDirectory) + const target = join(realDirectory, "target.json") + const alias = link === "directory" ? join(directory, "alias", "target.json") : join(realDirectory, "alias.json") + const entered = deferred() + const resume = deferred() + let writing: Promise | undefined + let deleting: Promise | undefined + try { + if (exists) await fs.writeFile(target, '{"before":true}') + if (link === "directory") await fs.symlink(realDirectory, join(directory, "alias"), "junction") + else await fs.symlink("target.json", alias) + const actual = await vi.importActual("fs/promises") + vi.mocked(fs.rename).mockImplementationOnce(async (from, to) => { + entered.resolve() + await resume.promise + await actual.rename(from, to) + }) + writing = safeWriteJson(alias, { saved: true }) + await entered.promise + if (operation === "recover") { + await expect(recoverMissingJsonFile(alias, { waitForStaleLock: false })).rejects.toMatchObject({ + code: "ELOCKED", + }) + resume.resolve() + await writing + expect(JSON.parse(await fs.readFile(target, "utf8"))).toEqual({ saved: true }) + } else { + let completed = false + deleting = deleteJsonFile(alias).then(() => { + completed = true + }) + await new Promise((resolve) => setTimeout(resolve, 50)) + const deletedBeforeWrite = completed + resume.resolve() + await Promise.all([writing, deleting]) + expect(deletedBeforeWrite).toBe(false) + await expect(fs.access(target)).rejects.toMatchObject({ code: "ENOENT" }) + } + if (link === "file") expect((await fs.lstat(alias)).isSymbolicLink()).toBe(true) + } finally { + resume.resolve() + await Promise.allSettled([writing, deleting]) + await fs.rm(directory, { recursive: true, force: true }) + } + }) +}) diff --git a/src/utils/__tests__/safeWriteJson.interruption.test.ts b/src/utils/__tests__/safeWriteJson.interruption.test.ts index c9c5993f84..390c9b4492 100644 --- a/src/utils/__tests__/safeWriteJson.interruption.test.ts +++ b/src/utils/__tests__/safeWriteJson.interruption.test.ts @@ -105,7 +105,8 @@ describe("safeWriteJson subprocess interruption fault injection", () => { let childBundlePath: string beforeEach(async () => { - tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "safe-write-interruption-")) + // The crash hook must compare the same canonical path that the writer uses. + tempDir = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "safe-write-interruption-"))) storageDir = path.join(tempDir, "tasks", "restart-task") childDir = path.join(tempDir, "child") await fs.mkdir(storageDir, { recursive: true }) diff --git a/src/utils/__tests__/safeWriteJson.metadata.test.ts b/src/utils/__tests__/safeWriteJson.metadata.test.ts new file mode 100644 index 0000000000..5a3cb019a1 --- /dev/null +++ b/src/utils/__tests__/safeWriteJson.metadata.test.ts @@ -0,0 +1,102 @@ +import * as fs from "fs/promises" +import { tmpdir } from "os" +import { join } from "path" +import { safeWriteJson, SKIP_JSON_WRITE } from "../safeWriteJson" + +vi.mock("fs/promises", async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, open: vi.fn(actual.open), chmod: vi.fn(actual.chmod) } +}) +afterEach(() => vi.restoreAllMocks()) + +// Invariants: JsonWriteMetadata.KeepMode, KeepLink, and SkipUnchanged. +it + .skipIf(process.platform === "win32") + .each([0o400, 0o600, 0o640, 0o644].flatMap((mode) => [false, true].map((linked) => ({ mode, linked }))))( + "keeps mode $mode with symlink $linked", + async ({ mode, linked }) => { + const directory = await fs.mkdtemp(join(tmpdir(), "json-metadata-")) + try { + const target = join(directory, "target.json") + const link = join(directory, "settings.json") + await fs.writeFile(target, '{"old":true}') + await fs.chmod(target, mode) + if (linked) await fs.symlink("target.json", link) + await safeWriteJson(linked ? link : target, { saved: true }) + if (linked) expect((await fs.lstat(link)).isSymbolicLink()).toBe(true) + expect((await fs.stat(target)).mode & 0o777).toBe(mode) + expect(JSON.parse(await fs.readFile(target, "utf8"))).toEqual({ saved: true }) + } finally { + await fs.rm(directory, { recursive: true, force: true }) + } + }, +) + +it("skips an unchanged merge without replacing the file", async () => { + const directory = await fs.mkdtemp(join(tmpdir(), "json-noop-")) + try { + const target = join(directory, "settings.json") + await fs.writeFile(target, '{ "mcpServers": {} }') + const before = await fs.stat(target) + await safeWriteJson(target, {}, { merge: () => SKIP_JSON_WRITE }) + expect((await fs.stat(target)).ino).toBe(before.ino) + expect(await fs.readFile(target, "utf8")).toBe('{ "mcpServers": {} }') + } finally { + await fs.rm(directory, { recursive: true, force: true }) + } +}) + +// Invariant: a project write cannot follow a link outside the real workspace. +it.skipIf(process.platform === "win32").each([true, false])( + "checks the workspace boundary for an existing target %s", + async (exists) => { + const directory = await fs.mkdtemp(join(tmpdir(), "json-workspace-")) + try { + const workspace = join(directory, "workspace") + await fs.mkdir(workspace) + const outside = exists ? join(directory, "outside.json") : join(directory, "missing", "outside.json") + if (exists) await fs.writeFile(outside, '{"keep":true}') + const linked = join(workspace, "mcp.json") + await fs.symlink(outside, linked) + await expect(safeWriteJson(linked, {}, { allowedRoot: workspace })).rejects.toThrow("outside the workspace") + if (exists) expect(await fs.readFile(outside, "utf8")).toBe('{"keep":true}') + else await expect(fs.stat(join(directory, "missing"))).rejects.toMatchObject({ code: "ENOENT" }) + const inside = join(workspace, "inside.json") + await fs.unlink(linked) + await fs.symlink(inside, linked) + await safeWriteJson(linked, { saved: true }, { allowedRoot: workspace }) + expect(JSON.parse(await fs.readFile(inside, "utf8"))).toEqual({ saved: true }) + } finally { + await fs.rm(directory, { recursive: true, force: true }) + } + }, +) + +it("flushes a private temporary file before restoring a read-only mode", async () => { + const actual = await vi.importActual("fs/promises") + const directory = await fs.mkdtemp(join(tmpdir(), "json-flush-mode-")) + try { + const target = join(directory, "settings.json") + await fs.writeFile(target, "{}") + await actual.chmod(target, 0o400) + const events: string[] = [] + vi.mocked(fs.open).mockImplementation(async (file, flags, mode) => { + const handle = await actual.open(file, flags, mode) + const sync = handle.sync.bind(handle) + vi.spyOn(handle, "sync").mockImplementation(async () => { + events.push("sync") + await sync() + }) + return handle + }) + vi.mocked(fs.chmod).mockImplementation(async (file, mode) => { + if (process.platform !== "win32") expect((await actual.stat(file)).mode & 0o777).toBe(0o600) + events.push("chmod") + await actual.chmod(file, mode) + }) + await safeWriteJson(target, { saved: true }) + expect(events).toEqual(["sync", "chmod"]) + } finally { + await fs.rm(directory, { recursive: true, force: true }) + } +}) diff --git a/src/utils/__tests__/safeWriteJson.test.ts b/src/utils/__tests__/safeWriteJson.test.ts index 30ac500212..73b2008499 100644 --- a/src/utils/__tests__/safeWriteJson.test.ts +++ b/src/utils/__tests__/safeWriteJson.test.ts @@ -82,7 +82,8 @@ describe("safeWriteJson", () => { beforeEach(async () => { // Create a temporary directory for each test - tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "safeWriteJson-test-")) + // Match the writer's canonical paths, including Windows drive and directory aliases. + tempDir = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "safeWriteJson-test-"))) // Create a unique file path for each test currentTestFilePath = path.join(tempDir, "test-file.json") diff --git a/src/utils/fileLock.ts b/src/utils/fileLock.ts index 49807ea154..dc6027a541 100644 --- a/src/utils/fileLock.ts +++ b/src/utils/fileLock.ts @@ -1,4 +1,6 @@ import * as path from "path" +import * as fs from "fs/promises" +import { getErrorCode } from "./errorCode" import { tracePersistenceEvent } from "../core/task-persistence/persistenceTrace" import * as lockfile from "proper-lockfile" @@ -19,6 +21,35 @@ export interface FileLockOptions { immediate?: boolean } +/** Resolves file aliases and missing targets to one lock and operation path. */ +export async function resolveFileLockPath(filePath: string): Promise { + let current = path.resolve(filePath) + const missing: string[] = [] + let links = 0 + for (;;) { + try { + return path.join(await fs.realpath(current), ...[...missing].reverse()) + } catch (error: unknown) { + if (getErrorCode(error) !== "ENOENT") throw error + const target = await fs.readlink(current).catch((linkError: unknown) => { + const code = getErrorCode(linkError) + if (code !== "ENOENT" && code !== "EINVAL") throw linkError + return undefined + }) + if (target !== undefined) { + if (++links > 40) throw Object.assign(new Error("Too many symbolic links"), { code: "ELOOP" }) + // Relative link targets use the physical parent, including before "..". + current = path.resolve(await resolveFileLockPath(path.dirname(current)), target) + continue + } + const parent = path.dirname(current) + if (parent === current) throw error + missing.push(path.basename(current)) + current = parent + } + } +} + /** * Acquire the advisory lock for one file path using the exact protocol * `safeWriteJson` uses, so operations that hold this lock serialize with @@ -27,7 +58,15 @@ export interface FileLockOptions { * while holding it. */ export async function acquireFileLock(filePath: string, options?: FileLockOptions): Promise<() => Promise> { - const absoluteFilePath = path.resolve(filePath) + const absoluteFilePath = await resolveFileLockPath(filePath) + return acquireResolvedFileLock(absoluteFilePath, options) +} + +/** Locks the path already resolved by this module's public entry points. */ +async function acquireResolvedFileLock( + absoluteFilePath: string, + options?: FileLockOptions, +): Promise<() => Promise> { if (options?.waitForStaleLock) tracePersistenceEvent("json-lock-wait", { filePath: absoluteFilePath }) try { return await lockfile.lock(absoluteFilePath, { @@ -72,29 +111,17 @@ export async function withFileLock( operation: (absoluteFilePath: string) => Promise, options?: FileLockOptions, ): Promise { - const absoluteFilePath = path.resolve(filePath) - const releaseLock = await acquireFileLock(absoluteFilePath, options) + const absoluteFilePath = await resolveFileLockPath(filePath) + const releaseLock = await acquireResolvedFileLock(absoluteFilePath, options) - let result: T try { - result = await operation(absoluteFilePath) - } catch (operationError) { - // The operation error is the primary failure. Release without - // reporting a secondary release error over it. + return await operation(absoluteFilePath) + } finally { + // A release failure must not replace the operation's result or error. try { await releaseLock() } catch (releaseError) { console.error(`Failed to release lock for ${absoluteFilePath}:`, releaseError) } - throw operationError - } - - try { - await releaseLock() - } catch (releaseError) { - // The operation already succeeded, so a release failure is only - // logged, matching how `safeWriteJson` handles release failures. - console.error(`Failed to release lock for ${absoluteFilePath}:`, releaseError) } - return result } diff --git a/src/utils/jsonFileRecovery.ts b/src/utils/jsonFileRecovery.ts index 1ad95dbdd8..3bd5a29e5f 100644 --- a/src/utils/jsonFileRecovery.ts +++ b/src/utils/jsonFileRecovery.ts @@ -4,7 +4,7 @@ import * as path from "path" import { getErrorCode } from "./errorCode" import { tracePersistenceEvent } from "../core/task-persistence/persistenceTrace" -import { withFileLock } from "./fileLock" +import { withFileLock, resolveFileLockPath } from "./fileLock" function getTempFilePrefix(absoluteFilePath: string, kind: "new" | "bak"): string { return `.${path.basename(absoluteFilePath)}.${kind}_` @@ -27,7 +27,7 @@ export async function recoverMissingJsonFile( filePath: string, options: { waitForStaleLock?: boolean } = {}, ): Promise { - const absoluteFilePath = path.resolve(filePath) + const absoluteFilePath = await resolveFileLockPath(filePath) let entries: string[] try { entries = await fs.readdir(path.dirname(absoluteFilePath)) diff --git a/src/utils/safeWriteJson.ts b/src/utils/safeWriteJson.ts index e54b8c51d3..665e614ddd 100644 --- a/src/utils/safeWriteJson.ts +++ b/src/utils/safeWriteJson.ts @@ -4,9 +4,12 @@ import * as path from "path" import { JsonStreamStringify } from "json-stream-stringify" import { getErrorCode } from "./errorCode" -import { acquireFileLock } from "./fileLock" +import { acquireFileLock, resolveFileLockPath } from "./fileLock" import { recoverInterruptedReplacement } from "./jsonFileRecovery" +/** A merge callback can return this value to leave the file unchanged. */ +export const SKIP_JSON_WRITE = Symbol("skip-json-write") + /** * Stages reported through the optional `trace` callback. They mark the * replacement-protocol steps that matter when diagnosing interrupted or @@ -22,6 +25,9 @@ export type SafeWriteJsonTrace = (event: { stage: SafeWriteJsonTraceStage; detai * Options for safeWriteJson function */ export interface SafeWriteJsonOptions { + /** Reject resolved targets outside this directory before any write or recovery. */ + allowedRoot?: string + /** * Whether to pretty-print the JSON output with indentation. * When true, uses tab characters for indentation. @@ -72,7 +78,14 @@ function createTempFilePath(absoluteFilePath: string, kind: "new" | "bak"): stri */ async function safeWriteJson(filePath: string, data: unknown, options?: SafeWriteJsonOptions): Promise { - const absoluteFilePath = path.resolve(filePath) + const absoluteFilePath = await resolveFileLockPath(filePath) + if (options?.allowedRoot) { + const root = await fs.realpath(options.allowedRoot) + const relative = path.relative(root, absoluteFilePath) + if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) { + throw new Error("MCP settings path is outside the workspace") + } + } let releaseLock = async () => {} // Initialized to a no-op // For directory creation @@ -130,6 +143,7 @@ async function safeWriteJson(filePath: string, data: unknown, options?: SafeWrit } } data = options.merge(existing, data) + if (data === SKIP_JSON_WRITE) return } // Step 1: Write data to a new temporary file and flush it to storage, @@ -137,8 +151,16 @@ async function safeWriteJson(filePath: string, data: unknown, options?: SafeWrit options?.trace?.({ stage: "write-start" }) actualTempNewFilePath = createTempFilePath(absoluteFilePath, "new") - await _streamDataToFile(actualTempNewFilePath, data, options?.prettyPrint) + const mode = await fs + .stat(absoluteFilePath) + .then((stat) => stat.mode & 0o777) + .catch((error: unknown) => { + if (getErrorCode(error) !== "ENOENT") throw error + return undefined + }) + await _streamDataToFile(actualTempNewFilePath, data, options?.prettyPrint, mode) await _flushFileToDisk(actualTempNewFilePath) + if (mode !== undefined) await fs.chmod(actualTempNewFilePath, mode) // Step 2: Commit the replacement with a single atomic rename. The // committed target stays in place until this rename lands, so a @@ -242,9 +264,12 @@ async function safeWriteJson(filePath: string, data: unknown, options?: SafeWrit * @param prettyPrint Whether to format the JSON with indentation. * @returns Promise */ -async function _streamDataToFile(targetPath: string, data: unknown, prettyPrint = false): Promise { +async function _streamDataToFile(targetPath: string, data: unknown, prettyPrint = false, mode?: number): Promise { // Stream data to avoid high memory usage for large JSON objects. - const fileWriteStream = fsSync.createWriteStream(targetPath, { encoding: "utf8" }) + const fileWriteStream = fsSync.createWriteStream(targetPath, { + encoding: "utf8", + ...(mode === undefined ? {} : { mode: 0o600 }), + }) // JsonStreamStringify traverses the object and streams tokens directly // The 'spaces' parameter adds indentation during streaming, not via a separate pass