@@ -48,13 +48,24 @@ internal sealed partial class ClientOAuthProvider : McpHttpClient
4848 private string ? _tokenEndpointAuthMethod ;
4949 private ITokenCache _tokenCache ;
5050 private AuthorizationServerMetadata ? _authServerMetadata ;
51+
52+ // Coalesces concurrent token acquisition so that when multiple in-flight requests observe an
53+ // expired token (or a 401) at the same time, only the first runs the refresh/authorization flow
54+ // while the others await its result. This also serializes all reads and writes to the mutable auth
55+ // state below (_authServerMetadata, _clientId, _clientSecret, _tokenEndpointAuthMethod) as well as
56+ // the accumulated scope set and step-up tracking (_accumulatedScopes, _hasAttemptedStepUp), so those
57+ // fields need no separate lock.
58+ //
59+ // Intentionally not disposed: this instance is only ever used via WaitAsync/Release (never its
60+ // AvailableWaitHandle), so SemaphoreSlim allocates no unmanaged resource and there is nothing to
61+ // dispose. Do not access AvailableWaitHandle, or this field will need deterministic disposal.
62+ private readonly SemaphoreSlim _tokenAcquisitionLock = new ( 1 , 1 ) ;
5163 // The accumulated scope set lives for this provider's lifetime and is intentionally not keyed by
5264 // resource or authorization server. This is safe today because one ClientOAuthProvider is created
5365 // per HttpClientTransport, i.e. per endpoint/resource. If a provider were ever reused across
5466 // multiple resources or auth servers, accumulated scopes could be sent to a server that rejects
5567 // them (invalid_scope). Accumulation is scoped per "resource and operation" combination (SEP-2350).
5668 private readonly HashSet < string > _accumulatedScopes = new ( StringComparer . Ordinal ) ;
57- private readonly object _scopeAccumulatorLock = new ( ) ;
5869 private bool _hasAttemptedStepUp ;
5970
6071 /// <summary>
@@ -145,7 +156,10 @@ internal override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage r
145156
146157 if ( ShouldRetryWithNewAccessToken ( response ) )
147158 {
148- return await HandleUnauthorizedResponseAsync ( request , message , response , attemptedRefresh , cancellationToken ) . ConfigureAwait ( false ) ;
159+ // Capture the token that produced this challenge so the retry path can detect whether
160+ // another concurrent caller already replaced it in the cache.
161+ var usedAccessToken = request . Headers . Authorization ? . Parameter ;
162+ return await HandleUnauthorizedResponseAsync ( request , message , response , attemptedRefresh , usedAccessToken , cancellationToken ) . ConfigureAwait ( false ) ;
149163 }
150164
151165 return response ;
@@ -161,15 +175,32 @@ internal override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage r
161175 return ( tokens . AccessToken , false ) ;
162176 }
163177
164- // Try to refresh the access token if it is invalid and we have a refresh token.
165- if ( _authServerMetadata is not null && tokens ? . RefreshToken is { Length : > 0 } refreshToken )
178+ // A refresh is only possible if we have both the auth server metadata and a refresh token.
179+ if ( _authServerMetadata is null || tokens ? . RefreshToken is not { Length : > 0 } )
180+ {
181+ // No valid token - auth handler will trigger the 401 flow
182+ return ( null , false ) ;
183+ }
184+
185+ // Serialize the refresh so concurrent callers that all saw the expired token don't each fire
186+ // their own refresh. Waiters re-check the cache after acquiring the lock and reuse the token
187+ // produced by whoever refreshed first.
188+ using var _ = await _tokenAcquisitionLock . LockAsync ( cancellationToken ) . ConfigureAwait ( false ) ;
189+
190+ var current = await _tokenCache . GetTokensAsync ( cancellationToken ) . ConfigureAwait ( false ) ;
191+ if ( current is not null && ! current . IsExpired )
192+ {
193+ return ( current . AccessToken , true ) ;
194+ }
195+
196+ if ( _authServerMetadata is not null && current ? . RefreshToken is { Length : > 0 } refreshToken )
166197 {
167198 var accessToken = await RefreshTokensAsync ( refreshToken , resourceUri . ToString ( ) , _authServerMetadata , cancellationToken ) . ConfigureAwait ( false ) ;
168199 return ( accessToken , true ) ;
169200 }
170201
171202 // No valid token - auth handler will trigger the 401 flow
172- return ( null , false ) ;
203+ return ( null , true ) ;
173204 }
174205
175206 private static bool ShouldRetryWithNewAccessToken ( HttpResponseMessage response )
@@ -208,6 +239,7 @@ private async Task<HttpResponseMessage> HandleUnauthorizedResponseAsync(
208239 JsonRpcMessage ? originalJsonRpcMessage ,
209240 HttpResponseMessage response ,
210241 bool attemptedRefresh ,
242+ string ? usedAccessToken ,
211243 CancellationToken cancellationToken )
212244 {
213245 if ( response . Headers . WwwAuthenticate . Count == 0 )
@@ -220,7 +252,7 @@ private async Task<HttpResponseMessage> HandleUnauthorizedResponseAsync(
220252 throw new McpException ( $ "The server does not support the '{ BearerScheme } ' authentication scheme. Server supports: [{ serverSchemes } ].") ;
221253 }
222254
223- var accessToken = await GetAccessTokenAsync ( response , attemptedRefresh , cancellationToken ) . ConfigureAwait ( false ) ;
255+ var accessToken = await GetAccessTokenAsync ( response , attemptedRefresh , usedAccessToken , cancellationToken ) . ConfigureAwait ( false ) ;
224256
225257 using var retryRequest = new HttpRequestMessage ( originalRequest . Method , originalRequest . RequestUri ) ;
226258
@@ -241,8 +273,31 @@ private async Task<HttpResponseMessage> HandleUnauthorizedResponseAsync(
241273 /// </summary>
242274 /// <param name="response">The HTTP response that triggered the authentication challenge.</param>
243275 /// <param name="attemptedRefresh">Indicates whether a token refresh has already been attempted.</param>
276+ /// <param name="usedAccessToken">The access token that produced the challenge, or <see langword="null"/> if none was sent.</param>
244277 /// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests.</param>
245- private async Task < string > GetAccessTokenAsync ( HttpResponseMessage response , bool attemptedRefresh , CancellationToken cancellationToken )
278+ private async Task < string > GetAccessTokenAsync ( HttpResponseMessage response , bool attemptedRefresh , string ? usedAccessToken , CancellationToken cancellationToken )
279+ {
280+ // Serialize the authorization flow so concurrent 401/403 challenges don't each run a full
281+ // refresh/registration/interactive authorization and race on the shared auth state below.
282+ using var _ = await _tokenAcquisitionLock . LockAsync ( cancellationToken ) . ConfigureAwait ( false ) ;
283+
284+ // While we waited for the lock, another concurrent caller may have already acquired or
285+ // refreshed the token. Reuse the cached token if it is both still valid and different from
286+ // the one that produced this challenge (otherwise we'd just replay the rejected token). When
287+ // no token was sent (usedAccessToken is null, e.g. concurrent cold-start requests), any valid
288+ // cached token was obtained by another caller and is safe to reuse. This is limited to 401; a
289+ // 403 insufficient_scope challenge must still run the step-up flow.
290+ if ( response . StatusCode == System . Net . HttpStatusCode . Unauthorized &&
291+ await _tokenCache . GetTokensAsync ( cancellationToken ) . ConfigureAwait ( false ) is { IsExpired : false } cached &&
292+ ! string . Equals ( cached . AccessToken , usedAccessToken , StringComparison . Ordinal ) )
293+ {
294+ return cached . AccessToken ;
295+ }
296+
297+ return await GetAccessTokenCoreAsync ( response , attemptedRefresh , usedAccessToken , cancellationToken ) . ConfigureAwait ( false ) ;
298+ }
299+
300+ private async Task < string > GetAccessTokenCoreAsync ( HttpResponseMessage response , bool attemptedRefresh , string ? usedAccessToken , CancellationToken cancellationToken )
246301 {
247302 // Get available authorization servers from the 401 or 403 response
248303 var protectedResourceMetadata = await ExtractProtectedResourceMetadata ( response , cancellationToken ) . ConfigureAwait ( false ) ;
@@ -262,17 +317,26 @@ private async Task<string> GetAccessTokenAsync(HttpResponseMessage response, boo
262317 if ( response . StatusCode == System . Net . HttpStatusCode . Forbidden )
263318 {
264319 bool introducesNewScopes = ChallengeIntroducesNewScopes ( protectedResourceMetadata ) ;
265- lock ( _scopeAccumulatorLock )
320+ if ( _hasAttemptedStepUp && ! introducesNewScopes )
266321 {
267- if ( _hasAttemptedStepUp && ! introducesNewScopes )
322+ // A step-up has already run and this challenge asks for nothing new. If that step-up
323+ // produced a different, still-valid token (for example another concurrent caller ran
324+ // it while this one waited on the lock), reuse that token instead of failing, since it
325+ // already reflects the accumulated scopes. Only fail when there is no newer token to
326+ // try, which is the genuine repeated-failure case where the stepped-up token itself
327+ // was rejected again.
328+ if ( await _tokenCache . GetTokensAsync ( cancellationToken ) . ConfigureAwait ( false ) is { IsExpired : false } steppedUpToken &&
329+ ! string . Equals ( steppedUpToken . AccessToken , usedAccessToken , StringComparison . Ordinal ) )
268330 {
269- ThrowFailedToHandleUnauthorizedResponse (
270- "A repeated insufficient_scope challenge added no scope beyond those already requested, " +
271- "so step-up authorization cannot satisfy the request." ) ;
331+ return steppedUpToken . AccessToken ;
272332 }
273333
274- _hasAttemptedStepUp = true ;
334+ ThrowFailedToHandleUnauthorizedResponse (
335+ "A repeated insufficient_scope challenge added no scope beyond those already requested, " +
336+ "so step-up authorization cannot satisfy the request." ) ;
275337 }
338+
339+ _hasAttemptedStepUp = true ;
276340 }
277341
278342 // Convert string URIs to Uri objects for the selector
@@ -812,13 +876,10 @@ private async Task PerformDynamicClientRegistrationAsync(
812876
813877 if ( currentOperationScopes . Count == 0 )
814878 {
815- lock ( _scopeAccumulatorLock )
816- {
817- // If we have previously requested scopes but nothing new, return the accumulated set.
818- return _accumulatedScopes . Count > 0
819- ? string . Join ( " " , _accumulatedScopes . OrderBy ( s => s , StringComparer . Ordinal ) )
820- : null ;
821- }
879+ // If we have previously requested scopes but nothing new, return the accumulated set.
880+ return _accumulatedScopes . Count > 0
881+ ? string . Join ( " " , _accumulatedScopes . OrderBy ( s => s , StringComparer . Ordinal ) )
882+ : null ;
822883 }
823884
824885 // Per SEP-2350: Compute the union of previously requested scopes and newly challenged scopes
@@ -827,16 +888,13 @@ private async Task PerformDynamicClientRegistrationAsync(
827888 // offline_access (AugmentScopeWithOfflineAccess) and any ScopeSelector are applied per request
828889 // in ComputeEffectiveScope and are intentionally not accumulated, so the selector always sees
829890 // the full union and the operation stays idempotent.
830- lock ( _scopeAccumulatorLock )
891+ foreach ( var scope in currentOperationScopes )
831892 {
832- foreach ( var scope in currentOperationScopes )
833- {
834- _accumulatedScopes . Add ( scope ) ;
835- }
836-
837- // Sort scopes for stable, deterministic output (scopes are unordered per RFC 6749 §3.3).
838- return string . Join ( " " , _accumulatedScopes . OrderBy ( s => s , StringComparer . Ordinal ) ) ;
893+ _accumulatedScopes . Add ( scope ) ;
839894 }
895+
896+ // Sort scopes for stable, deterministic output (scopes are unordered per RFC 6749 §3.3).
897+ return string . Join ( " " , _accumulatedScopes . OrderBy ( s => s , StringComparer . Ordinal ) ) ;
840898 }
841899
842900 /// <summary>
@@ -881,14 +939,11 @@ private bool ChallengeIntroducesNewScopes(ProtectedResourceMetadata protectedRes
881939 return false ;
882940 }
883941
884- lock ( _scopeAccumulatorLock )
942+ foreach ( var scope in currentOperationScopes )
885943 {
886- foreach ( var scope in currentOperationScopes )
944+ if ( ! _accumulatedScopes . Contains ( scope ) )
887945 {
888- if ( ! _accumulatedScopes . Contains ( scope ) )
889- {
890- return true ;
891- }
946+ return true ;
892947 }
893948 }
894949
0 commit comments