fix: request offline_access in MCP OAuth when the authorization server advertises it (#3979)

This commit is contained in:
Haozhe 2026-09-22 19:05:24 +08:00 • committed by GitHub
parent bb96d80748
commit e796bb5d48
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 84 additions and 4 deletions

View file

@ -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.

View file

@ -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<string | undefined> {
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') {

View file

@ -66,12 +66,14 @@ async function readyProvider(fixture: Fixture): Promise<McpOAuthClientProvider>
interface FakeAuthServer {
readonly url: string;
readonly counts: { register: number; exchange: number; refresh: number };
readonly registerScopes: Array<string | undefined>;
}
async function startFakeAuthServer(
options: { readonly rejectRefreshToken?: boolean; readonly refreshExpiresIn?: number } = {},
): Promise<FakeAuthServer> {
const counts = { register: 0, exchange: 0, refresh: 0 };
const registerScopes: Array<string | undefined> = [];
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<string, unknown>;
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<GatedExchangeAuthServer>
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);