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
9 changes: 6 additions & 3 deletions src/lib/mcp-oauth-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,7 @@ export class MCPOAuthProvider {
const authCode = await this.waitForAuthorizationCode();

// Step 8: Exchange authorization code for access token
const tokens = await this.exchangeCodeForTokens(authCode);
const tokens = await this.exchangeCodeForTokens(authCode, actualRedirectUri);

// Step 9: Store tokens
await writeTokens(this.serverUrlHash, tokens);
Expand Down Expand Up @@ -456,7 +456,10 @@ export class MCPOAuthProvider {
/**
* Exchange authorization code for access tokens
*/
private async exchangeCodeForTokens(code: string): Promise<WPTokens> {
private async exchangeCodeForTokens(
code: string,
redirectUri = this.config.redirectUri
): Promise<WPTokens> {
try {
const codeVerifier = await readTextFile(
this.serverUrlHash,
Expand All @@ -467,7 +470,7 @@ export class MCPOAuthProvider {
const tokenResponse = await exchangeAuthorizationCode(
this.config.tokenEndpoint!,
code,
this.config.redirectUri,
redirectUri,
this.config.clientId!,
codeVerifier,
CONFIG.OAUTH_RESOURCE_INDICATOR ? this.config.resource : undefined
Expand Down
22 changes: 22 additions & 0 deletions tests/unit/mcp-oauth-provider.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,4 +160,26 @@ describe('MCPOAuthProvider client registration', () => {
expect(scope.isDone()).toBe(false);
expect(provider.getConfig().clientId).toBe('env-client');
});

it('uses the selected callback port when exchanging the authorization code', async () => {
const { MCPOAuthProvider, generateServerUrlHash } = await loadModules();
const { writeTextFile } = await import('../../src/lib/persistent-auth-config.js');
const provider = new MCPOAuthProvider({
serverUrl,
clientId: 'dynamic-port-client',
scopes: ['read'],
});
(provider as any).config.tokenEndpoint = `${origin}/oauth/token`;

await writeTextFile(generateServerUrlHash(serverUrl), 'pkce_verifier.txt', 'a'.repeat(64));

const callback = 'http://127.0.0.1:49152/oauth/callback';
const exchange = nock(origin)
.post('/oauth/token', body => body.redirect_uri === callback)
.reply(200, { access_token: 'access-token', token_type: 'Bearer', expires_in: 3600 });

await (provider as any).exchangeCodeForTokens('authorization-code', callback);

expect(exchange.isDone()).toBe(true);
});
});