MCPcopy Create free account
hub / github.com/modelcontextprotocol/typescript-sdk / withOAuth

Function withOAuth

src/client/middleware.ts:37–95  ·  view source on GitHub ↗
(provider: OAuthClientProvider, baseUrl?: string | URL)

Source from the content-addressed store, hash-verified

35 */
36export const withOAuth =
37 (provider: OAuthClientProvider, baseUrl?: string | URL): Middleware =>
38 next => {
39 return async (input, init) => {
40 const makeRequest = async (): Promise<Response> => {
41 const headers = new Headers(init?.headers);
42
43 // Add authorization header if tokens are available
44 const tokens = await provider.tokens();
45 if (tokens) {
46 headers.set('Authorization', `Bearer ${tokens.access_token}`);
47 }
48
49 return await next(input, { ...init, headers });
50 };
51
52 let response = await makeRequest();
53
54 // Handle 401 responses by attempting re-authentication
55 if (response.status === 401) {
56 try {
57 const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
58
59 // Use provided baseUrl or extract from request URL
60 const serverUrl = baseUrl || (typeof input === 'string' ? new URL(input).origin : input.origin);
61
62 const result = await auth(provider, {
63 serverUrl,
64 resourceMetadataUrl,
65 scope,
66 fetchFn: next
67 });
68
69 if (result === 'REDIRECT') {
70 throw new UnauthorizedError('Authentication requires user authorization - redirect initiated');
71 }
72
73 if (result !== 'AUTHORIZED') {
74 throw new UnauthorizedError(`Authentication failed with result: ${result}`);
75 }
76
77 // Retry the request with fresh tokens
78 response = await makeRequest();
79 } catch (error) {
80 if (error instanceof UnauthorizedError) {
81 throw error;
82 }
83 throw new UnauthorizedError(`Failed to re-authenticate: ${error instanceof Error ? error.message : String(error)}`);
84 }
85 }
86
87 // If we still have a 401 after re-auth attempt, throw an error
88 if (response.status === 401) {
89 const url = typeof input === 'string' ? input : input.toString();
90 throw new UnauthorizedError(`Authentication failed for ${url}`);
91 }
92
93 return response;
94 };

Callers 1

middleware.test.tsFile · 0.85

Calls 4

authFunction · 0.85
toStringMethod · 0.80
makeRequestFunction · 0.70

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…