|
| 1 | +import { URL } from "node:url"; |
| 2 | +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; |
| 3 | +import { |
| 4 | + OAuthClientInformation, |
| 5 | + OAuthClientInformationFull, |
| 6 | + OAuthClientMetadata, |
| 7 | + OAuthTokens, |
| 8 | +} from "@modelcontextprotocol/sdk/shared/auth.js"; |
| 9 | +import { |
| 10 | + OAuthClientProvider, |
| 11 | + discoverAuthorizationServerMetadata, |
| 12 | + discoverOAuthProtectedResourceMetadata, |
| 13 | + extractResourceMetadataUrl, |
| 14 | +} from "@modelcontextprotocol/sdk/client/auth.js"; |
| 15 | + |
| 16 | +export async function createAutomatedOAuthTransport( |
| 17 | + serverUrl: string, |
| 18 | + clientId: string, |
| 19 | + clientSecret: string |
| 20 | +): Promise<StreamableHTTPClientTransport> { |
| 21 | + const scope = await discoverScope(serverUrl); |
| 22 | + |
| 23 | + const clientMetadata: OAuthClientMetadata = { |
| 24 | + client_name: "MCP Client", |
| 25 | + redirect_uris: [], |
| 26 | + grant_types: ["client_credentials"], |
| 27 | + response_types: [], |
| 28 | + token_endpoint_auth_method: "client_secret_basic", |
| 29 | + scope, |
| 30 | + }; |
| 31 | + |
| 32 | + const oauthProvider = new AutomatedOAuthClientProvider(clientMetadata, clientId, clientSecret); |
| 33 | + await performClientCredentialsFlow(serverUrl, oauthProvider); |
| 34 | + |
| 35 | + return new StreamableHTTPClientTransport(new URL(serverUrl), { |
| 36 | + authProvider: oauthProvider, |
| 37 | + }); |
| 38 | +} |
| 39 | + |
| 40 | +async function discoverScope(serverUrl: string): Promise<string> { |
| 41 | + const response = await fetch(serverUrl, { |
| 42 | + method: "POST", |
| 43 | + headers: { "Content-Type": "application/json" }, |
| 44 | + body: JSON.stringify({ jsonrpc: "2.0", method: "ping", id: 1 }), |
| 45 | + }); |
| 46 | + const resourceMetadataUrl = extractResourceMetadataUrl(response); |
| 47 | + const resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl }); |
| 48 | + return resourceMetadata.scopes_supported?.join(" ") || ""; |
| 49 | +} |
| 50 | + |
| 51 | +async function performClientCredentialsFlow(serverUrl: string, oauthProvider: AutomatedOAuthClientProvider): Promise<void> { |
| 52 | + if (oauthProvider.tokens()?.access_token) return; |
| 53 | + |
| 54 | + const response = await fetch(serverUrl, { |
| 55 | + method: "POST", |
| 56 | + headers: { "Content-Type": "application/json" }, |
| 57 | + body: JSON.stringify({ jsonrpc: "2.0", method: "ping", id: 1 }), |
| 58 | + }); |
| 59 | + const resourceMetadataUrl = extractResourceMetadataUrl(response); |
| 60 | + const resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl }); |
| 61 | + const authServerUrl = resourceMetadata.authorization_servers?.[0]; |
| 62 | + if (!authServerUrl) throw new Error("No authorization server found"); |
| 63 | + |
| 64 | + const metadata = await discoverAuthorizationServerMetadata(authServerUrl); |
| 65 | + if (!metadata?.token_endpoint) throw new Error("No token endpoint found"); |
| 66 | + |
| 67 | + const clientInfo = oauthProvider.clientInformation(); |
| 68 | + if (!clientInfo) throw new Error("No client information available"); |
| 69 | + |
| 70 | + const params = new URLSearchParams({ |
| 71 | + grant_type: "client_credentials", |
| 72 | + client_id: clientInfo.client_id, |
| 73 | + client_secret: clientInfo.client_secret!, |
| 74 | + scope: oauthProvider.clientMetadata.scope || "", |
| 75 | + }); |
| 76 | + |
| 77 | + const tokenResponse = await fetch(metadata.token_endpoint, { |
| 78 | + method: "POST", |
| 79 | + headers: { "Content-Type": "application/x-www-form-urlencoded" }, |
| 80 | + body: params, |
| 81 | + }); |
| 82 | + |
| 83 | + if (!tokenResponse.ok) throw new Error(`Token request failed: ${tokenResponse.status}`); |
| 84 | + oauthProvider.saveTokens(await tokenResponse.json()); |
| 85 | +} |
| 86 | + |
| 87 | +class AutomatedOAuthClientProvider implements OAuthClientProvider { |
| 88 | + private _clientInformation: OAuthClientInformationFull; |
| 89 | + private _tokens?: OAuthTokens; |
| 90 | + |
| 91 | + constructor( |
| 92 | + private readonly _clientMetadata: OAuthClientMetadata, |
| 93 | + clientId: string, |
| 94 | + clientSecret: string |
| 95 | + ) { |
| 96 | + this._clientInformation = { |
| 97 | + client_id: clientId, |
| 98 | + client_secret: clientSecret, |
| 99 | + ...this._clientMetadata, |
| 100 | + }; |
| 101 | + } |
| 102 | + |
| 103 | + get redirectUrl(): string | URL { |
| 104 | + return ""; |
| 105 | + } |
| 106 | + |
| 107 | + get clientMetadata(): OAuthClientMetadata { |
| 108 | + return this._clientMetadata; |
| 109 | + } |
| 110 | + |
| 111 | + clientInformation(): OAuthClientInformation | undefined { |
| 112 | + return this._clientInformation; |
| 113 | + } |
| 114 | + |
| 115 | + saveClientInformation(clientInformation: OAuthClientInformationFull): void { |
| 116 | + this._clientInformation = clientInformation; |
| 117 | + } |
| 118 | + |
| 119 | + tokens(): OAuthTokens | undefined { |
| 120 | + return this._tokens; |
| 121 | + } |
| 122 | + |
| 123 | + saveTokens(tokens: OAuthTokens): void { |
| 124 | + this._tokens = tokens; |
| 125 | + } |
| 126 | + |
| 127 | + redirectToAuthorization(): void { |
| 128 | + throw new Error("redirectToAuthorization should not be called in automated OAuth flow"); |
| 129 | + } |
| 130 | + |
| 131 | + saveCodeVerifier(): void { |
| 132 | + throw new Error("saveCodeVerifier should not be called in automated OAuth flow"); |
| 133 | + } |
| 134 | + |
| 135 | + codeVerifier(): string { |
| 136 | + throw new Error("codeVerifier should not be called in automated OAuth flow"); |
| 137 | + } |
| 138 | +} |
0 commit comments