diff --git a/README.md b/README.md index 3ef94af..4fa28a5 100644 --- a/README.md +++ b/README.md @@ -171,6 +171,7 @@ async function checkToken(token: string, baseUrl: string): Promise { it.each([ @@ -12,6 +13,16 @@ describe('buildBearerChallenge', () => { { error: 'insufficient_scope' as const, resourceMetadataUrl: METADATA }, `Bearer error="insufficient_scope", resource_metadata="${METADATA}"`, ], + [{ scopes: SCOPES }, 'Bearer scope="notes:read notes:write"'], + [ + { resourceMetadataUrl: METADATA, scopes: SCOPES }, + `Bearer resource_metadata="${METADATA}", scope="notes:read notes:write"`, + ], + [ + { error: 'insufficient_scope' as const, resourceMetadataUrl: METADATA, scopes: SCOPES }, + `Bearer error="insufficient_scope", resource_metadata="${METADATA}", scope="notes:read notes:write"`, + ], + [{ resourceMetadataUrl: METADATA, scopes: [] }, `Bearer resource_metadata="${METADATA}"`], ])('builds the challenge for %o', (options, expected) => { expect(buildBearerChallenge(options)).toBe(expected) }) diff --git a/src/host/challenge.ts b/src/host/challenge.ts index a89a0c8..043103c 100644 --- a/src/host/challenge.ts +++ b/src/host/challenge.ts @@ -6,16 +6,24 @@ export type BearerChallengeOptions = { error?: 'insufficient_scope' /** The resource's protected-resource metadata (RFC 9728), where the client finds how to authorise. */ resourceMetadataUrl?: string + /** + * The scopes a token needs for this resource, sent as RFC 6750's `scope` attribute. MCP clients + * request these first, ahead of the metadata's `scopes_supported`, so a client that can't find + * the resource's metadata still asks for the right ones. Left out when empty. + */ + scopes?: readonly string[] } /** The `WWW-Authenticate` value for a refused bearer token. */ export function buildBearerChallenge({ error, resourceMetadataUrl, + scopes, }: BearerChallengeOptions = {}): string { const params = [ ...(error ? [`error="${error}"`] : []), ...(resourceMetadataUrl ? [`resource_metadata="${resourceMetadataUrl}"`] : []), + ...(scopes && scopes.length > 0 ? [`scope="${scopes.join(' ')}"`] : []), ] return params.length > 0 ? `Bearer ${params.join(', ')}` : 'Bearer' }