Skip to content

Commit 513975e

Browse files
author
Tarek Mahmoud Sayed
committed
Coalesce concurrent cold-start authorizations (modelcontextprotocol#1595)
The post-lock cache re-check only reused a freshly cached token when the challenge carried a token (usedAccessToken is not null). During a cold-start connect the client can issue concurrent requests that all send no token, so each saw a null usedAccessToken, skipped the re-check and ran a full interactive authorization, producing redundant token exchanges (observed in CI as two authorization requests on a single connect). When no token was sent, any valid token now present in the cache was obtained by another caller and is safe to reuse, so drop the null guard. The remaining checks still prevent replaying a rejected token (the cached token must differ from the one that produced the challenge) and still run the step-up flow for 403 insufficient_scope challenges. Copilot-Session: 334e4d21-b783-46ae-8dc6-3c3b5defbe37
1 parent aed4e35 commit 513975e

1 file changed

Lines changed: 6 additions & 5 deletions

File tree

‎src/ModelContextProtocol.Core/Authentication/ClientOAuthProvider.cs‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -280,12 +280,13 @@ private async Task<string> GetAccessTokenAsync(HttpResponseMessage response, boo
280280
// refresh/registration/interactive authorization and race on the shared auth state below.
281281
using var _ = await _tokenAcquisitionLock.LockAsync(cancellationToken).ConfigureAwait(false);
282282

283-
// While we waited for the lock, another concurrent caller may have already refreshed the
284-
// token. Only reuse the cached token if it is both still valid and different from the one
285-
// that produced this challenge (otherwise we'd just replay the rejected token). This is
286-
// limited to 401; a 403 insufficient_scope challenge must still run the step-up flow.
283+
// While we waited for the lock, another concurrent caller may have already acquired or
284+
// refreshed the token. Reuse the cached token if it is both still valid and different from
285+
// the one that produced this challenge (otherwise we'd just replay the rejected token). When
286+
// no token was sent (usedAccessToken is null, e.g. concurrent cold-start requests), any valid
287+
// cached token was obtained by another caller and is safe to reuse. This is limited to 401; a
288+
// 403 insufficient_scope challenge must still run the step-up flow.
287289
if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized &&
288-
usedAccessToken is not null &&
289290
await _tokenCache.GetTokensAsync(cancellationToken).ConfigureAwait(false) is { IsExpired: false } cached &&
290291
!string.Equals(cached.AccessToken, usedAccessToken, StringComparison.Ordinal))
291292
{

0 commit comments

Comments
 (0)