diff --git a/core/context/mcp/MCPConnection.ts b/core/context/mcp/MCPConnection.ts index 71d1d1e62..71412d476 100644 --- a/core/context/mcp/MCPConnection.ts +++ b/core/context/mcp/MCPConnection.ts @@ -17,7 +17,7 @@ import { MCPTool, } from "../.."; import { getEnvPathFromUserShell } from "../../util/shellPath"; -import { performAuth } from "./MCPOauth"; +import { getOauthToken } from "./MCPOauth"; const DEFAULT_MCP_TIMEOUT = 20_000; // 20 seconds @@ -118,11 +118,19 @@ class MCPConnection { if (this.options.transport.type === "sse") { // currently support oauth for sse transports only console.log("debug1 extras", this.extras); - performAuth(this.options.transport.url, this.extras?.ide!).then( - (result) => { - console.log("debug1 result", result); - }, + if (!this.options.transport.requestOptions) { + this.options.transport.requestOptions = { + headers: {}, + }; + } + const accessToken = await getOauthToken( + this.options.transport.url, + this.extras?.ide!, ); + this.options.transport.requestOptions.headers = { + ...this.options.transport.requestOptions.headers, + Authorization: `Bearer ${accessToken}`, + }; } this.connectionPromise = Promise.race([ diff --git a/core/context/mcp/MCPOauth.ts b/core/context/mcp/MCPOauth.ts index 1a961feb2..6e1544533 100644 --- a/core/context/mcp/MCPOauth.ts +++ b/core/context/mcp/MCPOauth.ts @@ -4,55 +4,77 @@ import { } from "@modelcontextprotocol/sdk/client/auth.js"; import { OAuthClientInformationFull, + OAuthClientInformationSchema, OAuthTokens, + OAuthTokensSchema, } from "@modelcontextprotocol/sdk/shared/auth.js"; import { IDE } from "../.."; import http from "http"; import url from "url"; +import { FromCoreProtocol, ToCoreProtocol } from "../../protocol"; +import { IMessenger } from "../../protocol/messenger"; +import { GlobalContext, GlobalContextType } from "../../util/GlobalContext"; + +export type MCPOauthState = "login" | "authenticating" | "disconnect"; const PORT = 3000; const server = http.createServer((req, res) => { - // TODO: instead of sending bad requests for each case, try catch handle the bad request at the end of the function - if (!req.url) { - res.writeHead(400, { "Content-Type": "text/plain" }); - res.end("Bad Request"); - return; - } - const parsedUrl = url.parse(req.url, true); + try { + if (!req.url) { + throw new Error("no url found"); + } + const parsedUrl = url.parse(req.url, true); + if (parsedUrl.pathname !== "/") { + throw new Error("path is not index"); + } - if (parsedUrl.pathname === "/") { const query = new URLSearchParams( parsedUrl.query as Record, ).toString(); if (!query) { - console.error("no query params found!"); + throw new Error("no query params found"); } - const redirectUrl = `vscode://continue.Continue${query ? "?" + query : ""}`; + + const redirectUrl = `vscode://continue.Continue?${query}`; res.writeHead(302, { Location: redirectUrl, }); res.end(); - } else { - res.writeHead(404, { "Content-Type": "text/plain" }); - res.end("Not Found"); + } catch (error) { + res.writeHead(400, { "Content-Type": "text/plain" }); + res.end(`Unexpected redirect error: ${(error as Error).message}`); } }); +// TODO: start the server only when mcp oauth process starts and kill when done server.listen(PORT, () => { - console.log(`Server running at http://localhost:${PORT}/`); + console.log( + `Server running for MCP Oauth process at http://localhost:${PORT}/`, + ); }); +type MCPOauthStorage = GlobalContextType["mcpOauthStorage"][string]; +type MCPOauthStorageKey = keyof MCPOauthStorage; + class MCPConnectionOauthProvider implements OAuthClientProvider { + private globalContext: GlobalContext; + constructor( public oauthServerUrl: string, private ide: IDE, - ) {} + ) { + this.globalContext = new GlobalContext(); + console.log( + "debug1 mcp oauth storage", + this.globalContext.get("mcpOauthStorage"), + ); + } get redirectUrl() { - return "http://localhost:3000"; // TODO: this has to be a hub url or should we spin up a server? + return `http://localhost:${PORT}`; // TODO: this has to be a hub url or should we spin up a server? } get clientMetadata() { @@ -66,25 +88,76 @@ class MCPConnectionOauthProvider implements OAuthClientProvider { }; } - saveClientInformation(clientInformation: OAuthClientInformationFull) {} + private _getOauthStorage(key: K) { + return this.globalContext.get("mcpOauthStorage")?.[this.oauthServerUrl]?.[ + key + ]; + } + + private _updateOauthStorage( + key: K, + value: MCPOauthStorage[K], + ) { + const existingStorage = this.globalContext.get("mcpOauthStorage") ?? {}; + const existingServerStorage = existingStorage[this.oauthServerUrl] ?? {}; + + this.globalContext.update("mcpOauthStorage", { + ...existingStorage, + [this.oauthServerUrl]: { + ...existingServerStorage, + [key]: value, + }, + }); + } + + private _clearOauthStorage() { + const existingStorage = this.globalContext.get("mcpOauthStorage") ?? {}; + delete existingStorage[this.oauthServerUrl]; + this.globalContext.update("mcpOauthStorage", existingStorage); + } + + saveClientInformation(clientInformation: OAuthClientInformationFull) { + this._updateOauthStorage("clientInformation", clientInformation); + } async clientInformation() { - return undefined; + const existingClientInformation = + this._getOauthStorage("clientInformation"); + if (!existingClientInformation) { + return undefined; + } + return await OAuthClientInformationSchema.parseAsync( + existingClientInformation, + ); } async tokens() { - return undefined; + const existingTokens = this._getOauthStorage("tokens"); + if (!existingTokens) { + return undefined; + } + return await OAuthTokensSchema.parseAsync(existingTokens); } - saveTokens(tokens: OAuthTokens) {} + saveTokens(tokens: OAuthTokens) { + this._updateOauthStorage("tokens", tokens); + } codeVerifier(): string | Promise { - return ""; + const existingCodeVerifier = this._getOauthStorage("codeVerifier"); + if (!existingCodeVerifier) { + return ""; + } + return existingCodeVerifier; } - saveCodeVerifier(codeVerifier: string) {} + saveCodeVerifier(codeVerifier: string) { + this._updateOauthStorage("codeVerifier", codeVerifier); + } - clear() {} + clear() { + this._clearOauthStorage(); + } async redirectToAuthorization(authorizationUrl: URL) { console.log("debug1 redirecting to url", authorizationUrl); @@ -93,27 +166,46 @@ class MCPConnectionOauthProvider implements OAuthClientProvider { } } +// TODO: first fetch can fail - need to refresh from gui +export async function getOauthToken(mcpServerUrl: string, ide: IDE) { + const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide); + const tokens = await authProvider.tokens(); + return tokens?.access_token; +} + +// TODO: this needs to be called from an authenticate button in gui export async function performAuth(mcpServerUrl: string, ide: IDE) { const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide); - await auth(authProvider, { serverUrl: mcpServerUrl }); - - // full uri is of the format "https://localhost:3000/?code=712020%253Abed80c83-1041-49e0-99b5-5d4f9f8aa538%3ACSlICEGG3rzCQhla%3AHA0oJYDjijnNE8nCoADpZsSp8jr7cCSZ" - // const input = await ide.showInput({ - // prompt: "Paste the auth code here", - // }); - // const result = await auth(authProvider, { - // serverUrl: mcpServerUrl, - // authorizationCode: input, - // }); - // if (result === "AUTHORIZED") { - // void ide.showToast( - // "info", - // `Authenticated with ${new URL(mcpServerUrl).hostname} MCP server`, - // ); - // } else { - // void ide.showToast( - // "error", - // `Failed to authenticate with ${new URL(mcpServerUrl).hostname} MCP server`, - // ); - // } + const result = await auth(authProvider, { + serverUrl: mcpServerUrl, + }); + console.log("debug1 first result", result); +} + +export async function handleMCPOauthCode( + authorizationCode: string, + ide: IDE, + messenger: IMessenger, +) { + // const { serverUrl, authState } = await messenger.request( + // "getMCPOauthState", // remove this if not needed including the protocols - we can store the state in current file itself (also easier to kill the server) + // undefined, + // ); + const serverUrl = "https://mcp.asana.com/sse"; + if (!authorizationCode) { + ide.showToast("error", `No MCP authorization code found for ${serverUrl}`); + } + + console.log("debug1 authenticating ", { + serverUrl, + authorizationCode, + }); + const authProvider = new MCPConnectionOauthProvider(serverUrl, ide); + console.log("debug1 starting auth"); + const result = await auth(authProvider, { + serverUrl, + authorizationCode, + }); + + console.log("debug1 after auth result", result); } diff --git a/core/core.ts b/core/core.ts index d8275b8ff..74702f80c 100644 --- a/core/core.ts +++ b/core/core.ts @@ -61,6 +61,7 @@ import { } from "./config/onboarding"; import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks"; import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton"; +import { handleMCPOauthCode } from "./context/mcp/MCPOauth"; import { setMdmLicenseKey } from "./control-plane/mdm/mdm"; import { ApplyAbortManager } from "./edit/applyAbortManager"; import { streamDiffLines } from "./edit/streamDiffLines"; @@ -433,6 +434,10 @@ export class Core { description: prompt.description, }; }); + on("mcp/sendOauthCode", async (msg) => { + await handleMCPOauthCode(msg.data.code, this.ide, this.messenger); + }); + // Context providers on("context/addDocs", async (msg) => { void this.docsService.indexAndAdd(msg.data); diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 743556d15..5f1aa7ad9 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -142,6 +142,12 @@ export type ToCoreFromIdeOrWebviewProtocol = { description: string | undefined; }, ]; + "mcp/sendOauthCode": [ + { + code: string; + }, + void, + ]; "context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap]; "context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]]; "autocomplete/complete": [AutocompleteInput, string[]]; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 6e25e5f54..482ec37f6 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -92,4 +92,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "didCloseFiles", "toolCallPartialOutput", "freeTrialExceeded", + "getMCPOauthState", ]; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 1a8d40313..cc963982f 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -1,5 +1,6 @@ import { ConfigResult } from "@continuedev/config-yaml"; import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager.js"; +import { MCPOauthState } from "../context/mcp/MCPOauth.js"; import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes.js"; import type { BrowserSerializedContinueConfig, @@ -44,4 +45,8 @@ export type ToWebviewFromIdeOrCoreProtocol = { sessionUpdate: [{ sessionInfo: ControlPlaneSessionInfo | undefined }, void]; toolCallPartialOutput: [{ toolCallId: string; contextItems: any[] }, void]; freeTrialExceeded: [undefined, void]; + getMCPOauthState: [ + undefined, + { serverUrl: string; authState: MCPOauthState }, + ]; }; diff --git a/core/util/GlobalContext.ts b/core/util/GlobalContext.ts index 6885edde2..ddf9f6f44 100644 --- a/core/util/GlobalContext.ts +++ b/core/util/GlobalContext.ts @@ -9,6 +9,10 @@ import { SharedConfigSchema, } from "../config/sharedConfig"; +import { + OAuthClientInformationFull, + OAuthTokens, +} from "@modelcontextprotocol/sdk/shared/auth.js"; import { getGlobalContextFilePath } from "./paths"; export type GlobalContextModelSelections = Partial< @@ -39,6 +43,15 @@ export type GlobalContextType = { isSupportedLanceDbCpuTargetForLinux: boolean; sharedConfig: SharedConfigSchema; failedDocs: SiteIndexingConfig[]; + + mcpOauthStorage: Record< + string, + { + clientInformation?: OAuthClientInformationFull; + tokens?: OAuthTokens; + codeVerifier?: string; + } + >; }; /** diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index fe624179a..463b2ba42 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -73,11 +73,6 @@ export class VsCodeExtension { // Register auth provider this.workOsAuthProvider = new WorkOsAuthProvider(context, this.uriHandler); - // TODO: this should practically only start listening when user has started an mcp oauth flow. how to do this? - this.uriHandler.event((uri) => { - console.log("debug1 uri was", uri); - }); - void this.workOsAuthProvider.refreshSessions(); context.subscriptions.push(this.workOsAuthProvider); @@ -445,6 +440,14 @@ export class VsCodeExtension { void this.core.invoke("config/ideSettingsUpdate", settings); } }); + + // TODO: this should practically only start listening when user has started an mcp oauth flow. how to do this? + this.uriHandler.event((uri) => { + console.log("debug1 uri->", uri); + this.core.invoke("mcp/sendOauthCode", { + code: new URLSearchParams(uri.query).get("code") ?? "", + }); + }); } static continueVirtualDocumentScheme = EXTENSION_NAME;