diff --git a/.changeset/mcp-oauth-offline-access.md b/.changeset/mcp-oauth-offline-access.md new file mode 100644 index 00000000000..c01ddb43658 --- /dev/null +++ b/.changeset/mcp-oauth-offline-access.md @@ -0,0 +1,5 @@ +--- +"@moonshot-ai/kimi-code": patch +--- + +Fix MCP OAuth not requesting the offline_access scope, which caused hourly browser re-authorization with providers like Vercel. diff --git a/packages/agent-core-v2/src/mcpCore/oauth/service.ts b/packages/agent-core-v2/src/mcpCore/oauth/service.ts index cae78e863ef..a36b6eaa5ba 100644 --- a/packages/agent-core-v2/src/mcpCore/oauth/service.ts +++ b/packages/agent-core-v2/src/mcpCore/oauth/service.ts @@ -1,4 +1,8 @@ -import { auth, type OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js'; +import { + auth, + discoverOAuthServerInfo, + type OAuthClientProvider, +} from '@modelcontextprotocol/sdk/client/auth.js'; import type { OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js'; import type { ILogger as Logger } from '#/_base/log/log'; @@ -93,6 +97,7 @@ const REFRESH_AHEAD_MS = 120_000; const MAX_TIMER_DELAY_MS = 0x7fffffff; const DEFAULT_AUTH_REQUEST_TIMEOUT_MS = 30_000; const DEFAULT_SHUTDOWN_DRAIN_TIMEOUT_MS = 30_000; +const OFFLINE_ACCESS_SCOPE = 'offline_access'; const defaultScheduler: McpOAuthScheduler = { now: () => Date.now(), @@ -290,6 +295,38 @@ export class McpOAuthService { }) as typeof fetch; } + private async resolveRequestScope( + provider: McpOAuthClientProvider, + serverUrl: string | URL, + signal: AbortSignal, + ): Promise { + let discovery = await provider.discoveryState(); + if (discovery?.authorizationServerMetadata === undefined) { + try { + const info = await discoverOAuthServerInfo(serverUrl, { + fetchFn: this.authFetch(provider, [signal]), + }); + discovery = { + ...discovery, + authorizationServerUrl: info.authorizationServerUrl, + resourceMetadata: info.resourceMetadata ?? discovery?.resourceMetadata, + authorizationServerMetadata: info.authorizationServerMetadata, + }; + await provider.saveDiscoveryState(discovery); + } catch { + return undefined; + } + } + const advertised = discovery.authorizationServerMetadata?.scopes_supported; + if (advertised === undefined || !advertised.includes(OFFLINE_ACCESS_SCOPE)) return undefined; + const base = + discovery.resourceMetadata?.scopes_supported ?? + provider.clientMetadata.scope?.split(/\s+/).filter(Boolean) ?? + []; + if (base.includes(OFFLINE_ACCESS_SCOPE)) return undefined; + return [...base, OFFLINE_ACCESS_SCOPE].join(' '); + } + async beginAuthorization( serverName: string, serverUrl: string | URL, @@ -360,6 +397,7 @@ export class McpOAuthService { provider.setRedirectUrl(new URL(callbackServer.redirectUri)); await provider.ready; await provider.invalidateStaleRegistration(callbackServer.redirectUri); + const requestScope = await this.resolveRequestScope(provider, serverUrl, signal); let tokensSaved = false; const unsubscribeTokensSaved = this.onEvent((event) => { if ( @@ -373,6 +411,7 @@ export class McpOAuthService { try { const result = await auth(provider as OAuthClientProvider, { serverUrl, + scope: requestScope, fetchFn: this.authFetch(provider, [signal]), }); if (result !== 'REDIRECT') { diff --git a/packages/agent-core-v2/test/mcpCore/oauth/service.test.ts b/packages/agent-core-v2/test/mcpCore/oauth/service.test.ts index 313f93327a1..08df7646b6d 100644 --- a/packages/agent-core-v2/test/mcpCore/oauth/service.test.ts +++ b/packages/agent-core-v2/test/mcpCore/oauth/service.test.ts @@ -66,12 +66,14 @@ async function readyProvider(fixture: Fixture): Promise interface FakeAuthServer { readonly url: string; readonly counts: { register: number; exchange: number; refresh: number }; + readonly registerScopes: Array; } async function startFakeAuthServer( options: { readonly rejectRefreshToken?: boolean; readonly refreshExpiresIn?: number } = {}, ): Promise { const counts = { register: 0, exchange: 0, refresh: 0 }; + const registerScopes: Array = []; const httpServer: HttpServer = createHttpServer((req, res) => { if (req.method !== 'POST' || (req.url !== '/token' && req.url !== '/register')) { res.writeHead(404).end(); @@ -85,6 +87,7 @@ async function startFakeAuthServer( if (req.url === '/register') { counts.register += 1; const metadata = JSON.parse(body) as Record; + registerScopes.push(typeof metadata['scope'] === 'string' ? (metadata['scope'] as string) : undefined); res.writeHead(201, { 'content-type': 'application/json' }); res.end(JSON.stringify({ ...metadata, client_id: `test-client-${counts.register}` })); return; @@ -123,7 +126,7 @@ async function startFakeAuthServer( }), ); const port = (httpServer.address() as HttpAddress).port; - return { url: `http://127.0.0.1:${port}`, counts }; + return { url: `http://127.0.0.1:${port}`, counts, registerScopes }; } async function startHangingServer(): Promise<{ readonly url: string; readonly counts: { requests: number } }> { @@ -215,7 +218,13 @@ async function startGatedExchangeAuthServer(): Promise return { url: `http://127.0.0.1:${port}`, counts, exchangeStarted, releaseExchange }; } -function authServerState(authServerUrl: string) { +function authServerState( + authServerUrl: string, + options: { + readonly scopesSupported?: string[]; + readonly resourceScopesSupported?: string[]; + } = {}, +) { return { discovery: { authorizationServerUrl: authServerUrl, @@ -227,7 +236,16 @@ function authServerState(authServerUrl: string) { response_types_supported: ['code'], grant_types_supported: ['authorization_code', 'refresh_token'], token_endpoint_auth_methods_supported: ['none'], + scopes_supported: options.scopesSupported, }, + resourceMetadata: + options.resourceScopesSupported === undefined + ? undefined + : { + resource: SERVER_URL, + authorization_servers: [authServerUrl], + scopes_supported: options.resourceScopesSupported, + }, }, client: { client_id: 'cached-client', @@ -722,13 +740,29 @@ describe('McpOAuthService interactive flow serialization', () => { cleanups.push(() => fixture.service.dispose()); const authServer = await startFakeAuthServer(); const provider = await readyProvider(fixture); - await provider.saveDiscoveryState(authServerState(authServer.url).discovery); + await provider.saveDiscoveryState( + authServerState(authServer.url, { + scopesSupported: ['openid', 'offline_access'], + resourceScopesSupported: ['openid'], + }).discovery, + ); + await provider.saveClientInformation({ + client_id: 'stale-client', + redirect_uris: ['http://127.0.0.1:45678/callback'], + token_endpoint_auth_method: 'none', + grant_types: ['authorization_code', 'refresh_token'], + response_types: ['code'], + scope: 'openid', + } satisfies OAuthClientInformationFull); const first = await fixture.service.beginAuthorization(SERVER_NAME, SERVER_URL); const second = await fixture.service.beginAuthorization(SERVER_NAME, SERVER_URL, { clientLabel: 'other-client', }); expect(second.authorizationUrl.toString()).toBe(first.authorizationUrl.toString()); + expect(first.authorizationUrl.searchParams.get('scope')).toBe('openid offline_access'); + expect(authServer.counts.register).toBe(1); + expect(authServer.registerScopes).toEqual(['openid offline_access']); const firstComplete = first.complete({ timeoutMs: 10_000 }); await deliverCallback(first); @@ -894,6 +928,8 @@ describe('McpOAuthService interactive flow serialization', () => { const third = await fixture.service.beginAuthorization(SERVER_NAME, SERVER_URL); expect(third.authorizationUrl.toString()).not.toBe(first.authorizationUrl.toString()); + expect(third.authorizationUrl.searchParams.get('scope')).toBeNull(); + expect(authServer.registerScopes).toEqual([undefined, undefined]); await third.cancel(); }, 15000);