Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(connector): derive default OAuth scopes from the protected resource (#22564)

Bryane3cd3d1ca230
diff --git a/apps/server/src/routers/lambda/__tests__/connector.startOAuth.test.ts b/apps/server/src/routers/lambda/__tests__/connector.startOAuth.test.ts
index a8fb65f8431..4a338a0b88c 100644
--- a/apps/server/src/routers/lambda/__tests__/connector.startOAuth.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/connector.startOAuth.test.ts
@@ -34,12 +34,30 @@ const CONNECTOR_ID = '9f1f6f30-0000-4000-8000-000000000003';
const METADATA_URL = 'https://app.example.com/oauth/connector/client-metadata.json';
/** Authorization server co-located with the MCP server, advertising `metadata`. */
-const stubAuthorizationServer = (metadata: Record<string, unknown>) => {
+const stubAuthorizationServer = (
+ metadata: Record<string, unknown>,
+ resource?: { challengeScope?: string; scopes?: string[] },
+) => {
const registrations: unknown[] = [];
vi.stubGlobal(
'fetch',
vi.fn(async (url: string | URL, init?: RequestInit) => {
const href = String(url);
+ if (resource && href === 'https://mcp.example.com/mcp') {
+ return new Response(null, {
+ headers: {
+ 'WWW-Authenticate': `Bearer resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource"${resource.challengeScope === undefined ? '' : `, scope="${resource.challengeScope}"`}`,
+ },
+ status: 401,
+ });
+ }
+ if (resource && href === 'https://mcp.example.com/.well-known/oauth-protected-resource') {
+ return Response.json({
+ authorization_servers: ['https://mcp.example.com/'],
+ resource: 'https://mcp.example.com/mcp',
+ scopes_supported: resource.scopes,
+ });
+ }
if (href === 'https://mcp.example.com/.well-known/oauth-authorization-server') {
return Response.json({
authorization_endpoint: 'https://mcp.example.com/authorize',
@@ -140,4 +158,117 @@ describe('connectorRouter.startOAuth client registration', () => {
message: expect.stringContaining('neither Client ID Metadata Documents nor dynamic'),
});
});
+
+ const vercelScopes = ['openid', 'email', 'profile', 'offline_access', 'ema_issuer:manage'];
+ const vercelMetadata = {
+ client_id_metadata_document_supported: true,
+ scopes_supported: vercelScopes,
+ };
+
+ it('requests resource scopes plus offline access and consent for Vercel-shaped metadata', async () => {
+ stubAuthorizationServer(vercelMetadata, { scopes: ['openid'] });
+
+ const url = new URL((await startOAuth()).authorizationUrl);
+
+ expect(url.searchParams.get('scope')).toBe('openid offline_access');
+ expect(url.searchParams.get('prompt')).toBe('consent');
+ });
+
+ it('prefers the WWW-Authenticate scope over resource metadata', async () => {
+ stubAuthorizationServer(vercelMetadata, {
+ challengeScope: 'tools:read tools:write',
+ scopes: ['openid'],
+ });
+
+ const url = new URL((await startOAuth()).authorizationUrl);
+
+ expect(url.searchParams.get('scope')).toBe('tools:read tools:write offline_access');
+ });
+
+ it.each([undefined, {}])(
+ 'keeps the AS scope fallback when PRM has no scopes (%j)',
+ async (prm) => {
+ stubAuthorizationServer(vercelMetadata, prm);
+
+ const url = new URL((await startOAuth()).authorizationUrl);
+
+ expect(url.searchParams.get('scope')).toBe(vercelScopes.join(' '));
+ expect(url.searchParams.get('prompt')).toBe('consent');
+ },
+ );
+
+ it('keeps configured scopes ahead of challenge and resource metadata', async () => {
+ stubAuthorizationServer(vercelMetadata, {
+ challengeScope: 'challenged:read',
+ scopes: ['openid'],
+ });
+ connectorModelMock.findById.mockResolvedValue({
+ id: CONNECTOR_ID,
+ mcpServerUrl: 'https://mcp.example.com/mcp',
+ oidcConfig: { scheme: 'dcr', scopes: ['custom:read'] },
+ userId: 'me',
+ });
+
+ const url = new URL((await startOAuth()).authorizationUrl);
+
+ expect(url.searchParams.get('scope')).toBe('custom:read');
+ expect(url.searchParams.has('prompt')).toBe(false);
+ expect(connectorModelMock.update).toHaveBeenCalledWith(CONNECTOR_ID, {
+ oidcConfig: expect.objectContaining({ scopes: ['custom:read'] }),
+ });
+ });
+
+ it('keeps previously saved scopes and writes them back unchanged', async () => {
+ stubAuthorizationServer(vercelMetadata, { scopes: ['openid'] });
+ connectorModelMock.findById.mockResolvedValue({
+ id: CONNECTOR_ID,
+ mcpServerUrl: 'https://mcp.example.com/mcp',
+ oidcConfig: {
+ authorizationEndpoint: 'https://mcp.example.com/authorize',
+ clientId: METADATA_URL,
+ scheme: 'client_id_metadata_document',
+ scopes: vercelScopes,
+ },
+ userId: 'me',
+ });
+
+ const url = new URL((await startOAuth()).authorizationUrl);
+
+ expect(url.searchParams.get('scope')).toBe(vercelScopes.join(' '));
+ expect(connectorModelMock.update).toHaveBeenCalledWith(CONNECTOR_ID, {
+ oidcConfig: expect.objectContaining({ scopes: vercelScopes }),
+ });
+ });
+
+ it('does not request offline access or consent when the AS does not advertise it', async () => {
+ stubAuthorizationServer(
+ { ...vercelMetadata, scopes_supported: ['openid'] },
+ { scopes: ['openid'] },
+ );
+
+ const url = new URL((await startOAuth()).authorizationUrl);
+
+ expect(url.searchParams.get('scope')).toBe('openid');
+ expect(url.searchParams.has('prompt')).toBe(false);
+ });
+
+ it('omits scope and consent when no source advertises scopes', async () => {
+ stubAuthorizationServer({ client_id_metadata_document_supported: true });
+
+ const url = new URL((await startOAuth()).authorizationUrl);
+
+ expect(url.searchParams.has('scope')).toBe(false);
+ expect(url.searchParams.has('prompt')).toBe(false);
+ });
+
+ it('omits scope from dynamic registration when no source advertises scopes', async () => {
+ const registrations = stubAuthorizationServer({
+ registration_endpoint: 'https://mcp.example.com/register',
+ });
+
+ await startOAuth();
+
+ expect(registrations).toHaveLength(1);
+ expect(registrations[0]).not.toHaveProperty('scope');
+ });
});
diff --git a/apps/server/src/routers/lambda/connector.ts b/apps/server/src/routers/lambda/connector.ts
index ff0ddc9bce5..c7d0c0e3005 100644
--- a/apps/server/src/routers/lambda/connector.ts
+++ b/apps/server/src/routers/lambda/connector.ts
@@ -37,6 +37,7 @@ import {
discoverConnectorOAuth,
getConnectorRedirectUri,
resolveConnectorClient,
+ resolveConnectorOAuthScopes,
toClientInformation,
} from '@/server/services/connector/oauth';
import {
@@ -618,21 +619,18 @@ export const connectorRouter = router({
// Discovery and registration failures below are server-compatibility
// problems the user must fix in their OAuth setup, not internal errors β€”
// surface them as BAD_REQUEST with the reason so the form can show it.
- const { authorizationServerUrl, metadata } = await discoverConnectorOAuth(
- connector.mcpServerUrl,
- ).catch((error: unknown) => {
- throw new TRPCError({
- cause: error,
- code: 'BAD_REQUEST',
- message: (error as Error)?.message ?? String(error),
- });
- });
+ const discovery = await discoverConnectorOAuth(connector.mcpServerUrl).catch(
+ (error: unknown) => {
+ throw new TRPCError({
+ cause: error,
+ code: 'BAD_REQUEST',
+ message: (error as Error)?.message ?? String(error),
+ });
+ },
+ );
- // Default to the scopes advertised by the server when the user did not
- // specify any β€” many MCP authorization servers reject (or issue a useless
- // token for) a scope-less request.
- const scopes =
- existing.scopes && existing.scopes.length > 0 ? existing.scopes : metadata.scopes_supported;
+ const { authorizationServerUrl, metadata } = discovery;
+ const scopes = resolveConnectorOAuthScopes({ discovery, existingScopes: existing.scopes });
// 2. Resolve the OAuth client: pre-registration, CIMD, then DCR.
const { clientId, clientSecret, scheme, tokenEndpointAuthMethod } =
diff --git a/apps/server/src/services/connector/oauth.ts b/apps/server/src/services/connector/oauth.ts
index f04cd794781..6446cca70fa 100644
--- a/apps/server/src/services/connector/oauth.ts
+++ b/apps/server/src/services/connector/oauth.ts
@@ -14,7 +14,7 @@ import {
discoverAuthorizationServerMetadata,
discoverOAuthProtectedResourceMetadata,
exchangeAuthorization,
- extractResourceMetadataUrl,
+ extractWWWAuthenticateParams,
isHttpsUrl,
IssuerMismatchError,
OAuthError,
@@ -99,6 +99,8 @@ export const discoverConnectorAuthorizationServerMetadata = (
export interface DiscoveredOAuth {
authorizationServerUrl: string;
metadata: AuthorizationServerMetadata;
+ /** Resource-required scopes: challenge first, then protected resource metadata. */
+ scopes?: string[];
}
/**
@@ -115,6 +117,7 @@ export interface DiscoveredOAuth {
*/
export const discoverConnectorOAuth = async (mcpServerUrl: string): Promise<DiscoveredOAuth> => {
let resourceMetadataUrl: URL | undefined;
+ let scopes: string[] | undefined;
try {
const res = await connectorFetch(mcpServerUrl, {
headers: { accept: 'application/json, text/event-stream' },
@@ -123,7 +126,11 @@ export const discoverConnectorOAuth = async (mcpServerUrl: string): Promise<Disc
// Only the status and `WWW-Authenticate` header matter. Release the body: a server
// may answer this GET with an SSE stream that never ends.
await res.body?.cancel().catch(() => {});
- if (res.status === 401) resourceMetadataUrl = extractResourceMetadataUrl(res);
+ if (res.status === 401) {
+ const challenge = extractWWWAuthenticateParams(res);
+ resourceMetadataUrl = challenge.resourceMetadataUrl;
+ scopes = challenge.scope?.split(' ').filter(Boolean);
+ }
} catch (err) {
log('probe request failed, falling back to well-known discovery: %O', err);
}
@@ -136,6 +143,7 @@ export const discoverConnectorOAuth = async (mcpServerUrl: string): Promise<Disc
connectorFetch,
);
authorizationServerUrl = prm?.authorization_servers?.[0]?.toString();
+ if (!scopes?.length) scopes = prm?.scopes_supported;
} catch (err) {
log('protected-resource-metadata discovery failed: %O', err);
}
@@ -159,7 +167,30 @@ export const discoverConnectorOAuth = async (mcpServerUrl: string): Promise<Disc
throw new Error(`Failed to discover OAuth metadata for ${authorizationServerUrl}`);
}
- return { authorizationServerUrl, metadata };
+ return { authorizationServerUrl, metadata, ...(scopes?.length ? { scopes } : {}) };
+};
+
+/**
+ * Keep configured scopes unchanged. Otherwise select resource scopes before the
+ * legacy AS fallback and match the SDK's refresh-token scope augmentation.
+ */
+export const resolveConnectorOAuthScopes = (params: {
+ discovery: DiscoveredOAuth;
+ existingScopes?: string[];
+}): string[] | undefined => {
+ if (params.existingScopes?.length) return params.existingScopes;
+ const { metadata, scopes: resourceScopes } = params.discovery;
+ const selected = resourceScopes ?? metadata.scopes_supported;
+ const scopes = selected?.length ? [...new Set(selected)] : undefined;
+ if (
+ scopes?.length &&
+ metadata.scopes_supported?.includes('offline_access') &&
+ buildConnectorClientMetadata().grant_types?.includes('refresh_token') &&
+ !scopes.includes('offline_access')
+ ) {
+ scopes.push('offline_access');
+ }
+ return scopes;
};
type RegistrationAuthMethod = 'client_secret_basic' | 'client_secret_post' | 'none';