|
| 1 | +import { |
| 2 | + auth, |
| 3 | + extractResourceMetadataUrl, |
| 4 | + UnauthorizedError |
| 5 | +} from '@modelcontextprotocol/sdk/client/auth.js'; |
| 6 | +import type { FetchLike } from '@modelcontextprotocol/sdk/shared/transport.js'; |
| 7 | +import type { Middleware } from '@modelcontextprotocol/sdk/client/middleware.js'; |
| 8 | +import { ConformanceOAuthProvider } from './ConformanceOAuthProvider'; |
| 9 | + |
| 10 | +export const handle401 = async ( |
| 11 | + response: Response, |
| 12 | + provider: ConformanceOAuthProvider, |
| 13 | + next: FetchLike, |
| 14 | + serverUrl: string | URL |
| 15 | +): Promise<void> => { |
| 16 | + const resourceMetadataUrl = extractResourceMetadataUrl(response); |
| 17 | + |
| 18 | + let result = await auth(provider, { |
| 19 | + serverUrl, |
| 20 | + resourceMetadataUrl, |
| 21 | + fetchFn: next |
| 22 | + }); |
| 23 | + |
| 24 | + if (result === 'REDIRECT') { |
| 25 | + // Ordinarily, we'd wait for the callback to be handled here, |
| 26 | + // but in our conformance provider, we get the authorization code |
| 27 | + // during the redirect handling, so we can go straight to |
| 28 | + // retrying the auth step. |
| 29 | + // await provider.waitForCallback(); |
| 30 | + |
| 31 | + const authorizationCode = await provider.getAuthCode(); |
| 32 | + |
| 33 | + // TODO: this retry logic should be incorporated into the typescript SDK |
| 34 | + result = await auth(provider, { |
| 35 | + serverUrl, |
| 36 | + resourceMetadataUrl, |
| 37 | + authorizationCode, |
| 38 | + fetchFn: next |
| 39 | + }); |
| 40 | + if (result !== 'AUTHORIZED') { |
| 41 | + throw new UnauthorizedError( |
| 42 | + `Authentication failed with result: ${result}` |
| 43 | + ); |
| 44 | + } |
| 45 | + } |
| 46 | +}; |
| 47 | +/** |
| 48 | + * Creates a fetch wrapper that handles OAuth authentication with retry logic. |
| 49 | + * |
| 50 | + * Unlike the SDK's withOAuth, this version: |
| 51 | + * - Automatically handles authorization redirects by retrying with fresh tokens |
| 52 | + * - Does not throw UnauthorizedError on redirect, but instead retries |
| 53 | + * - Calls next() instead of throwing for redirect-based auth |
| 54 | + * |
| 55 | + * @param provider - OAuth client provider for authentication |
| 56 | + * @param baseUrl - Base URL for OAuth server discovery (defaults to request URL domain) |
| 57 | + * @returns A fetch middleware function |
| 58 | + */ |
| 59 | +export const withOAuthRetry = ( |
| 60 | + clientName: string, |
| 61 | + baseUrl?: string | URL, |
| 62 | + handle401Fn: typeof handle401 = handle401 |
| 63 | +): Middleware => { |
| 64 | + const provider = new ConformanceOAuthProvider( |
| 65 | + 'http://localhost:3000/callback', |
| 66 | + { |
| 67 | + client_name: clientName, |
| 68 | + redirect_uris: ['http://localhost:3000/callback'] |
| 69 | + } |
| 70 | + ); |
| 71 | + return (next: FetchLike) => { |
| 72 | + return async ( |
| 73 | + input: string | URL, |
| 74 | + init?: RequestInit |
| 75 | + ): Promise<Response> => { |
| 76 | + const makeRequest = async (): Promise<Response> => { |
| 77 | + const headers = new Headers(init?.headers); |
| 78 | + |
| 79 | + // Add authorization header if tokens are available |
| 80 | + const tokens = await provider.tokens(); |
| 81 | + if (tokens) { |
| 82 | + headers.set('Authorization', `Bearer ${tokens.access_token}`); |
| 83 | + } |
| 84 | + |
| 85 | + return await next(input, { ...init, headers }); |
| 86 | + }; |
| 87 | + |
| 88 | + let response = await makeRequest(); |
| 89 | + |
| 90 | + // Handle 401 responses by attempting re-authentication |
| 91 | + if (response.status === 401) { |
| 92 | + const serverUrl = |
| 93 | + baseUrl || |
| 94 | + (typeof input === 'string' ? new URL(input).origin : input.origin); |
| 95 | + await handle401Fn(response, provider, next, serverUrl); |
| 96 | + |
| 97 | + response = await makeRequest(); |
| 98 | + } |
| 99 | + |
| 100 | + // If we still have a 401 after re-auth attempt, throw an error |
| 101 | + if (response.status === 401) { |
| 102 | + const url = typeof input === 'string' ? input : input.toString(); |
| 103 | + throw new UnauthorizedError(`Authentication failed for ${url}`); |
| 104 | + } |
| 105 | + |
| 106 | + return response; |
| 107 | + }; |
| 108 | + }; |
| 109 | +}; |
0 commit comments