-
Notifications
You must be signed in to change notification settings - Fork 12.9k
fix(core): refresh OAuth-backed HTTP MCP sessions in chat #23493
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
nivbrook
wants to merge
4
commits into
google-gemini:main
Choose a base branch
from
nivbrook:fix-mcp-chat-refresh
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
40df4eb
fix(core): refresh OAuth-backed HTTP MCP sessions in chat
nivbrook e08df80
Merge branch 'main' into fix-mcp-chat-refresh
nivbrook 271c55d
fix(core): avoid stale MCP OAuth expiry after refresh
nivbrook c7ca7e2
Merge branch 'main' into fix-mcp-chat-refresh
nivbrook File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,164 @@ | ||
| /** | ||
| * @license | ||
| * Copyright 2026 Google LLC | ||
| * SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
|
|
||
| import { beforeEach, describe, expect, it, vi } from 'vitest'; | ||
| import type { MCPOAuthConfig } from './oauth-provider.js'; | ||
| import { StoredOAuthMcpProvider } from './stored-oauth-provider.js'; | ||
| import type { MCPOAuthTokenStorage } from './oauth-token-storage.js'; | ||
| import type { OAuthCredentials } from './token-storage/types.js'; | ||
|
|
||
| vi.mock('../utils/events.js', () => ({ | ||
| coreEvents: { | ||
| emitFeedback: vi.fn(), | ||
| }, | ||
| })); | ||
|
|
||
| vi.mock('../mcp/token-storage/hybrid-token-storage.js', () => ({ | ||
| HybridTokenStorage: vi.fn(), | ||
| })); | ||
|
|
||
| describe('StoredOAuthMcpProvider', () => { | ||
| const oauthConfig: MCPOAuthConfig = { | ||
| tokenUrl: 'https://auth.example.com/token', | ||
| }; | ||
|
|
||
| const storedCredentials: OAuthCredentials = { | ||
| serverName: 'test-server', | ||
| token: { | ||
| accessToken: 'stored-access-token', | ||
| refreshToken: 'stored-refresh-token', | ||
| tokenType: 'Bearer', | ||
| scope: 'scope-a scope-b', | ||
| expiresAt: Date.now() + 3600_000, | ||
| }, | ||
| clientId: 'stored-client-id', | ||
| tokenUrl: 'https://auth.example.com/token', | ||
| mcpServerUrl: 'https://example.com/mcp', | ||
| updatedAt: Date.now(), | ||
| }; | ||
|
|
||
| let tokenStorage: MCPOAuthTokenStorage; | ||
|
|
||
| beforeEach(() => { | ||
| tokenStorage = { | ||
| getCredentials: vi.fn().mockResolvedValue(storedCredentials), | ||
| saveToken: vi.fn().mockResolvedValue(undefined), | ||
| deleteCredentials: vi.fn().mockResolvedValue(undefined), | ||
| } as unknown as MCPOAuthTokenStorage; | ||
| }); | ||
|
|
||
| it('returns stored client information and tokens in SDK shape', async () => { | ||
| const provider = new StoredOAuthMcpProvider( | ||
| 'test-server', | ||
| oauthConfig, | ||
| tokenStorage, | ||
| ); | ||
|
|
||
| await expect(provider.clientInformation()).resolves.toEqual({ | ||
| client_id: 'stored-client-id', | ||
| client_secret: undefined, | ||
| token_endpoint_auth_method: 'none', | ||
| }); | ||
|
|
||
| const tokens = await provider.tokens(); | ||
| expect(tokens?.access_token).toBe('stored-access-token'); | ||
| expect(tokens?.refresh_token).toBe('stored-refresh-token'); | ||
| expect(tokens?.token_type).toBe('Bearer'); | ||
| expect(tokens?.scope).toBe('scope-a scope-b'); | ||
| expect(tokens?.expires_in).toBeGreaterThan(0); | ||
| }); | ||
|
|
||
| it('saves refreshed tokens and preserves the previous refresh token when omitted', async () => { | ||
| vi.mocked(tokenStorage.getCredentials) | ||
| .mockResolvedValueOnce(storedCredentials) | ||
| .mockResolvedValueOnce({ | ||
| ...storedCredentials, | ||
| token: { | ||
| ...storedCredentials.token, | ||
| accessToken: 'refreshed-access-token', | ||
| }, | ||
| }); | ||
|
|
||
| const provider = new StoredOAuthMcpProvider( | ||
| 'test-server', | ||
| oauthConfig, | ||
| tokenStorage, | ||
| ); | ||
|
|
||
| await provider.saveTokens({ | ||
| access_token: 'refreshed-access-token', | ||
| token_type: 'Bearer', | ||
| expires_in: 1800, | ||
| }); | ||
|
|
||
| expect(tokenStorage.saveToken).toHaveBeenCalledWith( | ||
| 'test-server', | ||
| expect.objectContaining({ | ||
| accessToken: 'refreshed-access-token', | ||
| refreshToken: 'stored-refresh-token', | ||
| tokenType: 'Bearer', | ||
| }), | ||
| 'stored-client-id', | ||
| 'https://auth.example.com/token', | ||
| 'https://example.com/mcp', | ||
| ); | ||
| }); | ||
|
|
||
| it('does not preserve a stale expiresAt when refreshed tokens omit expires_in', async () => { | ||
| const expiredCredentials: OAuthCredentials = { | ||
| ...storedCredentials, | ||
| token: { | ||
| ...storedCredentials.token, | ||
| expiresAt: Date.now() - 60_000, | ||
| }, | ||
| }; | ||
|
|
||
| vi.mocked(tokenStorage.getCredentials) | ||
| .mockResolvedValueOnce(expiredCredentials) | ||
| .mockResolvedValueOnce({ | ||
| ...expiredCredentials, | ||
| token: { | ||
| accessToken: 'refreshed-access-token', | ||
| refreshToken: 'stored-refresh-token', | ||
| tokenType: 'Bearer', | ||
| scope: 'scope-a scope-b', | ||
| }, | ||
| }); | ||
|
|
||
| const provider = new StoredOAuthMcpProvider( | ||
| 'test-server', | ||
| oauthConfig, | ||
| tokenStorage, | ||
| ); | ||
|
|
||
| await provider.saveTokens({ | ||
| access_token: 'refreshed-access-token', | ||
| token_type: 'Bearer', | ||
| }); | ||
|
|
||
| expect(tokenStorage.saveToken).toHaveBeenCalledWith( | ||
| 'test-server', | ||
| expect.not.objectContaining({ | ||
| expiresAt: expect.any(Number), | ||
| }), | ||
| 'stored-client-id', | ||
| 'https://auth.example.com/token', | ||
| 'https://example.com/mcp', | ||
| ); | ||
| }); | ||
|
|
||
| it('invalidates stored credentials', async () => { | ||
| const provider = new StoredOAuthMcpProvider( | ||
| 'test-server', | ||
| oauthConfig, | ||
| tokenStorage, | ||
| ); | ||
|
|
||
| await provider.invalidateCredentials('tokens'); | ||
|
|
||
| expect(tokenStorage.deleteCredentials).toHaveBeenCalledWith('test-server'); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,189 @@ | ||
| /** | ||
| * @license | ||
| * Copyright 2026 Google LLC | ||
| * SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
|
|
||
| import type { | ||
| OAuthClientInformationMixed, | ||
| OAuthClientMetadata, | ||
| OAuthTokens, | ||
| } from '@modelcontextprotocol/sdk/shared/auth.js'; | ||
| import { REDIRECT_PATH } from '../utils/oauth-flow.js'; | ||
| import { coreEvents } from '../utils/events.js'; | ||
| import { debugLogger } from '../utils/debugLogger.js'; | ||
| import type { MCPOAuthConfig } from './oauth-provider.js'; | ||
| import { MCPOAuthTokenStorage } from './oauth-token-storage.js'; | ||
| import type { OAuthCredentials, OAuthToken } from './token-storage/types.js'; | ||
| import type { McpAuthProvider } from './auth-provider.js'; | ||
|
|
||
| const DEFAULT_REDIRECT_URL = `http://localhost${REDIRECT_PATH}`; | ||
|
|
||
| function toOAuthTokens(token: OAuthToken): OAuthTokens { | ||
| const tokens: OAuthTokens = { | ||
| access_token: token.accessToken, | ||
| token_type: token.tokenType, | ||
| }; | ||
|
|
||
| if (token.refreshToken) { | ||
| tokens.refresh_token = token.refreshToken; | ||
| } | ||
| if (token.scope) { | ||
| tokens.scope = token.scope; | ||
| } | ||
| if (token.expiresAt) { | ||
| tokens.expires_in = Math.max( | ||
| 0, | ||
| Math.floor((token.expiresAt - Date.now()) / 1000), | ||
| ); | ||
| } | ||
|
|
||
| return tokens; | ||
| } | ||
|
|
||
| function toStoredToken( | ||
| tokens: OAuthTokens, | ||
| previousToken?: OAuthToken, | ||
| ): OAuthToken { | ||
| const storedToken: OAuthToken = { | ||
| accessToken: tokens.access_token, | ||
| tokenType: tokens.token_type || previousToken?.tokenType || 'Bearer', | ||
| refreshToken: tokens.refresh_token || previousToken?.refreshToken, | ||
| scope: tokens.scope || previousToken?.scope, | ||
| }; | ||
|
|
||
| if (tokens.expires_in !== undefined) { | ||
| storedToken.expiresAt = Date.now() + tokens.expires_in * 1000; | ||
| } | ||
|
|
||
| return storedToken; | ||
| } | ||
|
|
||
| export class StoredOAuthMcpProvider implements McpAuthProvider { | ||
| private cachedCredentials?: OAuthCredentials | null; | ||
| private cachedClientInformation?: OAuthClientInformationMixed; | ||
| private cachedCodeVerifier?: string; | ||
|
|
||
| constructor( | ||
| private readonly serverName: string, | ||
| private readonly oauthConfig: MCPOAuthConfig = {}, | ||
| private readonly tokenStorage: MCPOAuthTokenStorage = new MCPOAuthTokenStorage(), | ||
| ) {} | ||
|
|
||
| get redirectUrl(): string { | ||
| return this.oauthConfig.redirectUri || DEFAULT_REDIRECT_URL; | ||
| } | ||
|
|
||
| get clientMetadata(): OAuthClientMetadata { | ||
| return { | ||
| client_name: 'Gemini CLI MCP Client', | ||
| redirect_uris: [this.redirectUrl], | ||
| grant_types: ['authorization_code', 'refresh_token'], | ||
| response_types: ['code'], | ||
| token_endpoint_auth_method: this.oauthConfig.clientSecret | ||
| ? 'client_secret_post' | ||
| : 'none', | ||
| scope: this.oauthConfig.scopes?.join(' ') || undefined, | ||
| }; | ||
| } | ||
|
|
||
| private async getCredentials(): Promise<OAuthCredentials | null> { | ||
| if (this.cachedCredentials !== undefined) { | ||
| return this.cachedCredentials; | ||
| } | ||
| this.cachedCredentials = await this.tokenStorage.getCredentials( | ||
| this.serverName, | ||
| ); | ||
| return this.cachedCredentials; | ||
| } | ||
|
|
||
| async clientInformation(): Promise<OAuthClientInformationMixed | undefined> { | ||
| if (this.cachedClientInformation) { | ||
| return this.cachedClientInformation; | ||
| } | ||
|
|
||
| const credentials = await this.getCredentials(); | ||
| const clientId = this.oauthConfig.clientId || credentials?.clientId; | ||
| if (!clientId) { | ||
| return undefined; | ||
| } | ||
|
|
||
| this.cachedClientInformation = { | ||
| client_id: clientId, | ||
| client_secret: this.oauthConfig.clientSecret, | ||
| token_endpoint_auth_method: this.oauthConfig.clientSecret | ||
| ? 'client_secret_post' | ||
| : 'none', | ||
| }; | ||
| return this.cachedClientInformation; | ||
| } | ||
|
|
||
| saveClientInformation(clientInformation: OAuthClientInformationMixed): void { | ||
| this.cachedClientInformation = clientInformation; | ||
| } | ||
|
|
||
| async tokens(): Promise<OAuthTokens | undefined> { | ||
| const credentials = await this.getCredentials(); | ||
| if (!credentials) { | ||
| return undefined; | ||
| } | ||
| return toOAuthTokens(credentials.token); | ||
| } | ||
|
|
||
| async saveTokens(tokens: OAuthTokens): Promise<void> { | ||
| const credentials = await this.getCredentials(); | ||
| const clientId = | ||
| this.oauthConfig.clientId || | ||
| credentials?.clientId || | ||
| this.cachedClientInformation?.client_id; | ||
|
|
||
| await this.tokenStorage.saveToken( | ||
| this.serverName, | ||
| toStoredToken(tokens, credentials?.token), | ||
| clientId, | ||
| this.oauthConfig.tokenUrl || credentials?.tokenUrl, | ||
| credentials?.mcpServerUrl, | ||
| ); | ||
|
|
||
| this.cachedCredentials = await this.tokenStorage.getCredentials( | ||
| this.serverName, | ||
| ); | ||
| } | ||
|
|
||
| async redirectToAuthorization(authorizationUrl: URL): Promise<void> { | ||
| debugLogger.log( | ||
| `Stored OAuth provider for '${this.serverName}' needs re-authentication at ${authorizationUrl.toString()}`, | ||
| ); | ||
| coreEvents.emitFeedback( | ||
| 'info', | ||
| `MCP server '${this.serverName}' requires re-authentication using: /mcp auth ${this.serverName}`, | ||
| ); | ||
| } | ||
|
|
||
| saveCodeVerifier(codeVerifier: string): void { | ||
| this.cachedCodeVerifier = codeVerifier; | ||
| } | ||
|
|
||
| codeVerifier(): string { | ||
| if (!this.cachedCodeVerifier) { | ||
| throw new Error('No code verifier saved'); | ||
| } | ||
| return this.cachedCodeVerifier; | ||
| } | ||
|
|
||
| async invalidateCredentials( | ||
| scope: 'all' | 'client' | 'tokens' | 'verifier', | ||
| ): Promise<void> { | ||
| if (scope === 'all' || scope === 'client' || scope === 'tokens') { | ||
| await this.tokenStorage.deleteCredentials(this.serverName); | ||
| this.cachedCredentials = null; | ||
| if (scope === 'all' || scope === 'client') { | ||
| this.cachedClientInformation = undefined; | ||
| } | ||
| } | ||
|
|
||
| if (scope === 'all' || scope === 'verifier') { | ||
| this.cachedCodeVerifier = undefined; | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.