| 1 | import { |
| 2 | OAuthClientProvider, |
| 3 | auth, |
| 4 | } from "@modelcontextprotocol/sdk/client/auth.js"; |
| 5 | import { |
| 6 | OAuthClientInformationFull, |
| 7 | OAuthClientInformationSchema, |
| 8 | OAuthTokens, |
| 9 | OAuthTokensSchema, |
| 10 | } from "@modelcontextprotocol/sdk/shared/auth.js"; |
| 11 | import { IDE } from "../.."; |
| 12 | |
| 13 | import http from "http"; |
| 14 | import url from "url"; |
| 15 | import { v4 as uuidv4 } from "uuid"; |
| 16 | import { GlobalContext, GlobalContextType } from "../../util/GlobalContext"; |
| 17 | |
| 18 | // Use a Map to support concurrent authentications for different servers |
| 19 | interface MCPOauthContext { |
| 20 | serverId: string; |
| 21 | ide: IDE; |
| 22 | state?: string; |
| 23 | } |
| 24 | const authenticatingContexts = new Map<string, MCPOauthContext>(); |
| 25 | |
| 26 | // Map state parameters to server URLs for OAuth callback matching |
| 27 | const stateToServerUrl = new Map<string, string>(); |
| 28 | |
| 29 | const PORT = 3000; |
| 30 | |
| 31 | let serverInstance: http.Server | null = null; |
| 32 | |
| 33 | const createServerForOAuth = () => |
| 34 | http.createServer((req, res) => { |
| 35 | try { |
| 36 | if (!req.url) { |
| 37 | throw new Error("no url found"); |
| 38 | } |
| 39 | |
| 40 | const parsedUrl = url.parse(req.url, true); |
| 41 | if (!parsedUrl.query["code"]) { |
| 42 | throw new Error("no query params found"); |
| 43 | } |
| 44 | |
| 45 | const code = parsedUrl.query["code"] as string; |
| 46 | const state = parsedUrl.query["state"] as string | undefined; |
| 47 | |
| 48 | void handleMCPOauthCode(code, state); |
| 49 | |
| 50 | const html = ` |
| 51 | <!DOCTYPE html> |
| 52 | <html> |
| 53 | <head><title>Authentication Complete</title></head> |
| 54 | <body>Authentication Complete. You can close this page now.</body> |
| 55 | </html>`; |
| 56 | |
| 57 | res.writeHead(200, { |
| 58 | "Content-Type": "text/html", |
| 59 | }); |
| 60 | res.end(html); |
| 61 | } catch (error) { |
| 62 | res.writeHead(400, { "Content-Type": "text/plain" }); |
| 63 | res.end(`Unexpected redirect error: ${(error as Error).message}`); |
| 64 | } |
| 65 | }); |
| 66 | |
| 67 | type MCPOauthStorage = GlobalContextType["mcpOauthStorage"][string]; |
| 68 | type MCPOauthStorageKey = keyof MCPOauthStorage; |
| 69 | |
| 70 | class MCPConnectionOauthProvider implements OAuthClientProvider { |
| 71 | private globalContext: GlobalContext; |
| 72 | private _redirectUrl: string; |
| 73 | private _redirectUrlInitialized: Promise<void>; |
| 74 | |
| 75 | constructor( |
| 76 | public oauthServerUrl: string, |
| 77 | private ide: IDE, |
| 78 | ) { |
| 79 | this.globalContext = new GlobalContext(); |
| 80 | // Set default redirect URL immediately for synchronous access |
| 81 | this._redirectUrl = `http://localhost:${PORT}`; |
| 82 | // Initialize actual redirect URL asynchronously |
| 83 | this._redirectUrlInitialized = this._initializeRedirectUrl(); |
| 84 | } |
| 85 | |
| 86 | private async _initializeRedirectUrl(): Promise<void> { |
| 87 | try { |
| 88 | // If IDE supports getExternalUri (VS Code extension), use it for dynamic redirect URI |
| 89 | if (this.ide.getExternalUri) { |
| 90 | const localUri = `http://localhost:${PORT}`; |
| 91 | const externalUri = await this.ide.getExternalUri(localUri); |
| 92 | this._redirectUrl = externalUri; |
| 93 | } |
| 94 | // Otherwise keep the default localhost URL |
| 95 | } catch (error) { |
| 96 | console.error("Failed to initialize redirect URL:", error); |
| 97 | // Keep default URL on error |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | get redirectUrl() { |
| 102 | // Always return a valid URL, even if initialization is pending |
| 103 | return this._redirectUrl; |
| 104 | } |
| 105 | |
| 106 | getRedirectUrlWithState(state: string): string { |
| 107 | // Add state parameter to redirect URL |
| 108 | const urlObj = new URL(this._redirectUrl); |
| 109 | urlObj.searchParams.set("state", state); |
| 110 | return urlObj.toString(); |
| 111 | } |
| 112 | |
| 113 | async ensureRedirectUrl(): Promise<string> { |
| 114 | // Wait for initialization to complete before returning |
| 115 | await this._redirectUrlInitialized; |
| 116 | return this._redirectUrl; |
| 117 | } |
| 118 | |
| 119 | get clientMetadata() { |
| 120 | // Generate state parameter if needed |
| 121 | const state = authenticatingContexts.get(this.oauthServerUrl)?.state; |
| 122 | const redirectUri = state |
| 123 | ? this.getRedirectUrlWithState(state) |
| 124 | : this.redirectUrl; |
| 125 | |
| 126 | return { |
| 127 | redirect_uris: [redirectUri], |
| 128 | token_endpoint_auth_method: "none", |
| 129 | grant_types: ["authorization_code", "refresh_token"], |
| 130 | response_types: ["code"], |
| 131 | client_name: "Continue Dev, Inc", // get this from package.json? |
| 132 | client_uri: "https://continue.dev", // get this from package.json? |
| 133 | }; |
| 134 | } |
| 135 | |
| 136 | private _getOauthStorage<K extends MCPOauthStorageKey>(key: K) { |
| 137 | return this.globalContext.get("mcpOauthStorage")?.[this.oauthServerUrl]?.[ |
| 138 | key |
| 139 | ]; |
| 140 | } |
| 141 | |
| 142 | private _updateOauthStorage<K extends MCPOauthStorageKey>( |
| 143 | key: K, |
| 144 | value: MCPOauthStorage[K], |
| 145 | ) { |
| 146 | const existingStorage = this.globalContext.get("mcpOauthStorage") ?? {}; |
| 147 | const existingServerStorage = existingStorage[this.oauthServerUrl] ?? {}; |
| 148 | |
| 149 | this.globalContext.update("mcpOauthStorage", { |
| 150 | ...existingStorage, |
| 151 | [this.oauthServerUrl]: { |
| 152 | ...existingServerStorage, |
| 153 | [key]: value, |
| 154 | }, |
| 155 | }); |
| 156 | } |
| 157 | |
| 158 | private _clearOauthStorage() { |
| 159 | const existingStorage = this.globalContext.get("mcpOauthStorage") ?? {}; |
| 160 | delete existingStorage[this.oauthServerUrl]; |
| 161 | this.globalContext.update("mcpOauthStorage", existingStorage); |
| 162 | } |
| 163 | |
| 164 | saveClientInformation(clientInformation: OAuthClientInformationFull) { |
| 165 | this._updateOauthStorage("clientInformation", clientInformation); |
| 166 | } |
| 167 | |
| 168 | async clientInformation() { |
| 169 | const existingClientInformation = |
| 170 | this._getOauthStorage("clientInformation"); |
| 171 | if (!existingClientInformation) { |
| 172 | return undefined; |
| 173 | } |
| 174 | return await OAuthClientInformationSchema.parseAsync( |
| 175 | existingClientInformation, |
| 176 | ); |
| 177 | } |
| 178 | |
| 179 | async tokens() { |
| 180 | const existingTokens = this._getOauthStorage("tokens"); |
| 181 | if (!existingTokens) { |
| 182 | return undefined; |
| 183 | } |
| 184 | return await OAuthTokensSchema.parseAsync(existingTokens); |
| 185 | } |
| 186 | |
| 187 | saveTokens(tokens: OAuthTokens) { |
| 188 | this._updateOauthStorage("tokens", tokens); |
| 189 | } |
| 190 | |
| 191 | codeVerifier(): string | Promise<string> { |
| 192 | const existingCodeVerifier = this._getOauthStorage("codeVerifier"); |
| 193 | if (!existingCodeVerifier) { |
| 194 | return ""; |
| 195 | } |
| 196 | return existingCodeVerifier; |
| 197 | } |
| 198 | |
| 199 | saveCodeVerifier(codeVerifier: string) { |
| 200 | this._updateOauthStorage("codeVerifier", codeVerifier); |
| 201 | } |
| 202 | |
| 203 | clear() { |
| 204 | this._clearOauthStorage(); |
| 205 | } |
| 206 | |
| 207 | async redirectToAuthorization(authorizationUrl: URL) { |
| 208 | // Ensure redirect URL is initialized before proceeding |
| 209 | await this.ensureRedirectUrl(); |
| 210 | |
| 211 | // Only create and start local server if using localhost redirect |
| 212 | // For web-based VS Code, the redirect will be handled by VS Code's built-in mechanism |
| 213 | if (!this.ide.getExternalUri || this._redirectUrl.includes("localhost")) { |
| 214 | if (!serverInstance) { |
| 215 | serverInstance = createServerForOAuth(); |
| 216 | } |
| 217 | if (!serverInstance.listening) { |
| 218 | await new Promise<void>((resolve, reject) => { |
| 219 | serverInstance!.listen(PORT, () => { |
| 220 | console.debug( |
| 221 | `Server started for MCP Oauth process at http://localhost:${PORT}/`, |
| 222 | ); |
| 223 | resolve(); |
| 224 | }); |
| 225 | serverInstance!.on("error", reject); |
| 226 | }); |
| 227 | } |
| 228 | } |
| 229 | await this.ide.openUrl(authorizationUrl.toString()); |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | export async function getOauthToken(mcpServerUrl: string, ide: IDE) { |
| 234 | const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide); |
| 235 | const tokens = await authProvider.tokens(); |
| 236 | return tokens?.access_token; |
| 237 | } |
| 238 | |
| 239 | /** |
| 240 | * checks if the authentication is already done for the current server |
| 241 | * if not, starts the authentication process by opening a webpage url |
| 242 | */ |
| 243 | export async function performAuth(serverId: string, url: string, ide: IDE) { |
| 244 | const authProvider = new MCPConnectionOauthProvider(url, ide); |
| 245 | // Ensure redirect URL is ready before starting auth |
| 246 | await authProvider.ensureRedirectUrl(); |
| 247 | |
| 248 | // Generate a unique state parameter for this auth flow |
| 249 | const state = uuidv4(); |
| 250 | |
| 251 | // Store context for this specific server with state |
| 252 | authenticatingContexts.set(url, { |
| 253 | serverId, |
| 254 | ide, |
| 255 | state, |
| 256 | }); |
| 257 | |
| 258 | // Map state to server URL for callback matching |
| 259 | stateToServerUrl.set(state, url); |
| 260 | |
| 261 | try { |
| 262 | return await auth(authProvider, { |
| 263 | serverUrl: url, |
| 264 | }); |
| 265 | } catch (error) { |
| 266 | // Clean up on error |
| 267 | authenticatingContexts.delete(url); |
| 268 | stateToServerUrl.delete(state); |
| 269 | throw error; |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | /** |
| 274 | * handle the authentication code received from the oauth redirect |
| 275 | */ |
| 276 | async function handleMCPOauthCode(authorizationCode: string, state?: string) { |
| 277 | let serverUrl: string | undefined; |
| 278 | let context: MCPOauthContext | undefined; |
| 279 | |
| 280 | if (state) { |
| 281 | // Use state parameter to find the correct server |
| 282 | serverUrl = stateToServerUrl.get(state); |
| 283 | if (serverUrl) { |
| 284 | context = authenticatingContexts.get(serverUrl); |
| 285 | } |
| 286 | } else { |
| 287 | // Fallback: if no state or single context, use the first one |
| 288 | const contexts = Array.from(authenticatingContexts.entries()); |
| 289 | if (contexts.length === 1) { |
| 290 | [serverUrl, context] = contexts[0]; |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | if (!context || !serverUrl) { |
| 295 | console.error("No matching authenticating context found for state:", state); |
| 296 | return; |
| 297 | } |
| 298 | |
| 299 | const { ide, serverId } = context; |
| 300 | |
| 301 | try { |
| 302 | if (!serverUrl) { |
| 303 | throw new Error("No MCP server url found for authentication"); |
| 304 | } |
| 305 | if (!authorizationCode) { |
| 306 | throw new Error(`No MCP authorization code found for ${serverUrl}`); |
| 307 | } |
| 308 | |
| 309 | // Close the server before processing auth |
| 310 | if (serverInstance) { |
| 311 | await new Promise<void>((resolve) => { |
| 312 | serverInstance!.close(() => { |
| 313 | console.debug("Server for MCP Oauth process was closed"); |
| 314 | serverInstance = null; |
| 315 | resolve(); |
| 316 | }); |
| 317 | }); |
| 318 | } |
| 319 | |
| 320 | const authProvider = new MCPConnectionOauthProvider(serverUrl, ide); |
| 321 | await authProvider.ensureRedirectUrl(); |
| 322 | const authStatus = await auth(authProvider, { |
| 323 | serverUrl, |
| 324 | authorizationCode, |
| 325 | }); |
| 326 | |
| 327 | if (authStatus === "AUTHORIZED") { |
| 328 | const { MCPManagerSingleton } = await import("./MCPManagerSingleton"); // put dynamic import to avoid cyclic imports |
| 329 | await MCPManagerSingleton.getInstance().refreshConnection(serverId); |
| 330 | } |
| 331 | } catch (error) { |
| 332 | const errorMessage = error instanceof Error ? error.message : String(error); |
| 333 | console.error("OAuth authorization failed:", errorMessage); |
| 334 | if (context?.ide) { |
| 335 | await context.ide.showToast("error", `OAuth failed: ${errorMessage}`); |
| 336 | } |
| 337 | } finally { |
| 338 | // Always clean up the context and state mapping |
| 339 | authenticatingContexts.delete(serverUrl); |
| 340 | if (state) { |
| 341 | stateToServerUrl.delete(state); |
| 342 | } |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | export function removeMCPAuth(url: string, ide: IDE) { |
| 347 | const authProvider = new MCPConnectionOauthProvider(url, ide); |
| 348 | authProvider.clear(); |
| 349 | } |