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
5 changes: 5 additions & 0 deletions .changeset/propagate-token-save-errors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@modelcontextprotocol/client': patch
---

Propagate token persistence errors after a successful OAuth refresh instead of silently falling back to a new authorization flow.
11 changes: 7 additions & 4 deletions packages/client/src/client/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -763,19 +763,17 @@ async function authInternal(

// Handle token refresh or new authorization
if (tokens?.refresh_token) {
let newTokens: OAuthTokens | undefined;
try {
// Attempt to refresh the token
const newTokens = await refreshAuthorization(authorizationServerUrl, {
newTokens = await refreshAuthorization(authorizationServerUrl, {
metadata,
clientInformation,
refreshToken: tokens.refresh_token,
resource,
addClientAuthentication: provider.addClientAuthentication,
fetchFn
});

await provider.saveTokens(newTokens);
return 'AUTHORIZED';
} catch (error) {
// If this is a ServerError, or an unknown type, log it out and try to continue. Otherwise, escalate so we can fix things and retry.
if (!(error instanceof OAuthError) || error.code === OAuthErrorCode.ServerError) {
Expand All @@ -785,6 +783,11 @@ async function authInternal(
throw error;
}
}

if (newTokens) {
await provider.saveTokens(newTokens);
return 'AUTHORIZED';
}
}

const state = provider.state ? await provider.state() : undefined;
Expand Down
52 changes: 52 additions & 0 deletions packages/client/test/client/auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2158,6 +2158,58 @@ describe('OAuth Authorization', () => {
vi.clearAllMocks();
});

it('propagates saveTokens errors after a successful refresh', async () => {
const saveError = new Error('failed to persist refreshed tokens');
const provider: OAuthClientProvider = {
get redirectUrl() {
return 'http://localhost:3000/callback';
},
get clientMetadata() {
return {
redirect_uris: ['http://localhost:3000/callback'],
client_name: 'Test Client'
};
},
discoveryState: vi.fn().mockResolvedValue({
authorizationServerUrl: 'https://auth.example.com',
authorizationServerMetadata: {
issuer: 'https://auth.example.com',
authorization_endpoint: 'https://auth.example.com/authorize',
token_endpoint: 'https://auth.example.com/token',
response_types_supported: ['code'],
code_challenge_methods_supported: ['S256']
}
}),
clientInformation: vi.fn().mockResolvedValue({
client_id: 'test-client-id',
client_secret: 'test-client-secret'
}),
tokens: vi.fn().mockResolvedValue({
access_token: 'expired-token',
refresh_token: 'refresh-token',
token_type: 'bearer'
}),
saveTokens: vi.fn().mockRejectedValue(saveError),
redirectToAuthorization: vi.fn(),
saveCodeVerifier: vi.fn(),
codeVerifier: vi.fn()
};

mockFetch.mockResolvedValue({
ok: true,
status: 200,
json: async () => ({
access_token: 'new-token',
token_type: 'bearer',
expires_in: 3600,
refresh_token: 'new-refresh-token'
})
});

await expect(auth(provider, { serverUrl: 'https://resource.example.com' })).rejects.toThrow(saveError);
expect(provider.redirectToAuthorization).not.toHaveBeenCalled();
});

it('performs client_credentials with private_key_jwt when provider has addClientAuthentication', async () => {
// Arrange: metadata discovery for PRM and AS
mockFetch.mockImplementation(url => {
Expand Down
Loading