Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@modelcontextprotocol/client": patch
---

fix(client): preserve OAuth resource metadata indicator
32 changes: 19 additions & 13 deletions packages/client/src/client/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ export interface OAuthClientProvider {
*
* Implementations must verify the returned resource matches the MCP server.
*/
validateResourceURL?(serverUrl: string | URL, resource?: string): Promise<URL | undefined>;
validateResourceURL?(serverUrl: string | URL, resource?: string): Promise<OAuthResourceIndicator | undefined>;

/**
* If implemented, provides a way for the client to invalidate (e.g. delete) the specified
Expand Down Expand Up @@ -384,6 +384,11 @@ function isClientAuthMethod(method: string): method is ClientAuthMethod {

const AUTHORIZATION_CODE_RESPONSE_TYPE = 'code';
const AUTHORIZATION_CODE_CHALLENGE_METHOD = 'S256';
export type OAuthResourceIndicator = string | URL;

function serializeResourceIndicator(resource: OAuthResourceIndicator): string {
return typeof resource === 'string' ? resource : resource.href;
}

/**
* Determines the best client authentication method to use based on server support and client configuration.
Expand Down Expand Up @@ -684,11 +689,11 @@ async function authInternal(
// Save authorization server URL for providers that need it (e.g., CrossAppAccessProvider)
await provider.saveAuthorizationServerUrl?.(String(authorizationServerUrl));

const resource: URL | undefined = await selectResourceURL(serverUrl, provider, resourceMetadata);
const resource: OAuthResourceIndicator | undefined = await selectResourceURL(serverUrl, provider, resourceMetadata);

// Save resource URL for providers that need it (e.g., CrossAppAccessProvider)
if (resource) {
await provider.saveResourceUrl?.(String(resource));
await provider.saveResourceUrl?.(serializeResourceIndicator(resource));
}

// Scope selection used consistently for DCR and the authorization request.
Expand Down Expand Up @@ -844,7 +849,7 @@ export async function selectResourceURL(
serverUrl: string | URL,
provider: OAuthClientProvider,
resourceMetadata?: OAuthProtectedResourceMetadata
): Promise<URL | undefined> {
): Promise<OAuthResourceIndicator | undefined> {
const defaultResource = resourceUrlFromServerUrl(serverUrl);

// If provider has custom validation, delegate to it
Expand All @@ -861,8 +866,9 @@ export async function selectResourceURL(
if (!checkResourceAllowed({ requestedResource: defaultResource, configuredResource: resourceMetadata.resource })) {
throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`);
}
// Prefer the resource from metadata since it's what the server is telling us to request
return new URL(resourceMetadata.resource);
// Prefer the exact resource indicator from metadata since it's what the server is telling us to request.
// Constructing a URL would normalize pathless origins by appending "/", which can change the audience.
return resourceMetadata.resource;
}

/**
Expand Down Expand Up @@ -1376,7 +1382,7 @@ export async function startAuthorization(
redirectUrl: string | URL;
scope?: string;
state?: string;
resource?: URL;
resource?: OAuthResourceIndicator;
}
): Promise<{ authorizationUrl: URL; codeVerifier: string }> {
let authorizationUrl: URL;
Expand Down Expand Up @@ -1424,7 +1430,7 @@ export async function startAuthorization(
}

if (resource) {
authorizationUrl.searchParams.set('resource', resource.href);
authorizationUrl.searchParams.set('resource', serializeResourceIndicator(resource));
}

return { authorizationUrl, codeVerifier };
Expand Down Expand Up @@ -1472,7 +1478,7 @@ export async function executeTokenRequest(
tokenRequestParams: URLSearchParams;
clientInformation?: OAuthClientInformationMixed;
addClientAuthentication?: OAuthClientProvider['addClientAuthentication'];
resource?: URL;
resource?: OAuthResourceIndicator;
fetchFn?: FetchLike;
}
): Promise<OAuthTokens> {
Expand All @@ -1484,7 +1490,7 @@ export async function executeTokenRequest(
});

if (resource) {
tokenRequestParams.set('resource', resource.href);
tokenRequestParams.set('resource', serializeResourceIndicator(resource));
}

if (addClientAuthentication) {
Expand Down Expand Up @@ -1548,7 +1554,7 @@ export async function exchangeAuthorization(
authorizationCode: string;
codeVerifier: string;
redirectUri: string | URL;
resource?: URL;
resource?: OAuthResourceIndicator;
addClientAuthentication?: OAuthClientProvider['addClientAuthentication'];
fetchFn?: FetchLike;
}
Expand Down Expand Up @@ -1590,7 +1596,7 @@ export async function refreshAuthorization(
metadata?: AuthorizationServerMetadata;
clientInformation: OAuthClientInformationMixed;
refreshToken: string;
resource?: URL;
resource?: OAuthResourceIndicator;
addClientAuthentication?: OAuthClientProvider['addClientAuthentication'];
fetchFn?: FetchLike;
}
Expand Down Expand Up @@ -1651,7 +1657,7 @@ export async function fetchToken(
fetchFn
}: {
metadata?: AuthorizationServerMetadata;
resource?: URL;
resource?: OAuthResourceIndicator;
/** Authorization code for the default `authorization_code` grant flow */
authorizationCode?: string;
/** Optional scope parameter from auth() options */
Expand Down
45 changes: 44 additions & 1 deletion packages/client/test/client/auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
refreshAuthorization,
registerClient,
selectClientAuthMethod,
selectResourceURL,
startAuthorization,
validateClientMetadataUrl
} from '../../src/client/auth.js';
Expand Down Expand Up @@ -1301,7 +1302,7 @@ describe('OAuth Authorization', () => {
const tokenCall = mockFetch.mock.calls.find(call => call[0].toString().includes('/token'));
expect(tokenCall).toBeDefined();
const body = tokenCall![1].body as URLSearchParams;
expect(body.get('resource')).toBe('https://resource.example.com/');
expect(body.get('resource')).toBe('https://resource.example.com');
});

it('re-saves enriched state when partial cache is supplemented with fetched metadata', async () => {
Expand Down Expand Up @@ -1464,6 +1465,17 @@ describe('OAuth Authorization', () => {
});
});

describe('selectResourceURL', () => {
it('preserves the exact protected resource metadata resource indicator', async () => {
const resource = await selectResourceURL('https://api.example.com/mcp-server', {} as OAuthClientProvider, {
resource: 'https://api.example.com',
authorization_servers: ['https://auth.example.com']
});

expect(resource).toBe('https://api.example.com');
});
});

describe('startAuthorization', () => {
const validMetadata = {
issuer: 'https://auth.example.com',
Expand Down Expand Up @@ -1508,6 +1520,17 @@ describe('OAuth Authorization', () => {
expect(codeVerifier).toBe('test_verifier');
});

it('preserves string resource indicators exactly', async () => {
const { authorizationUrl } = await startAuthorization('https://auth.example.com', {
metadata: undefined,
clientInformation: validClientInfo,
redirectUrl: 'http://localhost:3000/callback',
resource: 'https://api.example.com'
});

expect(authorizationUrl.searchParams.get('resource')).toBe('https://api.example.com');
});

it('includes scope parameter when provided', async () => {
const { authorizationUrl } = await startAuthorization('https://auth.example.com', {
clientInformation: validClientInfo,
Expand Down Expand Up @@ -1686,6 +1709,26 @@ describe('OAuth Authorization', () => {
expect(body.get('resource')).toBe('https://api.example.com/mcp-server');
});

it('preserves string resource indicators exactly in token requests', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => validTokens
});

await exchangeAuthorization('https://auth.example.com', {
clientInformation: validClientInfo,
authorizationCode: 'code123',
codeVerifier: 'verifier123',
redirectUri: 'http://localhost:3000/callback',
resource: 'https://api.example.com'
});

const options = mockFetch.mock.calls[0]![1];
const body = options.body as URLSearchParams;
expect(body.get('resource')).toBe('https://api.example.com');
});

it('allows for string "expires_in" values', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
Expand Down
Loading