Merge pull request #6800 from uinstinct/mcp-oauth

feat: mcp oauth
This commit is contained in:
Dallin Romney 2025-08-12 19:36:00 -07:00 • committed by GitHub
commit 08842da68b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 560 additions and 17 deletions

View file

@ -428,6 +428,7 @@ async function configYamlToContinueConfig(options: {
timeout: server.connectionTimeout,
})),
false,
{ ide },
);
return { config: continueConfig, errors: localErrors };

View file

@ -1,12 +1,16 @@
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";
import {
IDE,
MCPConnectionStatus,
MCPOptions,
MCPPrompt,
@ -16,6 +20,7 @@ import {
MCPTool,
} from "../..";
import { getEnvPathFromUserShell } from "../../util/shellPath";
import { getOauthToken } from "./MCPOauth";
const DEFAULT_MCP_TIMEOUT = 20_000; // 20 seconds
@ -30,10 +35,23 @@ 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;
};
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[] = [];
@ -46,7 +64,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
@ -78,6 +99,7 @@ class MCPConnection {
resourceTemplates: this.resourceTemplates,
tools: this.tools,
status: this.status,
isProtectedResource: this.isProtectedResource,
};
}
@ -106,6 +128,26 @@ class MCPConnection {
this.abortController.abort();
this.abortController = new AbortController();
// currently support oauth for sse transports only
if (this.options.transport.type === "sse") {
if (!this.options.transport.requestOptions) {
this.options.transport.requestOptions = {
headers: {},
};
}
const accessToken = await getOauthToken(
this.options.transport.url,
this.extras?.ide!,
);
if (accessToken) {
this.isProtectedResource = true;
this.options.transport.requestOptions.headers = {
...this.options.transport.requestOptions.headers,
Authorization: `Bearer ${accessToken}`,
};
}
}
this.connectionPromise = Promise.race([
// If aborted by a refresh or other, cancel and don't do anything
new Promise((resolve) => {
@ -244,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" &&

View file

@ -1,7 +1,6 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { beforeEach, describe, expect, it, vi } from "vitest";
import MCPConnection from "./MCPConnection";
import { StdioOptions } from "../../index.d.js";
// Mock the shell path utility
vi.mock("../../util/shellPath", () => ({
@ -143,6 +142,7 @@ describe("MCPConnection", () => {
expect(status).toEqual({
...options,
errors: [],
isProtectedResource: false,
prompts: [],
resources: [],
resourceTemplates: [],

View file

@ -6,7 +6,7 @@ import {
StdioOptions,
TransportOptions,
} from "../..";
import MCPConnection from "./MCPConnection";
import MCPConnection, { MCPExtras } from "./MCPConnection";
export class MCPManagerSingleton {
private static instance: MCPManagerSingleton;
@ -26,12 +26,12 @@ export class MCPManagerSingleton {
}
createConnection(id: string, options: MCPOptions): MCPConnection {
if (!this.connections.has(id)) {
if (this.connections.has(id)) {
return this.connections.get(id)!;
} else {
const connection = new MCPConnection(options);
this.connections.set(id, connection);
return connection;
} else {
return this.connections.get(id)!;
}
}
@ -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
@ -73,15 +77,15 @@ export class MCPManagerSingleton {
// Add any connections that are not yet in manager
servers.forEach((server) => {
if (!this.connections.has(server.id)) {
refresh = true;
this.connections.set(server.id, new MCPConnection(server));
} else {
if (this.connections.has(server.id)) {
const conn = this.connections.get(server.id);
if (conn) {
// We need to update it. Some attributes may have changed, such as name, faviconUrl, etc.
conn.options = server;
}
} else {
refresh = true;
this.connections.set(server.id, new MCPConnection(server, extras));
}
});
@ -162,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,

View file

@ -0,0 +1,227 @@
import {
OAuthClientProvider,
auth,
} from "@modelcontextprotocol/sdk/client/auth.js";
import {
OAuthClientInformationFull,
OAuthClientInformationSchema,
OAuthTokens,
OAuthTokensSchema,
} from "@modelcontextprotocol/sdk/shared/auth.js";
import { IDE, MCPServerStatus, SSEOptions } from "../..";
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) => {
try {
if (!req.url) {
throw new Error("no url found");
}
const parsedUrl = url.parse(req.url, true);
if (!parsedUrl.query["code"]) {
throw new Error("no query params found");
}
void handleMCPOauthCode(parsedUrl.query["code"] as string);
const html = `
<!DOCTYPE html>
<html>
<head><title>Authentication Complete</title></head>
<body>Authentication Complete. You can close this page now.</body>
</html>`;
res.writeHead(200, {
"Content-Type": "text/html",
});
res.end(html);
} catch (error) {
res.writeHead(400, { "Content-Type": "text/plain" });
res.end(`Unexpected redirect error: ${(error as Error).message}`);
}
});
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();
}
get redirectUrl() {
return `http://localhost:${PORT}`; // 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?
};
}
private _getOauthStorage<K extends MCPOauthStorageKey>(key: K) {
return this.globalContext.get("mcpOauthStorage")?.[this.oauthServerUrl]?.[
key
];
}
private _updateOauthStorage<K extends MCPOauthStorageKey>(
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() {
const existingClientInformation =
this._getOauthStorage("clientInformation");
if (!existingClientInformation) {
return undefined;
}
return await OAuthClientInformationSchema.parseAsync(
existingClientInformation,
);
}
async tokens() {
const existingTokens = this._getOauthStorage("tokens");
if (!existingTokens) {
return undefined;
}
return await OAuthTokensSchema.parseAsync(existingTokens);
}
saveTokens(tokens: OAuthTokens) {
this._updateOauthStorage("tokens", tokens);
}
codeVerifier(): string | Promise<string> {
const existingCodeVerifier = this._getOauthStorage("codeVerifier");
if (!existingCodeVerifier) {
return "";
}
return existingCodeVerifier;
}
saveCodeVerifier(codeVerifier: string) {
this._updateOauthStorage("codeVerifier", codeVerifier);
}
clear() {
this._clearOauthStorage();
}
async redirectToAuthorization(authorizationUrl: URL) {
if (!server.listening) {
server.listen(PORT, () => {
console.debug(
`Server started for MCP Oauth process at http://localhost:${PORT}/`,
);
});
}
void this.ide.openUrl(authorizationUrl.toString());
}
}
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);
authenticatingMCPContext = {
authenticatingServer: mcpServer,
ide,
};
return await auth(authProvider, {
serverUrl: mcpServerUrl,
});
}
/**
* handle the authentication code received from the oauth redirect
*/
async function handleMCPOauthCode(authorizationCode: string) {
if (!authenticatingMCPContext) {
return;
}
const { ide, authenticatingServer } = authenticatingMCPContext;
const serverUrl = (authenticatingServer.transport as SSEOptions).url;
if (!serverUrl) {
void ide.showToast("error", "No MCP server url found for authentication");
return;
}
if (!authorizationCode) {
void ide.showToast(
"error",
`No MCP authorization code found for ${serverUrl}`,
);
return;
}
server.close(() => console.debug("Server for MCP Oauth process was closed"));
const authProvider = new MCPConnectionOauthProvider(serverUrl, ide);
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) {
const mcpServerUrl = (mcpServer.transport as SSEOptions).url;
const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide);
authProvider.clear();
}

View file

@ -0,0 +1,181 @@
import fs from "node:fs";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { GlobalContext } from "../../util/GlobalContext";
import { getGlobalContextFilePath } from "../../util/paths";
import { getOauthToken, performAuth, removeMCPAuth } from "./MCPOauth";
// Mock the MCP SDK auth module
vi.mock("@modelcontextprotocol/sdk/client/auth.js", () => ({
auth: vi.fn(),
}));
// Mock the MCPManagerSingleton to avoid circular imports
vi.mock("./MCPManagerSingleton", () => ({
MCPManagerSingleton: {
getInstance: vi.fn(() => ({
refreshConnection: vi.fn(),
})),
},
}));
describe("MCPOauth", () => {
let globalContextFilePath: string;
let mockIde: any;
let mockMcpServer: any;
beforeEach(() => {
// file is present in the core/test directory
globalContextFilePath = getGlobalContextFilePath();
if (fs.existsSync(globalContextFilePath)) {
fs.unlinkSync(globalContextFilePath);
}
mockIde = {
openUrl: vi.fn(),
showToast: vi.fn(),
};
mockMcpServer = {
id: "test-server",
transport: {
type: "sse",
url: "https://test-server.com",
},
};
vi.clearAllMocks();
});
afterEach(() => {
if (fs.existsSync(globalContextFilePath)) {
fs.unlinkSync(globalContextFilePath);
}
});
describe("getOauthToken", () => {
test("should return undefined when no tokens are stored", async () => {
const result = await getOauthToken("https://test-server.com", mockIde);
expect(result).toBeUndefined();
});
test("should return access token when tokens are stored", async () => {
const globalContext = new GlobalContext();
globalContext.update("mcpOauthStorage", {
"https://test-server.com": {
tokens: {
access_token: "test-access-token",
token_type: "Bearer",
},
},
});
const result = await getOauthToken("https://test-server.com", mockIde);
expect(result).toBe("test-access-token");
});
test("should handle different server URLs independently", async () => {
const globalContext = new GlobalContext();
globalContext.update("mcpOauthStorage", {
"https://server1.com": {
tokens: {
access_token: "token1",
token_type: "Bearer",
},
},
"https://server2.com": {
tokens: {
access_token: "token2",
token_type: "Bearer",
},
},
});
const result1 = await getOauthToken("https://server1.com", mockIde);
const result2 = await getOauthToken("https://server2.com", mockIde);
const result3 = await getOauthToken("https://server3.com", mockIde);
expect(result1).toBe("token1");
expect(result2).toBe("token2");
expect(result3).toBeUndefined();
});
});
describe("performAuth", () => {
test("should call auth with correct parameters and return auth result", async () => {
const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
const mockAuth = vi.mocked(auth);
mockAuth.mockResolvedValue("AUTHORIZED");
const result = await performAuth(mockMcpServer, mockIde);
expect(mockAuth).toHaveBeenCalledWith(
expect.any(Object), // MCPConnectionOauthProvider instance
{
serverUrl: "https://test-server.com",
},
);
expect(result).toBe("AUTHORIZED");
});
});
describe("removeMCPAuth", () => {
test("should clear oauth storage for the server", () => {
const globalContext = new GlobalContext();
globalContext.update("mcpOauthStorage", {
"https://test-server.com": {
tokens: {
access_token: "test-access-token",
token_type: "Bearer",
},
clientInformation: {
client_id: "test-client-id",
redirect_uris: ["http://localhost:3000"],
},
codeVerifier: "test-code-verifier",
},
"https://other-server.com": {
tokens: {
access_token: "other-access-token",
token_type: "Bearer",
},
},
});
removeMCPAuth(mockMcpServer, mockIde);
const updatedStorage = globalContext.get("mcpOauthStorage");
expect(updatedStorage).toEqual({
"https://other-server.com": {
tokens: {
access_token: "other-access-token",
token_type: "Bearer",
},
},
});
});
test("should handle non-existent server gracefully", () => {
const globalContext = new GlobalContext();
globalContext.update("mcpOauthStorage", {
"https://other-server.com": {
tokens: {
access_token: "other-access-token",
token_type: "Bearer",
},
},
});
removeMCPAuth(mockMcpServer, mockIde);
const updatedStorage = globalContext.get("mcpOauthStorage");
expect(updatedStorage).toEqual({
"https://other-server.com": {
tokens: {
access_token: "other-access-token",
token_type: "Bearer",
},
},
});
});
});
});

View file

@ -61,6 +61,7 @@ import {
} from "./config/onboarding";
import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks";
import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton";
import { performAuth, removeMCPAuth } from "./context/mcp/MCPOauth";
import { setMdmLicenseKey } from "./control-plane/mdm/mdm";
import { ApplyAbortManager } from "./edit/applyAbortManager";
import { streamDiffLines } from "./edit/streamDiffLines";
@ -418,6 +419,19 @@ export class Core {
description: prompt.description,
};
});
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);
}
});
on("mcp/removeAuthentication", async (msg) => {
removeMCPAuth(msg.data, this.ide);
await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
});
// Context providers
on("context/addDocs", async (msg) => {
void this.docsService.indexAndAdd(msg.data);

2
core/index.d.ts vendored
View file

@ -1278,6 +1278,7 @@ export type MCPConnectionStatus =
| "connecting"
| "connected"
| "error"
| "authenticating"
| "not-connected";
export type MCPPromptArgs = {
@ -1323,6 +1324,7 @@ export interface MCPTool {
export interface MCPServerStatus extends MCPOptions {
status: MCPConnectionStatus;
errors: string[];
isProtectedResource: boolean;
prompts: MCPPrompt[];
tools: MCPTool[];

View file

@ -26,6 +26,7 @@ import {
FileSymbolMap,
IdeSettings,
LLMFullCompletionOptions,
MCPServerStatus,
MessageOption,
ModelDescription,
PromptLog,
@ -130,6 +131,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
},
ContextItemWithId[],
];
"mcp/reloadServer": [
{
id: string;
@ -147,6 +149,9 @@ export type ToCoreFromIdeOrWebviewProtocol = {
description: string | undefined;
},
];
"mcp/startAuthentication": [MCPServerStatus, void];
"mcp/removeAuthentication": [MCPServerStatus, void];
"context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap];
"context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]];
"autocomplete/complete": [AutocompleteInput, string[]];

View file

@ -28,6 +28,8 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"config/updateSelectedModel",
"mcp/reloadServer",
"mcp/getPrompt",
"mcp/startAuthentication",
"mcp/removeAuthentication",
"context/getContextItems",
"context/getSymbolsForFiles",
"context/loadSubmenuItems",

View file

@ -15,6 +15,7 @@ const createMcpServer = (name: string): MCPServerStatus => ({
type: "sse",
url: "",
},
isProtectedResource: false,
});
const createMCPTool = (name: string): MCPTool => ({

View file

@ -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,14 @@ export type GlobalContextType = {
isSupportedLanceDbCpuTargetForLinux: boolean;
sharedConfig: SharedConfigSchema;
failedDocs: SiteIndexingConfig[];
mcpOauthStorage: Record<
string,
{
clientInformation?: OAuthClientInformationFull;
tokens?: OAuthTokens;
codeVerifier?: string;
}
>;
shownDeprecatedProviderWarnings: {
[providerTitle: string]: boolean;
};

View file

@ -86,6 +86,7 @@ export class VsCodeExtension {
constructor(context: vscode.ExtensionContext) {
// Register auth provider
this.workOsAuthProvider = new WorkOsAuthProvider(context, this.uriHandler);
void this.workOsAuthProvider.refreshSessions();
context.subscriptions.push(this.workOsAuthProvider);

View file

@ -3,7 +3,10 @@ import {
ArrowPathIcon,
CircleStackIcon,
CommandLineIcon,
GlobeAltIcon,
InformationCircleIcon,
ShieldCheckIcon,
ShieldExclamationIcon,
WrenchScrewdriverIcon,
} from "@heroicons/react/24/outline";
import { MCPServerStatus } from "core";
@ -30,8 +33,9 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) {
const promptsTooltipId = `${server.id}-prompts`;
const resourcesTooltipId = `${server.id}-resources`;
const errorsTooltipId = `${server.id}-errors`;
const mcpAuthTooltipId = `${server.id}-auth`;
async function onRefresh() {
const updateMCPServerStatus = (status: MCPServerStatus["status"]) => {
// optimistic config update
dispatch(
updateConfig({
@ -40,23 +44,37 @@ 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 () => {
updateMCPServerStatus("authenticating");
await ideMessenger.request("mcp/removeAuthentication", server);
};
const onRefresh = async () => {
updateMCPServerStatus("connecting");
ideMessenger.post("mcp/reloadServer", {
id: server.id,
});
}
};
return (
<div
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" : ""}`}
>
<div className="flex flex-row items-center gap-3">
{/* Name and Status */}
@ -159,8 +177,33 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) {
</div>
</div>
{/* Refresh button */}
<div className="flex items-center gap-2">
{server.isProtectedResource && (
<>
<div
className="text-lightgray flex cursor-pointer items-center hover:text-white hover:opacity-80"
data-tooltip-id={
server.status !== "authenticating" ? mcpAuthTooltipId : ""
}
>
{server.status === "error" ? (
<ShieldExclamationIcon
className="h-3 w-3"
onClick={onAuthenticate}
/>
) : server.status === "authenticating" ? (
<GlobeAltIcon className="animate-spin-slow h-3 w-3" />
) : (
<ShieldCheckIcon className="h-3 w-3" onClick={onRemoveAuth} />
)}
</div>
{server.status !== "authenticating" && (
<ToolTip place="left" id={mcpAuthTooltipId}>
{server.status === "error" ? "Authenticate" : "Logout"}
</ToolTip>
)}
</>
)}
<EditBlockButton
blockType={"mcpServers"}
block={serverFromYaml}