Skip to content
Draft
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
6 changes: 6 additions & 0 deletions .changeset/preserve-oauth-resource-indicator-strings.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@modelcontextprotocol/client': patch
---

Preserve OAuth resource indicator strings from protected resource metadata
instead of normalizing them through `URL`.
24 changes: 13 additions & 11 deletions packages/client/src/client/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ export type AddClientAuthentication = (
metadata?: AuthorizationServerMetadata
) => void | Promise<void>;

export type OAuthResource = string | URL;

/**
* Context passed to {@linkcode AuthProvider.onUnauthorized} when the server
* responds with 401. Provides everything needed to refresh credentials.
Expand Down Expand Up @@ -348,7 +350,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<OAuthResource | undefined>;

/**
* If implemented, provides a way for the client to invalidate (e.g. delete) the specified
Expand Down Expand Up @@ -1185,7 +1187,7 @@ async function authInternal(
await provider.saveDiscoveryState?.(freshDiscoveryState);
}

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

// Save resource URL for providers that need it (e.g., CrossAppAccessProvider)
if (resource) {
Expand Down Expand Up @@ -1390,7 +1392,7 @@ export async function selectResourceURL(
serverUrl: string | URL,
provider: OAuthClientProvider,
resourceMetadata?: OAuthProtectedResourceMetadata
): Promise<URL | undefined> {
): Promise<OAuthResource | undefined> {
const defaultResource = resourceUrlFromServerUrl(serverUrl);

// If provider has custom validation, delegate to it
Expand All @@ -1408,7 +1410,7 @@ export async function selectResourceURL(
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);
return resourceMetadata.resource;
}

/**
Expand Down Expand Up @@ -1968,7 +1970,7 @@ export async function startAuthorization(
redirectUrl: string | URL;
scope?: string;
state?: string;
resource?: URL;
resource?: OAuthResource;
}
): Promise<{ authorizationUrl: URL; codeVerifier: string }> {
let authorizationUrl: URL;
Expand Down Expand Up @@ -2016,7 +2018,7 @@ export async function startAuthorization(
}

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

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

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

if (addClientAuthentication) {
Expand Down Expand Up @@ -2147,7 +2149,7 @@ export async function exchangeAuthorization(
iss?: string;
codeVerifier: string;
redirectUri: string | URL;
resource?: URL;
resource?: OAuthResource;
addClientAuthentication?: OAuthClientProvider['addClientAuthentication'];
fetchFn?: FetchLike;
}
Expand Down Expand Up @@ -2195,7 +2197,7 @@ export async function refreshAuthorization(
metadata?: AuthorizationServerMetadata;
clientInformation: OAuthClientInformationMixed;
refreshToken: string;
resource?: URL;
resource?: OAuthResource;
addClientAuthentication?: OAuthClientProvider['addClientAuthentication'];
fetchFn?: FetchLike;
}
Expand Down Expand Up @@ -2257,7 +2259,7 @@ export async function fetchToken(
fetchFn
}: {
metadata?: AuthorizationServerMetadata;
resource?: URL;
resource?: OAuthResource;
/** Authorization code for the default `authorization_code` grant flow */
authorizationCode?: string;
/**
Expand Down
44 changes: 43 additions & 1 deletion packages/client/test/client/auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import {
resolveAuthorizationCallbackParams,
resolveClientMetadata,
selectClientAuthMethod,
selectResourceURL,
startAuthorization,
UnauthorizedError,
validateAuthorizationResponseIssuer,
Expand Down Expand Up @@ -1580,7 +1581,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 @@ -1743,6 +1744,17 @@ describe('OAuth Authorization', () => {
});
});

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

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

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

it('preserves string resource indicators in the authorization URL', 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 @@ -1965,6 +1988,25 @@ describe('OAuth Authorization', () => {
expect(body.get('resource')).toBe('https://api.example.com/mcp-server');
});

it('preserves string resource indicators in the token request', 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 body = mockFetch.mock.calls[0]![1].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