@@ -93,6 +93,15 @@ export class McpOAuthClientProvider implements OAuthClientProvider {
9393 private _effectiveResourceIndicator : string | null
9494 /** Deduplicates concurrent _ensureCallbackServer() calls. */
9595 private _ensureServerPromise : Promise < void > | null = null
96+ /** Callback promise most recently returned to a waitForAuthCode() caller. */
97+ private _awaitedAuthCodePromise : Promise < string > | null = null
98+ /**
99+ * Rejected callback promise of a listener that failed while no caller was waiting.
100+ * The next waitForAuthCode() call reports it once instead of starting another listener.
101+ */
102+ private _unreportedAuthCodeFailure : Promise < string > | null = null
103+ /** Stops a detached listener. A replacement listener waits for it because it may reuse the port. */
104+ private _listenerCleanup : Promise < void > | null = null
96105
97106 private constructor (
98107 private readonly _serverUrl : string ,
@@ -243,6 +252,11 @@ export class McpOAuthClientProvider implements OAuthClientProvider {
243252
244253 private async _doStartCallbackServer ( ) : Promise < void > {
245254 this . _closed = false
255+ // A new listener belongs to a new authorization attempt, so an earlier failure no longer applies.
256+ this . _unreportedAuthCodeFailure = null
257+ if ( this . _listenerCleanup ) {
258+ await this . _listenerCleanup
259+ }
246260 const { port : configuredPort , host, path } = getCallbackAddress ( this . _configuredRedirectUri )
247261 const { server, port, result, cancel } = await startCallbackServer (
248262 configuredPort ?? this . _port ,
@@ -261,18 +275,31 @@ export class McpOAuthClientProvider implements OAuthClientProvider {
261275 this . _authCodePromise = authCodePromise
262276
263277 // Static clients can start this promise before waitForAuthCode() observes it.
264- // Observe rejection now to prevent an unhandled rejection, but keep the original
265- // promise so waitForAuthCode() still receives the callback error. Stop only this
266- // promise's listener before clearing it so a later flow can bind a fresh listener.
267- void authCodePromise . catch ( async ( ) => {
268- if ( this . _authCodePromise === authCodePromise && this . _server === server ) {
269- await stopCallbackServer ( server , cancel ) . catch ( ( ) => { } )
270- if ( this . _authCodePromise === authCodePromise && this . _server === server ) {
271- this . _server = null
272- this . _cancelCallbackServer = null
273- }
278+ // Observe rejection now to prevent an unhandled rejection. A caller that is already
279+ // waiting receives the error from this promise; otherwise keep the rejected promise so
280+ // the next waitForAuthCode() call reports it instead of waiting on a new listener.
281+ void authCodePromise . catch ( ( ) => {
282+ // close() detaches this promise before it cancels the listener and stops it itself.
283+ if ( this . _authCodePromise !== authCodePromise ) return
284+ if ( this . _awaitedAuthCodePromise !== authCodePromise ) {
285+ this . _unreportedAuthCodeFailure = authCodePromise
286+ }
287+ // Detach only the failed listener so a later authorization attempt starts a fresh one.
288+ // Keep the failed promise current for callers that are still resuming from startup.
289+ this . _server = null
290+ this . _cancelCallbackServer = null
291+ this . _stopDetachedListener ( server , cancel )
292+ } )
293+ }
294+
295+ /** Stops a listener that is no longer attached. A replacement listener waits because it may reuse the port. */
296+ private _stopDetachedListener ( server : http . Server , cancel : ( ) => void ) : void {
297+ const cleanup = stopCallbackServerIgnoringErrors ( server , cancel ) . finally ( ( ) => {
298+ if ( this . _listenerCleanup === cleanup ) {
299+ this . _listenerCleanup = null
274300 }
275301 } )
302+ this . _listenerCleanup = cleanup
276303 }
277304
278305 state ( ) : string {
@@ -521,12 +548,24 @@ export class McpOAuthClientProvider implements OAuthClientProvider {
521548 * Resolves with the authorization code once the user completes the OAuth
522549 * browser flow and the local callback server receives the redirect.
523550 * Rejects on error or 5-minute timeout.
551+ *
552+ * If the listener failed before any caller waited, the first call rejects with
553+ * that failure without starting another listener. A later call starts a fresh one.
524554 */
525555 async waitForAuthCode ( ) : Promise < string > {
526- if ( ! this . _authCodePromise || ! this . _server ) {
556+ if ( ! this . _unreportedAuthCodeFailure && ( ! this . _authCodePromise || ! this . _server ) ) {
527557 await this . _ensureCallbackServer ( )
528558 }
529- return this . _authCodePromise !
559+ const unreportedFailure = this . _unreportedAuthCodeFailure
560+ if ( unreportedFailure ) {
561+ this . _unreportedAuthCodeFailure = null
562+ return unreportedFailure
563+ }
564+ // A caller that waited for listener startup receives that listener's result, even when
565+ // another caller already took the failure while this caller was resuming.
566+ const authCodePromise = this . _authCodePromise !
567+ this . _awaitedAuthCodePromise = authCodePromise
568+ return authCodePromise
530569 }
531570
532571 /**
@@ -655,13 +694,30 @@ export class McpOAuthClientProvider implements OAuthClientProvider {
655694 if ( this . _ensureServerPromise ) {
656695 await this . _ensureServerPromise . catch ( ( ) => { } )
657696 }
658- if ( ! this . _closed && this . _server ) {
697+ // A closed flow must not report its failure to a later flow.
698+ this . _unreportedAuthCodeFailure = null
699+ const server = this . _server
700+ if ( ! this . _closed && server ) {
659701 this . _closed = true
660- await stopCallbackServer ( this . _server , this . _cancelCallbackServer ?? ( ( ) => { } ) ) . catch ( ( ) => { } )
702+ const cancel = this . _cancelCallbackServer ?? ( ( ) => { } )
703+ // Detach before cancelling so the rejection handler does not record the cancellation.
661704 this . _server = null
662705 this . _cancelCallbackServer = null
663706 this . _authCodePromise = null
707+ this . _stopDetachedListener ( server , cancel )
664708 }
709+ if ( this . _listenerCleanup ) {
710+ await this . _listenerCleanup
711+ }
712+ }
713+ }
714+
715+ /** Stops a callback listener. A cleanup error must not replace the callback error. */
716+ async function stopCallbackServerIgnoringErrors ( server : http . Server , cancel : ( ) => void ) : Promise < void > {
717+ try {
718+ await stopCallbackServer ( server , cancel )
719+ } catch {
720+ // The callback result, not the cleanup result, is the error that callers report.
665721 }
666722}
667723
0 commit comments