fix: clear stale client registration on OAuth flow failure

When a stored client_id is no longer recognized by the OAuth server,
the flow fails but the stale client stays in MongoDB, causing every
retry to reuse the same invalid registration in an infinite loop.

On OAuth failure, clear the stored client registration so the next
attempt falls through to fresh Dynamic Client Registration.

- Add MCPTokenStorage.deleteClientRegistration() for targeted cleanup
- Call it from MCPConnectionFactory's OAuth failure path
- Add integration test proving recovery from stale client reuse
This commit is contained in:
Danny Avila 2026-04-03 15:26:43 -04:00
parent 20a08e1904
commit d355be7dd0
3 changed files with 92 additions and 1 deletions

View file

@ -413,7 +413,17 @@ export class MCPConnectionFactory {
if (result?.tokens) {
connection.emit('oauthHandled');
} else {
// OAuth failed, emit oauthFailed to properly reject the promise
// OAuth failed — clear stored client registration so the next attempt
// does a fresh DCR instead of reusing a potentially stale client_id
if (this.tokenMethods?.deleteTokens) {
await MCPTokenStorage.deleteClientRegistration({
userId: this.userId!,
serverName: this.serverName,
deleteTokens: this.tokenMethods.deleteTokens,
}).catch((err) => {
logger.debug(`${this.logPrefix} Failed to clear stale client registration`, err);
});
}
logger.warn(`${this.logPrefix} OAuth failed, emitting oauthFailed event`);
connection.emit('oauthFailed', new Error('OAuth authentication failed'));
}