Skip to content

Commit f92cb93

Browse files
Report an MCP OAuth callback failure before a retry (#2238)
* Report an MCP OAuth callback failure before a retry A callback listener can fail before waitForAuthCode() starts to wait. The provider then started a new listener and hid the original error for up to five minutes. - Keep a failure that occurs while no caller waits. - Report that failure once on the next waitForAuthCode() call. - Start a new listener on the call after that. - Close each failed listener. Ignore errors from that cleanup. - Start a new listener only after the old listener closes. - Discard a kept failure when a new listener starts or close() runs. * Answer late MCP OAuth callback requests After the callback wait ends, the listener ignored a new request and sent no response. The connection stayed open, so stopCallbackServer() could not finish. This delayed close(), the OAuth error, and a retry. - Send 404 to a request that arrives after the callback wait ends. - Add a test that uses a real loopback listener.
1 parent 87b57cb commit f92cb93

5 files changed

Lines changed: 432 additions & 53 deletions

File tree

‎src/services/mcp/McpOAuthClientProvider.ts‎

Lines changed: 70 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -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

‎src/services/mcp/__tests__/McpHub.spec.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3211,6 +3211,29 @@ describe("McpHub", () => {
32113211
).resolves.toBeUndefined()
32123212
})
32133213

3214+
it("should record the callback error and disconnect when waitForAuthCode rejects", async () => {
3215+
vsc.window.showInformationMessage.mockResolvedValueOnce(t("mcp:oauth.flow.authenticateButton"))
3216+
// The provider reports a callback listener failure, such as a timeout before the user authenticated.
3217+
mockAuthProvider.waitForAuthCode.mockRejectedValueOnce(new Error("Callback timeout"))
3218+
3219+
await mcpHub["_initiateOAuthFlow"](
3220+
serverName,
3221+
source,
3222+
config,
3223+
mockAuthProvider,
3224+
mockTransport,
3225+
mockConnection,
3226+
)
3227+
3228+
expect(mockAuthProvider.openBrowser).toHaveBeenCalledTimes(1)
3229+
expect(mockAuthProvider.exchangeCodeForTokens).not.toHaveBeenCalled()
3230+
expect(mockAuthProvider.close).toHaveBeenCalled()
3231+
expect(mockConnection.server.status).toBe("disconnected")
3232+
expect(mcpHub["appendErrorMessage"]).toHaveBeenCalledTimes(1)
3233+
expect(mcpHub["appendErrorMessage"]).toHaveBeenCalledWith(mockConnection, "Callback timeout")
3234+
expect(mcpHub["connectToServer"]).not.toHaveBeenCalled()
3235+
})
3236+
32143237
it("should disconnect and flag error when Cancel is pressed after Authenticate is clicked", async () => {
32153238
// Simulate: user clicks Authenticate in the toast, then cancels via the progress bar
32163239
// while waitForAuthCode is still pending.

0 commit comments

Comments
 (0)