From 2473a3993f0e2cac1740061146e3d0246668bf74 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Fri, 25 Jul 2025 19:11:55 +0530 Subject: [PATCH 01/17] handle mcp authenticated token - spin up a local server to handle redirects - create an MCPOauth class to handle oauths --- core/config/yaml/loadYaml.ts | 1 + core/context/mcp/MCPConnection.ts | 21 +++- core/context/mcp/MCPManagerSingleton.ts | 10 +- core/context/mcp/MCPOauth.ts | 119 ++++++++++++++++++ .../vscode/src/extension/VsCodeExtension.ts | 6 + 5 files changed, 153 insertions(+), 4 deletions(-) create mode 100644 core/context/mcp/MCPOauth.ts diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 4f1a1632f..e7e6bb0c3 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -440,6 +440,7 @@ async function configYamlToContinueConfig(options: { timeout: server.connectionTimeout, })), false, + { ide }, ); return { config: continueConfig, errors: localErrors }; diff --git a/core/context/mcp/MCPConnection.ts b/core/context/mcp/MCPConnection.ts index 3d39a0c7c..71d1d1e62 100644 --- a/core/context/mcp/MCPConnection.ts +++ b/core/context/mcp/MCPConnection.ts @@ -7,6 +7,7 @@ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/ import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js"; import { + IDE, MCPConnectionStatus, MCPOptions, MCPPrompt, @@ -16,6 +17,7 @@ import { MCPTool, } from "../.."; import { getEnvPathFromUserShell } from "../../util/shellPath"; +import { performAuth } from "./MCPOauth"; const DEFAULT_MCP_TIMEOUT = 20_000; // 20 seconds @@ -30,6 +32,10 @@ const WINDOWS_BATCH_COMMANDS = [ "bunx", ]; +export type MCPExtras = { + ide: IDE; +}; + class MCPConnection { public client: Client; public abortController: AbortController; @@ -46,7 +52,10 @@ class MCPConnection { stderr: "", }; - constructor(public options: MCPOptions) { + constructor( + public options: MCPOptions, + public extras?: MCPExtras, + ) { // Don't construct transport in constructor to avoid blocking this.transport = {} as Transport; // Will be set in connectClient @@ -106,6 +115,16 @@ class MCPConnection { this.abortController.abort(); this.abortController = new AbortController(); + 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); + }, + ); + } + this.connectionPromise = Promise.race([ // If aborted by a refresh or other, cancel and don't do anything new Promise((resolve) => { diff --git a/core/context/mcp/MCPManagerSingleton.ts b/core/context/mcp/MCPManagerSingleton.ts index 7eafa1564..515fdecc7 100644 --- a/core/context/mcp/MCPManagerSingleton.ts +++ b/core/context/mcp/MCPManagerSingleton.ts @@ -6,7 +6,7 @@ import { StdioOptions, TransportOptions, } from "../.."; -import MCPConnection from "./MCPConnection"; +import MCPConnection, { MCPExtras } from "./MCPConnection"; export class MCPManagerSingleton { private static instance: MCPManagerSingleton; @@ -48,7 +48,11 @@ export class MCPManagerSingleton { this.connections.delete(id); } - setConnections(servers: MCPOptions[], forceRefresh: boolean) { + setConnections( + servers: MCPOptions[], + forceRefresh: boolean, + extras?: MCPExtras, + ) { let refresh = false; // Remove any connections that are no longer in config @@ -75,7 +79,7 @@ export class MCPManagerSingleton { servers.forEach((server) => { if (!this.connections.has(server.id)) { refresh = true; - this.connections.set(server.id, new MCPConnection(server)); + this.connections.set(server.id, new MCPConnection(server, extras)); } else { const conn = this.connections.get(server.id); if (conn) { diff --git a/core/context/mcp/MCPOauth.ts b/core/context/mcp/MCPOauth.ts new file mode 100644 index 000000000..1a961feb2 --- /dev/null +++ b/core/context/mcp/MCPOauth.ts @@ -0,0 +1,119 @@ +import { + OAuthClientProvider, + auth, +} from "@modelcontextprotocol/sdk/client/auth.js"; +import { + OAuthClientInformationFull, + OAuthTokens, +} from "@modelcontextprotocol/sdk/shared/auth.js"; +import { IDE } from "../.."; + +import http from "http"; +import url from "url"; + +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); + + if (parsedUrl.pathname === "/") { + const query = new URLSearchParams( + parsedUrl.query as Record, + ).toString(); + if (!query) { + console.error("no query params found!"); + } + const redirectUrl = `vscode://continue.Continue${query ? "?" + query : ""}`; + + res.writeHead(302, { + Location: redirectUrl, + }); + res.end(); + } else { + res.writeHead(404, { "Content-Type": "text/plain" }); + res.end("Not Found"); + } +}); + +server.listen(PORT, () => { + console.log(`Server running at http://localhost:${PORT}/`); +}); + +class MCPConnectionOauthProvider implements OAuthClientProvider { + constructor( + public oauthServerUrl: string, + private ide: IDE, + ) {} + + get redirectUrl() { + return "http://localhost:3000"; // TODO: this has to be a hub url or should we spin up a server? + } + + get clientMetadata() { + return { + redirect_uris: [this.redirectUrl], + token_endpoint_auth_method: "none", + grant_types: ["authorization_code", "refresh_token"], + response_types: ["code"], + client_name: "Continue Dev, Inc", // get this from package.json? + client_uri: "https://continue.dev", // get this from package.json? + }; + } + + saveClientInformation(clientInformation: OAuthClientInformationFull) {} + + async clientInformation() { + return undefined; + } + + async tokens() { + return undefined; + } + + saveTokens(tokens: OAuthTokens) {} + + codeVerifier(): string | Promise { + return ""; + } + + saveCodeVerifier(codeVerifier: string) {} + + clear() {} + + async redirectToAuthorization(authorizationUrl: URL) { + console.log("debug1 redirecting to url", authorizationUrl); + // TODO here the url needs to be sent to the extension + this.ide.openUrl(authorizationUrl.toString()); + } +} + +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`, + // ); + // } +} diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index f0137bd0c..fe624179a 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -72,6 +72,12 @@ export class VsCodeExtension { constructor(context: vscode.ExtensionContext) { // 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); From 35a58c0c9d5933d044208f397ff24936f3c9ab4b Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Mon, 28 Jul 2025 12:26:03 +0530 Subject: [PATCH 02/17] handle authentication callback - add storage to store tokens - in mcp connection, add headers --- core/context/mcp/MCPConnection.ts | 18 +- core/context/mcp/MCPOauth.ts | 180 +++++++++++++----- core/core.ts | 5 + core/protocol/core.ts | 6 + core/protocol/passThrough.ts | 1 + core/protocol/webview.ts | 5 + core/util/GlobalContext.ts | 13 ++ .../vscode/src/extension/VsCodeExtension.ts | 13 +- 8 files changed, 187 insertions(+), 54 deletions(-) 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; From a062f26559ff289bea3b20f1e9bda66734d88dd4 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Mon, 28 Jul 2025 21:51:47 +0530 Subject: [PATCH 03/17] add authenticate button in gui - added a startAuthentication protocol --- core/context/mcp/MCPConnection.ts | 1 - core/context/mcp/MCPOauth.ts | 14 ++---- core/core.ts | 17 ++++++- core/protocol/core.ts | 2 + core/protocol/passThrough.ts | 1 + .../Lump/sections/mcp/MCPSection.tsx | 46 +++++++++++++++++-- 6 files changed, 65 insertions(+), 16 deletions(-) diff --git a/core/context/mcp/MCPConnection.ts b/core/context/mcp/MCPConnection.ts index 71412d476..7b1d0b615 100644 --- a/core/context/mcp/MCPConnection.ts +++ b/core/context/mcp/MCPConnection.ts @@ -117,7 +117,6 @@ class MCPConnection { if (this.options.transport.type === "sse") { // currently support oauth for sse transports only - console.log("debug1 extras", this.extras); if (!this.options.transport.requestOptions) { this.options.transport.requestOptions = { headers: {}, diff --git a/core/context/mcp/MCPOauth.ts b/core/context/mcp/MCPOauth.ts index 6e1544533..043117251 100644 --- a/core/context/mcp/MCPOauth.ts +++ b/core/context/mcp/MCPOauth.ts @@ -8,7 +8,7 @@ import { OAuthTokens, OAuthTokensSchema, } from "@modelcontextprotocol/sdk/shared/auth.js"; -import { IDE } from "../.."; +import { IDE, MCPServerStatus, SSEOptions } from "../.."; import http from "http"; import url from "url"; @@ -173,13 +173,12 @@ export async function getOauthToken(mcpServerUrl: string, ide: IDE) { return tokens?.access_token; } -// TODO: this needs to be called from an authenticate button in gui -export async function performAuth(mcpServerUrl: string, ide: IDE) { +export async function performAuth(mcpServer: MCPServerStatus, ide: IDE) { + const mcpServerUrl = (mcpServer.transport as SSEOptions).url; const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide); - const result = await auth(authProvider, { + return await auth(authProvider, { serverUrl: mcpServerUrl, }); - console.log("debug1 first result", result); } export async function handleMCPOauthCode( @@ -201,11 +200,8 @@ export async function handleMCPOauthCode( authorizationCode, }); const authProvider = new MCPConnectionOauthProvider(serverUrl, ide); - console.log("debug1 starting auth"); - const result = await auth(authProvider, { + return await auth(authProvider, { serverUrl, authorizationCode, }); - - console.log("debug1 after auth result", result); } diff --git a/core/core.ts b/core/core.ts index 74702f80c..c72503af0 100644 --- a/core/core.ts +++ b/core/core.ts @@ -61,7 +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 { handleMCPOauthCode, performAuth } from "./context/mcp/MCPOauth"; import { setMdmLicenseKey } from "./control-plane/mdm/mdm"; import { ApplyAbortManager } from "./edit/applyAbortManager"; import { streamDiffLines } from "./edit/streamDiffLines"; @@ -434,8 +434,21 @@ export class Core { description: prompt.description, }; }); + on("mcp/startAuthentication", async (msg) => { + const status = await performAuth(msg.data, this.ide); + if (status === "AUTHORIZED") { + await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); + } + }); on("mcp/sendOauthCode", async (msg) => { - await handleMCPOauthCode(msg.data.code, this.ide, this.messenger); + const status = await handleMCPOauthCode( + msg.data.code, + this.ide, + this.messenger, + ); + if (status === "AUTHORIZED") { + // await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); + } }); // Context providers diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 5f1aa7ad9..517dd34fd 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -26,6 +26,7 @@ import { FileSymbolMap, IdeSettings, LLMFullCompletionOptions, + MCPServerStatus, MessageOption, ModelDescription, PromptLog, @@ -142,6 +143,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { description: string | undefined; }, ]; + "mcp/startAuthentication": [MCPServerStatus, void]; "mcp/sendOauthCode": [ { code: string; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 482ec37f6..96858f29d 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -28,6 +28,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "config/updateSelectedModel", "mcp/reloadServer", "mcp/getPrompt", + "mcp/startAuthentication", "context/getContextItems", "context/getSymbolsForFiles", "context/loadSubmenuItems", diff --git a/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx b/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx index 76fb338e9..73b890fd2 100644 --- a/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx @@ -1,13 +1,16 @@ import { ConfigYaml, parseConfigYaml } from "@continuedev/config-yaml"; import { + ArrowLeftCircleIcon, ArrowPathIcon, CircleStackIcon, CommandLineIcon, + GlobeAltIcon, InformationCircleIcon, + UserCircleIcon, WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; import { MCPServerStatus } from "core"; -import { useContext, useMemo } from "react"; +import { useContext, useMemo, useState } from "react"; import { useAuth } from "../../../../../context/Auth"; import { IdeMessengerContext } from "../../../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../../../redux/hooks"; @@ -17,6 +20,10 @@ import { ToolTip } from "../../../../gui/Tooltip"; import EditBlockButton from "../../EditBlockButton"; import { ExploreBlocksButton } from "../ExploreBlocksButton"; +function has401Error(errors: string[]) { + return !!errors.find((error) => error.includes("401")); +} + interface MCPServerStatusProps { server: MCPServerStatus; serverFromYaml?: NonNullable[number]; @@ -30,7 +37,17 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) { const resourcesTooltipId = `${server.id}-resources`; const errorsTooltipId = `${server.id}-errors`; - async function onRefresh() { + const [mcpAuthStatus, setMcpAuthStatus] = useState< + "unauthenticated" | "authenticated" | "authenticating" + >("unauthenticated"); + + const onAuthenticate = async () => { + setMcpAuthStatus("authenticating"); // TODO: move this updateConfig later with "authenticated" and "authenticating" status + await ideMessenger.request("mcp/startAuthentication", server); + setMcpAuthStatus("authenticated"); + }; + + const onRefresh = async () => { // optimistic config update dispatch( updateConfig({ @@ -48,7 +65,13 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) { ideMessenger.post("mcp/reloadServer", { id: server.id, }); - } + }; + + // useEffect(() => { + // if (hasConnectionResetError(server.errors)) { + // onRefresh(); + // } + // }, [server.errors]); return (
- {/* Refresh button */}
+ {has401Error(server.errors) && ( + <> +
+ {mcpAuthStatus === "authenticating" ? ( + + ) : mcpAuthStatus === "authenticated" ? ( + + ) : ( + + )} +
+ + )} Date: Mon, 28 Jul 2025 22:33:43 +0530 Subject: [PATCH 04/17] remove getmcpauthstate --- core/protocol/passThrough.ts | 1 - core/protocol/webview.ts | 5 ----- 2 files changed, 6 deletions(-) diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 96858f29d..1f79d9867 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -93,5 +93,4 @@ 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 cc963982f..1a8d40313 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -1,6 +1,5 @@ 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, @@ -45,8 +44,4 @@ export type ToWebviewFromIdeOrCoreProtocol = { sessionUpdate: [{ sessionInfo: ControlPlaneSessionInfo | undefined }, void]; toolCallPartialOutput: [{ toolCallId: string; contextItems: any[] }, void]; freeTrialExceeded: [undefined, void]; - getMCPOauthState: [ - undefined, - { serverUrl: string; authState: MCPOauthState }, - ]; }; From ab66938a661b4604afef8e25833c02acc933eb44 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Mon, 28 Jul 2025 22:42:47 +0530 Subject: [PATCH 05/17] added mcp remove authentication - add protectedresource key to mcp server status - shift mcp server auth status handling to core --- core/context/mcp/MCPConnection.ts | 32 ++++++++++--- core/context/mcp/MCPOauth.ts | 24 +++++----- core/core.ts | 16 ++++--- core/index.d.ts | 1 + core/protocol/core.ts | 3 ++ core/protocol/passThrough.ts | 1 + core/tools/mcpToolName.vitest.ts | 1 + .../Lump/sections/mcp/MCPSection.tsx | 48 ++++++++++++------- 8 files changed, 84 insertions(+), 42 deletions(-) diff --git a/core/context/mcp/MCPConnection.ts b/core/context/mcp/MCPConnection.ts index 7b1d0b615..c5a975473 100644 --- a/core/context/mcp/MCPConnection.ts +++ b/core/context/mcp/MCPConnection.ts @@ -1,7 +1,10 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; -import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"; +import { + SSEClientTransport, + SseError, +} from "@modelcontextprotocol/sdk/client/sse.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js"; @@ -32,6 +35,14 @@ const WINDOWS_BATCH_COMMANDS = [ "bunx", ]; +function is401Error(error: unknown) { + return ( + (error instanceof SseError && error.code === 401) || + (error instanceof Error && error.message.includes("401")) || + (error instanceof Error && error.message.includes("Unauthorized")) + ); +} + export type MCPExtras = { ide: IDE; }; @@ -40,6 +51,7 @@ class MCPConnection { public client: Client; public abortController: AbortController; public status: MCPConnectionStatus = "not-connected"; + public isProtectedResource = false; public errors: string[] = []; public prompts: MCPPrompt[] = []; public tools: MCPTool[] = []; @@ -87,6 +99,7 @@ class MCPConnection { resourceTemplates: this.resourceTemplates, tools: this.tools, status: this.status, + isProtectedResource: this.isProtectedResource, }; } @@ -115,8 +128,8 @@ class MCPConnection { this.abortController.abort(); this.abortController = new AbortController(); + // currently support oauth for sse transports only if (this.options.transport.type === "sse") { - // currently support oauth for sse transports only if (!this.options.transport.requestOptions) { this.options.transport.requestOptions = { headers: {}, @@ -126,10 +139,13 @@ class MCPConnection { this.options.transport.url, this.extras?.ide!, ); - this.options.transport.requestOptions.headers = { - ...this.options.transport.requestOptions.headers, - Authorization: `Bearer ${accessToken}`, - }; + if (accessToken) { + this.isProtectedResource = true; + this.options.transport.requestOptions.headers = { + ...this.options.transport.requestOptions.headers, + Authorization: `Bearer ${accessToken}`, + }; + } } this.connectionPromise = Promise.race([ @@ -270,6 +286,10 @@ class MCPConnection { } } + if (is401Error(error)) { + this.isProtectedResource = true; + } + // Include stdio output if available for stdio transport if ( this.options.transport.type === "stdio" && diff --git a/core/context/mcp/MCPOauth.ts b/core/context/mcp/MCPOauth.ts index 043117251..f76b62fba 100644 --- a/core/context/mcp/MCPOauth.ts +++ b/core/context/mcp/MCPOauth.ts @@ -12,11 +12,9 @@ import { IDE, MCPServerStatus, SSEOptions } 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"; +let currentMCPAuthServerUrl = ""; const PORT = 3000; @@ -157,6 +155,10 @@ class MCPConnectionOauthProvider implements OAuthClientProvider { clear() { this._clearOauthStorage(); + console.log( + "debug1 after clearing mcp oauth storage", + this.globalContext.get("mcpOauthStorage"), + ); } async redirectToAuthorization(authorizationUrl: URL) { @@ -181,15 +183,7 @@ export async function performAuth(mcpServer: MCPServerStatus, ide: IDE) { }); } -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, - // ); +export async function handleMCPOauthCode(authorizationCode: string, ide: IDE) { const serverUrl = "https://mcp.asana.com/sse"; if (!authorizationCode) { ide.showToast("error", `No MCP authorization code found for ${serverUrl}`); @@ -205,3 +199,9 @@ export async function handleMCPOauthCode( authorizationCode, }); } + +export function removeMCPAuth(mcpServer: MCPServerStatus, ide: IDE) { + const mcpServerUrl = (mcpServer.transport as SSEOptions).url; + const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide); + authProvider.clear(); +} diff --git a/core/core.ts b/core/core.ts index c72503af0..cb846c7ad 100644 --- a/core/core.ts +++ b/core/core.ts @@ -61,7 +61,11 @@ import { } from "./config/onboarding"; import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks"; import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton"; -import { handleMCPOauthCode, performAuth } from "./context/mcp/MCPOauth"; +import { + handleMCPOauthCode, + performAuth, + removeMCPAuth, +} from "./context/mcp/MCPOauth"; import { setMdmLicenseKey } from "./control-plane/mdm/mdm"; import { ApplyAbortManager } from "./edit/applyAbortManager"; import { streamDiffLines } from "./edit/streamDiffLines"; @@ -441,15 +445,15 @@ export class Core { } }); on("mcp/sendOauthCode", async (msg) => { - const status = await handleMCPOauthCode( - msg.data.code, - this.ide, - this.messenger, - ); + const status = await handleMCPOauthCode(msg.data.code, this.ide); if (status === "AUTHORIZED") { // await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); } }); + on("mcp/removeAuthentication", async (msg) => { + removeMCPAuth(msg.data, this.ide); + await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); + }); // Context providers on("context/addDocs", async (msg) => { diff --git a/core/index.d.ts b/core/index.d.ts index 13e231b87..90b978a63 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1310,6 +1310,7 @@ export interface MCPTool { export interface MCPServerStatus extends MCPOptions { status: MCPConnectionStatus; errors: string[]; + isProtectedResource: boolean; prompts: MCPPrompt[]; tools: MCPTool[]; diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 517dd34fd..daacaa4f1 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -126,6 +126,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, ContextItemWithId[], ]; + "mcp/reloadServer": [ { id: string; @@ -150,6 +151,8 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, void, ]; + "mcp/removeAuthentication": [MCPServerStatus, 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 1f79d9867..4575a2b53 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -29,6 +29,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "mcp/reloadServer", "mcp/getPrompt", "mcp/startAuthentication", + "mcp/removeAuthentication", "context/getContextItems", "context/getSymbolsForFiles", "context/loadSubmenuItems", diff --git a/core/tools/mcpToolName.vitest.ts b/core/tools/mcpToolName.vitest.ts index 8c20f630a..ff60d5200 100644 --- a/core/tools/mcpToolName.vitest.ts +++ b/core/tools/mcpToolName.vitest.ts @@ -15,6 +15,7 @@ const createMcpServer = (name: string): MCPServerStatus => ({ type: "sse", url: "", }, + isProtectedResource: false, }); const createMCPTool = (name: string): MCPTool => ({ diff --git a/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx b/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx index 73b890fd2..ede04c013 100644 --- a/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx @@ -1,22 +1,22 @@ import { ConfigYaml, parseConfigYaml } from "@continuedev/config-yaml"; import { - ArrowLeftCircleIcon, ArrowPathIcon, CircleStackIcon, CommandLineIcon, - GlobeAltIcon, InformationCircleIcon, - UserCircleIcon, + ShieldCheckIcon, + ShieldExclamationIcon, WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; import { MCPServerStatus } from "core"; -import { useContext, useMemo, useState } from "react"; +import { useContext, useMemo } from "react"; import { useAuth } from "../../../../../context/Auth"; import { IdeMessengerContext } from "../../../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../../../redux/hooks"; import { updateConfig } from "../../../../../redux/slices/configSlice"; import { fontSize } from "../../../../../util"; import { ToolTip } from "../../../../gui/Tooltip"; +import { Button } from "../../../../ui"; import EditBlockButton from "../../EditBlockButton"; import { ExploreBlocksButton } from "../ExploreBlocksButton"; @@ -36,15 +36,14 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) { const promptsTooltipId = `${server.id}-prompts`; const resourcesTooltipId = `${server.id}-resources`; const errorsTooltipId = `${server.id}-errors`; - - const [mcpAuthStatus, setMcpAuthStatus] = useState< - "unauthenticated" | "authenticated" | "authenticating" - >("unauthenticated"); + const mcpAuthTooltipId = `${server.id}-auth`; const onAuthenticate = async () => { - setMcpAuthStatus("authenticating"); // TODO: move this updateConfig later with "authenticated" and "authenticating" status await ideMessenger.request("mcp/startAuthentication", server); - setMcpAuthStatus("authenticated"); + }; + + const onRemoveAuth = async () => { + await ideMessenger.request("mcp/removeAuthentication", server); }; const onRefresh = async () => { @@ -154,20 +153,33 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) {
- {has401Error(server.errors) && ( + {server.isProtectedResource && ( <>
- {mcpAuthStatus === "authenticating" ? ( - - ) : mcpAuthStatus === "authenticated" ? ( - - ) : ( - + {server.status === "error" ? ( + + ) : server.status === "connecting" ? null : ( + )}
+ +
+ +
+
)} Date: Mon, 28 Jul 2025 23:03:01 +0530 Subject: [PATCH 06/17] handle mcp oauth callback --- core/context/mcp/MCPOauth.ts | 31 ++++++++++++++----- core/core.ts | 11 +++++-- .../Lump/sections/mcp/MCPSection.tsx | 14 ++++----- 3 files changed, 38 insertions(+), 18 deletions(-) diff --git a/core/context/mcp/MCPOauth.ts b/core/context/mcp/MCPOauth.ts index f76b62fba..34e79368d 100644 --- a/core/context/mcp/MCPOauth.ts +++ b/core/context/mcp/MCPOauth.ts @@ -14,7 +14,8 @@ import http from "http"; import url from "url"; import { GlobalContext, GlobalContextType } from "../../util/GlobalContext"; -let currentMCPAuthServerUrl = ""; +/**in memory storage variable for the server that is currently being authenticated */ +let authenticatingMCPServer: MCPServerStatus | null = null; const PORT = 3000; @@ -162,29 +163,40 @@ class MCPConnectionOauthProvider implements OAuthClientProvider { } async redirectToAuthorization(authorizationUrl: URL) { - console.log("debug1 redirecting to url", authorizationUrl); - // TODO here the url needs to be sent to the extension this.ide.openUrl(authorizationUrl.toString()); } } -// 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; } +/** + * checks if the authentication is already done for the current server + * if not, starts the authentication process by opening a webpage url + */ export async function performAuth(mcpServer: MCPServerStatus, ide: IDE) { const mcpServerUrl = (mcpServer.transport as SSEOptions).url; const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide); - return await auth(authProvider, { + const authStatus = await auth(authProvider, { serverUrl: mcpServerUrl, }); + if (authStatus === "REDIRECT") { + authenticatingMCPServer = mcpServer; + } + return authStatus; } +/** + * handle the authentication code received from the oauth redirect + */ export async function handleMCPOauthCode(authorizationCode: string, ide: IDE) { - const serverUrl = "https://mcp.asana.com/sse"; + const serverUrl = (authenticatingMCPServer?.transport as SSEOptions).url; + if (!serverUrl) { + ide.showToast("error", "No MCP server url found for authentication"); + } if (!authorizationCode) { ide.showToast("error", `No MCP authorization code found for ${serverUrl}`); } @@ -194,10 +206,15 @@ export async function handleMCPOauthCode(authorizationCode: string, ide: IDE) { authorizationCode, }); const authProvider = new MCPConnectionOauthProvider(serverUrl, ide); - return await auth(authProvider, { + const authStatus = await auth(authProvider, { serverUrl, authorizationCode, }); + + const prevAuthenticatingMCPServer = authenticatingMCPServer!; + authenticatingMCPServer = null; + + return { authStatus, authenticatingMCPServer: prevAuthenticatingMCPServer }; } export function removeMCPAuth(mcpServer: MCPServerStatus, ide: IDE) { diff --git a/core/core.ts b/core/core.ts index cb846c7ad..41663acca 100644 --- a/core/core.ts +++ b/core/core.ts @@ -445,9 +445,14 @@ export class Core { } }); on("mcp/sendOauthCode", async (msg) => { - const status = await handleMCPOauthCode(msg.data.code, this.ide); - if (status === "AUTHORIZED") { - // await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); + const { authStatus, authenticatingMCPServer } = await handleMCPOauthCode( + msg.data.code, + this.ide, + ); + if (authStatus === "AUTHORIZED") { + await MCPManagerSingleton.getInstance().refreshConnection( + authenticatingMCPServer.id, + ); } }); on("mcp/removeAuthentication", async (msg) => { diff --git a/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx b/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx index ede04c013..4363df837 100644 --- a/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx @@ -9,7 +9,7 @@ import { WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; import { MCPServerStatus } from "core"; -import { useContext, useMemo } from "react"; +import { useContext, useMemo, useState } from "react"; import { useAuth } from "../../../../../context/Auth"; import { IdeMessengerContext } from "../../../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../../../redux/hooks"; @@ -30,6 +30,8 @@ interface MCPServerStatusProps { } function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) { const ideMessenger = useContext(IdeMessengerContext); + // TODO: refactor this to mcp state - also easier to remove the in memory storage + const [isMcpAuthenticating, setIsMcpAuthenticating] = useState(false); const config = useAppSelector((store) => store.config.config); const dispatch = useAppDispatch(); const toolsTooltipId = `${server.id}-tools`; @@ -39,7 +41,9 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) { const mcpAuthTooltipId = `${server.id}-auth`; const onAuthenticate = async () => { + setIsMcpAuthenticating(true); await ideMessenger.request("mcp/startAuthentication", server); + setIsMcpAuthenticating(false); }; const onRemoveAuth = async () => { @@ -66,12 +70,6 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) { }); }; - // useEffect(() => { - // if (hasConnectionResetError(server.errors)) { - // onRefresh(); - // } - // }, [server.errors]); - return (
- {server.isProtectedResource && ( + {server.isProtectedResource && !isMcpAuthenticating && ( <>
Date: Mon, 28 Jul 2025 23:21:45 +0530 Subject: [PATCH 07/17] store mcp authenticating server as connection status --- core/context/mcp/MCPOauth.ts | 30 ++++++----------- core/core.ts | 11 +++++-- core/index.d.ts | 1 + .../Lump/sections/mcp/MCPSection.tsx | 33 ++++++++++--------- 4 files changed, 36 insertions(+), 39 deletions(-) diff --git a/core/context/mcp/MCPOauth.ts b/core/context/mcp/MCPOauth.ts index 34e79368d..58f55b34c 100644 --- a/core/context/mcp/MCPOauth.ts +++ b/core/context/mcp/MCPOauth.ts @@ -14,9 +14,6 @@ import http from "http"; import url from "url"; import { GlobalContext, GlobalContextType } from "../../util/GlobalContext"; -/**in memory storage variable for the server that is currently being authenticated */ -let authenticatingMCPServer: MCPServerStatus | null = null; - const PORT = 3000; const server = http.createServer((req, res) => { @@ -180,41 +177,34 @@ export async function getOauthToken(mcpServerUrl: string, ide: IDE) { export async function performAuth(mcpServer: MCPServerStatus, ide: IDE) { const mcpServerUrl = (mcpServer.transport as SSEOptions).url; const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide); - const authStatus = await auth(authProvider, { + return await auth(authProvider, { serverUrl: mcpServerUrl, }); - if (authStatus === "REDIRECT") { - authenticatingMCPServer = mcpServer; - } - return authStatus; } /** * handle the authentication code received from the oauth redirect */ -export async function handleMCPOauthCode(authorizationCode: string, ide: IDE) { - const serverUrl = (authenticatingMCPServer?.transport as SSEOptions).url; +export async function handleMCPOauthCode( + authorizationCode: string, + ide: IDE, + authenticatingServer: MCPServerStatus | undefined, +) { + const serverUrl = (authenticatingServer?.transport as SSEOptions).url; if (!serverUrl) { ide.showToast("error", "No MCP server url found for authentication"); + return; } if (!authorizationCode) { ide.showToast("error", `No MCP authorization code found for ${serverUrl}`); + return; } - console.log("debug1 authenticating ", { - serverUrl, - authorizationCode, - }); const authProvider = new MCPConnectionOauthProvider(serverUrl, ide); - const authStatus = await auth(authProvider, { + return await auth(authProvider, { serverUrl, authorizationCode, }); - - const prevAuthenticatingMCPServer = authenticatingMCPServer!; - authenticatingMCPServer = null; - - return { authStatus, authenticatingMCPServer: prevAuthenticatingMCPServer }; } export function removeMCPAuth(mcpServer: MCPServerStatus, ide: IDE) { diff --git a/core/core.ts b/core/core.ts index 41663acca..bac3744c6 100644 --- a/core/core.ts +++ b/core/core.ts @@ -439,19 +439,24 @@ export class Core { }; }); on("mcp/startAuthentication", async (msg) => { + await new Promise((resolve) => setTimeout(resolve, 5000)); const status = await performAuth(msg.data, this.ide); if (status === "AUTHORIZED") { await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); } }); on("mcp/sendOauthCode", async (msg) => { - const { authStatus, authenticatingMCPServer } = await handleMCPOauthCode( + const authenticatingServer = MCPManagerSingleton.getInstance() + .getStatuses() + .find((s) => s.status === "authenticating"); + const authStatus = await handleMCPOauthCode( msg.data.code, this.ide, + authenticatingServer, ); - if (authStatus === "AUTHORIZED") { + if (authStatus === "AUTHORIZED" && authenticatingServer) { await MCPManagerSingleton.getInstance().refreshConnection( - authenticatingMCPServer.id, + authenticatingServer.id, ); } }); diff --git a/core/index.d.ts b/core/index.d.ts index 90b978a63..f71b200bb 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1262,6 +1262,7 @@ export interface MCPOptions { } export type MCPConnectionStatus = + | "authenticating" | "connecting" | "connected" | "error" diff --git a/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx b/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx index 4363df837..51e3368da 100644 --- a/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx @@ -9,7 +9,7 @@ import { WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; import { MCPServerStatus } from "core"; -import { useContext, useMemo, useState } from "react"; +import { useContext, useMemo } from "react"; import { useAuth } from "../../../../../context/Auth"; import { IdeMessengerContext } from "../../../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../../../redux/hooks"; @@ -30,8 +30,6 @@ interface MCPServerStatusProps { } function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) { const ideMessenger = useContext(IdeMessengerContext); - // TODO: refactor this to mcp state - also easier to remove the in memory storage - const [isMcpAuthenticating, setIsMcpAuthenticating] = useState(false); const config = useAppSelector((store) => store.config.config); const dispatch = useAppDispatch(); const toolsTooltipId = `${server.id}-tools`; @@ -40,17 +38,7 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) { const errorsTooltipId = `${server.id}-errors`; const mcpAuthTooltipId = `${server.id}-auth`; - const onAuthenticate = async () => { - setIsMcpAuthenticating(true); - await ideMessenger.request("mcp/startAuthentication", server); - setIsMcpAuthenticating(false); - }; - - const onRemoveAuth = async () => { - await ideMessenger.request("mcp/removeAuthentication", server); - }; - - const onRefresh = async () => { + const updateMCPServerStatus = (status: MCPServerStatus["status"]) => { // optimistic config update dispatch( updateConfig({ @@ -59,12 +47,25 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) { s.id === server.id ? { ...s, - status: "connecting", + status, } : s, ), }), ); + }; + + const onAuthenticate = async () => { + updateMCPServerStatus("authenticating"); + await ideMessenger.request("mcp/startAuthentication", server); + }; + + const onRemoveAuth = async () => { + await ideMessenger.request("mcp/removeAuthentication", server); + }; + + const onRefresh = async () => { + updateMCPServerStatus("connecting"); ideMessenger.post("mcp/reloadServer", { id: server.id, }); @@ -151,7 +152,7 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) {
- {server.isProtectedResource && !isMcpAuthenticating && ( + {server.isProtectedResource && server.status !== "authenticating" && ( <>
Date: Tue, 29 Jul 2025 11:53:28 +0530 Subject: [PATCH 08/17] fix find authenticating server --- core/context/mcp/MCPManagerSingleton.ts | 4 ++++ core/core.ts | 1 + 2 files changed, 5 insertions(+) diff --git a/core/context/mcp/MCPManagerSingleton.ts b/core/context/mcp/MCPManagerSingleton.ts index 515fdecc7..4a704f427 100644 --- a/core/context/mcp/MCPManagerSingleton.ts +++ b/core/context/mcp/MCPManagerSingleton.ts @@ -166,6 +166,10 @@ export class MCPManagerSingleton { })); } + setStatus(server: MCPServerStatus, status: MCPServerStatus["status"]) { + this.connections.get(server.id)!.status = status; + } + async getPrompt( serverName: string, promptName: string, diff --git a/core/core.ts b/core/core.ts index bac3744c6..abe73b2be 100644 --- a/core/core.ts +++ b/core/core.ts @@ -440,6 +440,7 @@ export class Core { }); on("mcp/startAuthentication", async (msg) => { await new Promise((resolve) => setTimeout(resolve, 5000)); + MCPManagerSingleton.getInstance().setStatus(msg.data, "authenticating"); const status = await performAuth(msg.data, this.ide); if (status === "AUTHORIZED") { await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); From 64702333a768c15fe2fb86a0d17154fbd59e69ed Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 29 Jul 2025 12:24:27 +0530 Subject: [PATCH 09/17] remove vscode redirect after authentication --- core/context/mcp/MCPOauth.ts | 56 ++++++++++++++++++++++++------------ core/core.ts | 37 +++++++++++------------- 2 files changed, 54 insertions(+), 39 deletions(-) diff --git a/core/context/mcp/MCPOauth.ts b/core/context/mcp/MCPOauth.ts index 58f55b34c..b746286bb 100644 --- a/core/context/mcp/MCPOauth.ts +++ b/core/context/mcp/MCPOauth.ts @@ -14,6 +14,11 @@ import http from "http"; import url from "url"; import { GlobalContext, GlobalContextType } from "../../util/GlobalContext"; +let authenticatingMCPContext = null as { + authenticatingServer: MCPServerStatus; + ide: IDE; +} | null; + const PORT = 3000; const server = http.createServer((req, res) => { @@ -21,24 +26,25 @@ const server = http.createServer((req, res) => { 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"); - } - const query = new URLSearchParams( - parsedUrl.query as Record, - ).toString(); - if (!query) { + const parsedUrl = url.parse(req.url, true); + if (!parsedUrl.query["code"]) { throw new Error("no query params found"); } - const redirectUrl = `vscode://continue.Continue?${query}`; + handleMCPOauthCode(parsedUrl.query["code"] as string); - res.writeHead(302, { - Location: redirectUrl, + const html = ` + + +Authentication Complete +Authentication Complete. You can close this page now. +`; + + res.writeHead(200, { + "Content-Type": "text/html", }); - res.end(); + res.end(html); } catch (error) { res.writeHead(400, { "Content-Type": "text/plain" }); res.end(`Unexpected redirect error: ${(error as Error).message}`); @@ -177,6 +183,10 @@ export async function getOauthToken(mcpServerUrl: string, ide: IDE) { export async function performAuth(mcpServer: MCPServerStatus, ide: IDE) { const mcpServerUrl = (mcpServer.transport as SSEOptions).url; const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide); + authenticatingMCPContext = { + authenticatingServer: mcpServer, + ide, + }; return await auth(authProvider, { serverUrl: mcpServerUrl, }); @@ -185,12 +195,13 @@ export async function performAuth(mcpServer: MCPServerStatus, ide: IDE) { /** * handle the authentication code received from the oauth redirect */ -export async function handleMCPOauthCode( - authorizationCode: string, - ide: IDE, - authenticatingServer: MCPServerStatus | undefined, -) { - const serverUrl = (authenticatingServer?.transport as SSEOptions).url; +export async function handleMCPOauthCode(authorizationCode: string) { + if (!authenticatingMCPContext) { + return; + } + const { ide, authenticatingServer } = authenticatingMCPContext; + const serverUrl = (authenticatingServer.transport as SSEOptions).url; + if (!serverUrl) { ide.showToast("error", "No MCP server url found for authentication"); return; @@ -201,10 +212,17 @@ export async function handleMCPOauthCode( } const authProvider = new MCPConnectionOauthProvider(serverUrl, ide); - return await auth(authProvider, { + const authStatus = await auth(authProvider, { serverUrl, authorizationCode, }); + if (authStatus === "AUTHORIZED") { + const { MCPManagerSingleton } = await import("./MCPManagerSingleton"); // put dynamic import to avoid cyclic imports + await MCPManagerSingleton.getInstance().refreshConnection( + authenticatingServer.id, + ); + } + authenticatingMCPContext = null; } export function removeMCPAuth(mcpServer: MCPServerStatus, ide: IDE) { diff --git a/core/core.ts b/core/core.ts index abe73b2be..c1c36c37c 100644 --- a/core/core.ts +++ b/core/core.ts @@ -61,11 +61,7 @@ import { } from "./config/onboarding"; import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks"; import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton"; -import { - handleMCPOauthCode, - performAuth, - removeMCPAuth, -} from "./context/mcp/MCPOauth"; +import { performAuth, removeMCPAuth } from "./context/mcp/MCPOauth"; import { setMdmLicenseKey } from "./control-plane/mdm/mdm"; import { ApplyAbortManager } from "./edit/applyAbortManager"; import { streamDiffLines } from "./edit/streamDiffLines"; @@ -446,21 +442,22 @@ export class Core { await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); } }); - on("mcp/sendOauthCode", async (msg) => { - const authenticatingServer = MCPManagerSingleton.getInstance() - .getStatuses() - .find((s) => s.status === "authenticating"); - const authStatus = await handleMCPOauthCode( - msg.data.code, - this.ide, - authenticatingServer, - ); - if (authStatus === "AUTHORIZED" && authenticatingServer) { - await MCPManagerSingleton.getInstance().refreshConnection( - authenticatingServer.id, - ); - } - }); + // TODO: remove this protocol altogher along with vscode counterpart + // on("mcp/sendOauthCode", async (msg) => { + // const authenticatingServer = MCPManagerSingleton.getInstance() + // .getStatuses() + // .find((s) => s.status === "authenticating"); + // const authStatus = await handleMCPOauthCode( + // msg.data.code, + // this.ide, + // authenticatingServer, + // ); + // if (authStatus === "AUTHORIZED" && authenticatingServer) { + // await MCPManagerSingleton.getInstance().refreshConnection( + // authenticatingServer.id, + // ); + // } + // }); on("mcp/removeAuthentication", async (msg) => { removeMCPAuth(msg.data, this.ide); await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); From 2bc7f158640be5ba9fb0f46eff48af4af4af631d Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 29 Jul 2025 12:25:56 +0530 Subject: [PATCH 10/17] remove mcp/sendOauthCode protocol --- core/core.ts | 16 ---------------- core/protocol/core.ts | 6 ------ .../vscode/src/extension/VsCodeExtension.ts | 8 -------- 3 files changed, 30 deletions(-) diff --git a/core/core.ts b/core/core.ts index c1c36c37c..4e406fa3f 100644 --- a/core/core.ts +++ b/core/core.ts @@ -442,22 +442,6 @@ export class Core { await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); } }); - // TODO: remove this protocol altogher along with vscode counterpart - // on("mcp/sendOauthCode", async (msg) => { - // const authenticatingServer = MCPManagerSingleton.getInstance() - // .getStatuses() - // .find((s) => s.status === "authenticating"); - // const authStatus = await handleMCPOauthCode( - // msg.data.code, - // this.ide, - // authenticatingServer, - // ); - // if (authStatus === "AUTHORIZED" && authenticatingServer) { - // await MCPManagerSingleton.getInstance().refreshConnection( - // authenticatingServer.id, - // ); - // } - // }); on("mcp/removeAuthentication", async (msg) => { removeMCPAuth(msg.data, this.ide); await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); diff --git a/core/protocol/core.ts b/core/protocol/core.ts index daacaa4f1..086ba2104 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -145,12 +145,6 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, ]; "mcp/startAuthentication": [MCPServerStatus, void]; - "mcp/sendOauthCode": [ - { - code: string; - }, - void, - ]; "mcp/removeAuthentication": [MCPServerStatus, void]; "context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap]; diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 463b2ba42..32154e19a 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -440,14 +440,6 @@ 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; From c401c2cda4eb79a0ec689a1391417aa5269f4c15 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 29 Jul 2025 12:46:20 +0530 Subject: [PATCH 11/17] put a spinner to show authentication progress --- core/index.d.ts | 2 +- .../Lump/sections/mcp/MCPSection.tsx | 23 ++++++++++++------- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index f71b200bb..f9e85f72d 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1262,10 +1262,10 @@ export interface MCPOptions { } export type MCPConnectionStatus = - | "authenticating" | "connecting" | "connected" | "error" + | "authenticating" | "not-connected"; export type MCPPromptArgs = { diff --git a/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx b/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx index 51e3368da..d771aad4a 100644 --- a/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx @@ -3,6 +3,7 @@ import { ArrowPathIcon, CircleStackIcon, CommandLineIcon, + GlobeAltIcon, InformationCircleIcon, ShieldCheckIcon, ShieldExclamationIcon, @@ -20,10 +21,6 @@ import { Button } from "../../../../ui"; import EditBlockButton from "../../EditBlockButton"; import { ExploreBlocksButton } from "../ExploreBlocksButton"; -function has401Error(errors: string[]) { - return !!errors.find((error) => error.includes("401")); -} - interface MCPServerStatusProps { server: MCPServerStatus; serverFromYaml?: NonNullable[number]; @@ -61,6 +58,7 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) { }; const onRemoveAuth = async () => { + updateMCPServerStatus("authenticating"); await ideMessenger.request("mcp/removeAuthentication", server); }; @@ -76,7 +74,7 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) { style={{ fontSize: fontSize(-2), }} - className="flex flex-row items-center justify-between gap-3" + className={`flex flex-row items-center justify-between gap-3 ${server.status === "authenticating" ? "my-0.5" : ""}`} >
{/* Name and Status */} @@ -152,7 +150,7 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) {
- {server.isProtectedResource && server.status !== "authenticating" && ( + {server.isProtectedResource && ( <>
{server.status === "error" ? ( - ) : server.status === "connecting" ? null : ( + ) : server.status === "authenticating" ? ( + + ) : ( )}
- + + {server.status !== "authenticating" && ( + + {server.status === "error" ? "Authenticate" : "Logout"} + + )} )}