diff --git a/docs/mcp/connecting-to-a-remote-server.mdx b/docs/mcp/connecting-to-a-remote-server.mdx index 26c3ea99..e1edbb91 100644 --- a/docs/mcp/connecting-to-a-remote-server.mdx +++ b/docs/mcp/connecting-to-a-remote-server.mdx @@ -29,11 +29,33 @@ The "Remote Servers" tab allows you to connect to any MCP server that's accessib 2. Fill in the required information: - **Server Name**: Provide a unique, descriptive name for the server - **Server URL**: Enter the complete URL endpoint of the MCP server (e.g., `https://example.com/mcp-sse`) + - **Transport Type**: Select the connection protocol (Streamable HTTP is recommended for modern servers) 3. Click "Add Server" to initiate the connection 4. Cline will attempt to connect to the server and display the connection status > **Note**: When connecting to a remote server, ensure you trust the source, as MCP servers can execute code in your environment. +#### Transport Types + +Cline supports two transport protocols for remote MCP servers: + +- **Streamable HTTP (Recommended)**: The modern MCP transport protocol with better performance, reliability, and full OAuth 2.1 authentication support. Use this for most remote servers. +- **SSE (Legacy)**: Server-Sent Events transport. Use this only if the server specifically requires SSE or doesn't support Streamable HTTP. + +#### OAuth Authentication + +Some MCP servers (like Vercel's MCP) require OAuth authentication to access your data securely. When connecting to an OAuth-enabled server: + +1. Add the server as usual with its URL +2. If the server requires authentication, you'll see an error message asking to authenticate. +3. Click the **"Authenticate"** button that appears +4. Your browser will open to the server's authorization page +5. Sign in and grant permission +6. You'll be redirected back to Cline automatically +7. The server will connect and show a green status dot + +Once authenticated, your credentials are securely stored and the server will reconnect automatically when you reload Cline. You won't need to authenticate again unless you delete the server or your credentials expire. + ### Remote Server Discovery If you're looking for MCP servers to connect to, several third-party marketplaces provide directories of available servers with various capabilities. @@ -90,9 +112,20 @@ Toggle the switch next to each server to enable or disable it: If a server fails to connect: 1. An error message will be displayed with details about the failure -2. Check that the server URL is correct and the server is running -3. Use the "Restart Server" button to attempt reconnection -4. If problems persist, you can delete the server and try adding it again +2. **For OAuth errors**: Click the "Authenticate" button to complete the authorization flow +3. Check that the server URL is correct and the server is running +4. Try selecting a different transport type (Streamable HTTP vs SSE) +5. Use the "Restart Server" button to attempt reconnection +6. If problems persist, you can delete the server and try adding it again + +#### OAuth-Specific Issues + +If you're having trouble authenticating with an OAuth-enabled server: + +- **"Authentication required" persists**: Make sure you completed the authorization flow in your browser and didn't cancel it +- **Browser doesn't open**: Check your system's default browser settings and ensure external URLs can be opened +- **Redirect errors**: Verify you're using the latest version of Cline - older versions may not support OAuth +- **Reset authentication**: Delete the server and re-add it to start fresh with a new OAuth flow ### Advanced Configuration @@ -105,10 +138,11 @@ For advanced users, Cline stores MCP server configurations in a JSON file that c { "mcpServers": { "exampleServer": { - "url": "https://example.com/mcp-sse", + "url": "https://example.com/mcp-server", + "type": "streamableHttp", "disabled": false, "autoApprove": ["tool1", "tool2"], - "timeout": 30 + "timeout": 60 } } } @@ -117,9 +151,10 @@ For advanced users, Cline stores MCP server configurations in a JSON file that c Key configuration options: - **url**: The endpoint URL (for remote servers) +- **type**: Transport protocol - `"streamableHttp"` (recommended) or `"sse"` (legacy) - **disabled**: Whether the server is currently enabled (true/false) - **autoApprove**: List of tool names that don't require confirmation -- **timeout**: Maximum time in seconds to wait for server responses +- **timeout**: Maximum time in seconds to wait for server responses (default: 60) For additional MCP settings, click the "Advanced MCP Settings" link to access VSCode settings. @@ -130,3 +165,20 @@ Once connected, Cline can use the tools and resources provided by the MCP server 1. A tool approval prompt will appear (unless auto-approved) 2. Review the tool details and parameters before approving 3. The tool will execute and return results to Cline + +### Example: Connecting to Vercel MCP + +[Vercel MCP](https://vercel.com/docs/mcp/vercel-mcp) is an OAuth-enabled server that provides tools for managing your Vercel projects and deployments: + +1. Click "Remote Servers" tab +2. Enter: + - **Server Name**: `vercel` + - **Server URL**: `https://mcp.vercel.com` + - **Transport Type**: Streamable HTTP (pre-selected) +3. Click "Add Server" +4. You'll see "Authentication required" - click the **"Authenticate"** button +5. Sign in to Vercel in your browser and authorize Cline +6. Return to Cline - the server will automatically connect +7. Vercel's tools (deploy, logs, projects) are now available to Cline! + +Your Vercel authentication persists across sessions, so you won't need to re-authenticate each time you use Cline. diff --git a/package-lock.json b/package-lock.json index 73f868de..f523f217 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "claude-dev", - "version": "3.36.0", + "version": "3.36.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "claude-dev", - "version": "3.36.0", + "version": "3.36.1", "license": "Apache-2.0", "dependencies": { "@anthropic-ai/sdk": "^0.37.0", diff --git a/package.json b/package.json index 9dd43fba..88623829 100644 --- a/package.json +++ b/package.json @@ -149,6 +149,12 @@ "category": "Cline", "when": "cline.isDevMode" }, + { + "command": "cline.dev.expireMcpOAuthTokens", + "title": "Expire MCP OAuth Tokens (for testing)", + "category": "Cline", + "when": "cline.isDevMode" + }, { "command": "cline.addToChat", "title": "Add to Cline", diff --git a/proto/cline/mcp.proto b/proto/cline/mcp.proto index 231eb5eb..c30ed799 100644 --- a/proto/cline/mcp.proto +++ b/proto/cline/mcp.proto @@ -18,6 +18,7 @@ service McpService { rpc toggleToolAutoApprove(ToggleToolAutoApproveRequest) returns (McpServers); rpc refreshMcpMarketplace(EmptyRequest) returns (McpMarketplaceCatalog); rpc openMcpSettings(EmptyRequest) returns (Empty); + rpc authenticateMcpServer(StringRequest) returns (Empty); // Subscribe to MCP marketplace catalog updates rpc subscribeToMcpMarketplaceCatalog(EmptyRequest) returns (stream McpMarketplaceCatalog); @@ -43,6 +44,7 @@ message AddRemoteMcpServerRequest { Metadata metadata = 1; string server_name = 2; string server_url = 3; + optional string transport_type = 4; } message ToggleToolAutoApproveRequest { @@ -91,6 +93,8 @@ message McpServer { repeated McpResourceTemplate resource_templates = 7; optional bool disabled = 8; optional int32 timeout = 9; + optional bool oauth_required = 10; + optional string oauth_auth_status = 11; } message McpServers { diff --git a/proto/cline/state.proto b/proto/cline/state.proto index 9d1d2d60..01ee7ed1 100644 --- a/proto/cline/state.proto +++ b/proto/cline/state.proto @@ -89,6 +89,7 @@ message Secrets { optional string oca_api_key = 37; optional string oca_refresh_token = 38; optional string hicap_api_key = 39; + optional string mcp_oauth_secrets = 40; } message Settings { diff --git a/src/core/controller/index.ts b/src/core/controller/index.ts index f4caad32..1d60d2ed 100644 --- a/src/core/controller/index.ts +++ b/src/core/controller/index.ts @@ -640,6 +640,23 @@ export class Controller { } } + async handleMcpOAuthCallback(serverHash: string, code: string, state: string | null) { + try { + await this.mcpHub.completeOAuth(serverHash, code, state) + await this.postStateToWebview() + HostProvider.window.showMessage({ + type: ShowMessageType.INFORMATION, + message: `Successfully authenticated MCP server`, + }) + } catch (error) { + console.error("Failed to complete MCP OAuth:", error) + HostProvider.window.showMessage({ + type: ShowMessageType.ERROR, + message: `Failed to authenticate MCP server`, + }) + } + } + async handleTaskCreation(prompt: string) { await sendChatButtonClickedEvent() await this.initTask(prompt) diff --git a/src/core/controller/mcp/addRemoteMcpServer.ts b/src/core/controller/mcp/addRemoteMcpServer.ts index fc9037f3..d0224bc2 100644 --- a/src/core/controller/mcp/addRemoteMcpServer.ts +++ b/src/core/controller/mcp/addRemoteMcpServer.ts @@ -20,7 +20,7 @@ export async function addRemoteMcpServer(controller: Controller, request: AddRem } // Call the McpHub method to add the remote server - const servers = await controller.mcpHub?.addRemoteServer(request.serverName, request.serverUrl) + const servers = await controller.mcpHub?.addRemoteServer(request.serverName, request.serverUrl, request.transportType) const protoServers = convertMcpServersToProtoMcpServers(servers) diff --git a/src/core/controller/mcp/authenticateMcpServer.ts b/src/core/controller/mcp/authenticateMcpServer.ts new file mode 100644 index 00000000..acd77ee4 --- /dev/null +++ b/src/core/controller/mcp/authenticateMcpServer.ts @@ -0,0 +1,26 @@ +import type { StringRequest } from "@shared/proto/cline/common" +import { Empty } from "@shared/proto/cline/common" +import type { Controller } from "../index" + +/** + * Initiates OAuth authentication for an MCP server + * @param controller The controller instance + * @param request The request containing server name + * @returns Empty response + */ +export async function authenticateMcpServer(controller: Controller, request: StringRequest): Promise { + try { + const serverName = request.value + if (!serverName) { + throw new Error("Server name is required") + } + + // Call the McpHub method to initiate OAuth + await controller.mcpHub?.initiateOAuth(serverName) + + return Empty.create() + } catch (error) { + console.error(`Failed to initiate OAuth for MCP server:`, error) + throw error + } +} diff --git a/src/core/storage/utils/state-helpers.ts b/src/core/storage/utils/state-helpers.ts index b3b34973..f1bf01da 100644 --- a/src/core/storage/utils/state-helpers.ts +++ b/src/core/storage/utils/state-helpers.ts @@ -54,6 +54,7 @@ export async function readSecretsFromDisk(context: ExtensionContext): Promise, @@ -97,6 +98,7 @@ export async function readSecretsFromDisk(context: ExtensionContext): Promise, context.secrets.get("hicapApiKey") as Promise, context.secrets.get("aihubmixApiKey") as Promise, + context.secrets.get("mcpOAuthSecrets") as Promise, context.secrets.get("nousResearchApiKey") as Promise, ]) @@ -142,6 +144,7 @@ export async function readSecretsFromDisk(context: ExtensionContext): Promise context.secrets.delete(key))) diff --git a/src/dev/commands/tasks.ts b/src/dev/commands/tasks.ts index 31be30d1..cd777da6 100644 --- a/src/dev/commands/tasks.ts +++ b/src/dev/commands/tasks.ts @@ -13,6 +13,44 @@ import { ShowMessageType } from "@/shared/proto/host/window" */ export function registerTaskCommands(controller: Controller): vscode.Disposable[] { return [ + vscode.commands.registerCommand("cline.dev.expireMcpOAuthTokens", async () => { + try { + const stateManager = controller.stateManager + const secretsJson = stateManager.getSecretKey("mcpOAuthSecrets") + + if (!secretsJson) { + vscode.window.showInformationMessage("No MCP OAuth secrets found - no servers are authenticated") + return + } + + const secrets = JSON.parse(secretsJson) + let expiredCount = 0 + + // Set all tokens_saved_at to 2 hours ago (past expiration) + for (const hash in secrets) { + if (secrets[hash].tokens_saved_at) { + secrets[hash].tokens_saved_at = Date.now() - 2 * 60 * 60 * 1000 // 2 hours ago + expiredCount++ + console.log(`[Dev] Expired tokens for hash: ${hash}`) + } + } + + stateManager.setSecret("mcpOAuthSecrets", JSON.stringify(secrets)) + + const action = await vscode.window.showInformationMessage( + `Expired ${expiredCount} MCP OAuth token(s). Reload window to test token refresh flow.`, + "Reload Window", + "Cancel", + ) + + if (action === "Reload Window") { + vscode.commands.executeCommand("workbench.action.reloadWindow") + } + } catch (error) { + vscode.window.showErrorMessage(`Failed to expire tokens: ${error}`) + console.error("[Dev] Error expiring MCP OAuth tokens:", error) + } + }), vscode.commands.registerCommand("cline.dev.createTestTasks", async () => { const count = ( await HostProvider.window.showInputBox({ diff --git a/src/services/mcp/McpHub.ts b/src/services/mcp/McpHub.ts index d0a49902..4ab2ccc5 100644 --- a/src/services/mcp/McpHub.ts +++ b/src/services/mcp/McpHub.ts @@ -1,6 +1,7 @@ import { setTimeout as setTimeoutPromise } from "node:timers/promises" import { sendMcpServersUpdate } from "@core/controller/mcp/subscribeToMcpServers" import { GlobalFileNames } from "@core/storage/disk" +import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js" import { Client } from "@modelcontextprotocol/sdk/client/index.js" import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js" import { getDefaultEnvironment, StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js" @@ -34,8 +35,10 @@ import ReconnectingEventSource from "reconnecting-eventsource" import { z } from "zod" import { HostProvider } from "@/hosts/host-provider" import { ShowMessageType } from "@/shared/proto/host/window" +import { getServerAuthHash } from "@/utils/mcpAuth" import { TelemetryService } from "../telemetry/TelemetryService" import { DEFAULT_REQUEST_TIMEOUT_MS } from "./constants" +import { McpOAuthManager } from "./McpOAuthManager" import { BaseConfigSchema, McpSettingsSchema, ServerConfigSchema } from "./schemas" import { McpConnection, McpServerConfig, Transport } from "./types" export class McpHub { @@ -43,6 +46,7 @@ export class McpHub { private getSettingsDirectoryPath: () => Promise private clientVersion: string private telemetryService: TelemetryService + private mcpOAuthManager: McpOAuthManager private settingsWatcher?: FSWatcher private fileWatchers: Map = new Map() @@ -75,6 +79,7 @@ export class McpHub { this.getSettingsDirectoryPath = getSettingsDirectoryPath this.clientVersion = clientVersion this.telemetryService = telemetryService + this.mcpOAuthManager = new McpOAuthManager() this.watchMcpSettingsFile() this.initializeMcpServers() } @@ -242,6 +247,12 @@ export class McpHub { let transport: StdioClientTransport | SSEClientTransport | StreamableHTTPClientTransport + // Create OAuth provider for remote transports (SSE and HTTP) + const authProvider = + config.type === "sse" || config.type === "streamableHttp" + ? await this.mcpOAuthManager.getOrCreateProvider(name, config.url) + : undefined + switch (config.type) { case "stdio": { transport = new StdioClientTransport({ @@ -304,6 +315,7 @@ export class McpHub { } case "sse": { const sseOptions = { + authProvider, requestInit: { headers: config.headers, }, @@ -311,7 +323,26 @@ export class McpHub { const reconnectingEventSourceOptions = { max_retry_time: 5000, withCredentials: !!config.headers?.["Authorization"], + // IMPORTANT: Custom fetch function is required for SSE with OAuth + // When we provide eventSourceInit, we override the SDK's default fetch + // The SDK's default would call _commonHeaders() for auth, but since we're + // overriding it, we must provide our own fetch that: + // 1. Calls authProvider.tokens() dynamically (not captured once) + // 2. Gets fresh tokens for each connection/reconnection + // 3. Allows the SDK to auto-refresh expired tokens + // Without this, tokens would be stale and fail after expiry + fetch: authProvider + ? async (url: string | URL, init?: RequestInit) => { + const tokens = await authProvider.tokens() // Dynamic - gets fresh tokens + const headers = new Headers(init?.headers) + if (tokens?.access_token) { + headers.set("Authorization", `Bearer ${tokens.access_token}`) + } + return fetch(url.toString(), { ...init, headers }) + } + : undefined, } + // Use ReconnectingEventSource for auto-reconnection on connection drops global.EventSource = ReconnectingEventSource transport = new SSEClientTransport(new URL(config.url), { ...sseOptions, @@ -332,8 +363,9 @@ export class McpHub { } case "streamableHttp": { transport = new StreamableHTTPClientTransport(new URL(config.url), { + authProvider, requestInit: { - headers: config.headers, + headers: config.headers ?? undefined, }, }) transport.onerror = async (error) => { @@ -359,14 +391,46 @@ export class McpHub { status: "connecting", disabled: config.disabled, uid: this.getMcpServerKey(name), + oauthRequired: false, + oauthAuthStatus: "authenticated", }, client, transport, + authProvider, } this.connections.push(connection) - // Connect - await client.connect(transport) + // Connect - wrap in try-catch to detect OAuth requirement + try { + await client.connect(transport) + } catch (error) { + if (error instanceof UnauthorizedError) { + // Server requires OAuth authentication + console.log(`Server "${name}" requires OAuth authentication`) + const unauthConnection: McpConnection = { + server: { + name, + config: JSON.stringify(config), + status: "disconnected", + disabled: false, + oauthRequired: true, + oauthAuthStatus: "unauthenticated", + error: "This MCP server requires authentication to get started.", + uid: this.getMcpServerKey(name), + }, + client, + transport, + authProvider, // CRITICAL: Keep authProvider so it's available when user authenticates! + } + // Replace the connection with unauthenticated version + this.connections = this.connections.filter((conn) => conn.server.name !== name) + this.connections.push(unauthConnection) + await this.notifyWebviewOfServerChanges() + return // Don't throw, just mark as needs auth + } + // Re-throw other errors + throw error + } connection.server.status = "connected" connection.server.error = "" @@ -557,6 +621,20 @@ export class McpHub { } } + async clearOAuthForConnection(name: string): Promise { + const connection = this.connections.find((conn) => conn.server.name === name) + if (connection) { + try { + const config = JSON.parse(connection.server.config) + if (config.url) { + await this.mcpOAuthManager.clearServerAuth(name, config.url) + } + } catch (error) { + console.error(`Failed to clear OAuth data for ${name}:`, error) + } + } + } + async updateServerConnectionsRPC(newServers: Record): Promise { this.isConnecting = true this.removeAllFileWatchers() @@ -591,7 +669,7 @@ export class McpHub { if (config.type === "stdio") { this.setupFileWatcher(name, config) } - await this.deleteConnection(name) + await this.deleteConnection(name) // Don't clear OAuth - just reconnecting with new config await this.connectToServer(name, config, "rpc") console.log(`Reconnected MCP server with updated config: ${name}`) } catch (error) { @@ -613,7 +691,8 @@ export class McpHub { // Delete removed servers for (const name of currentNames) { if (!newNames.has(name)) { - await this.deleteConnection(name) + await this.clearOAuthForConnection(name) // Clear OAuth data first + await this.deleteConnection(name) // Then delete connection console.log(`Deleted MCP server: ${name}`) } } @@ -1022,7 +1101,11 @@ export class McpHub { } } - public async addRemoteServer(serverName: string, serverUrl: string): Promise { + public async addRemoteServer( + serverName: string, + serverUrl: string, + transportType: string = "streamableHttp", + ): Promise { try { const settings = await this.readAndValidateMcpSettingsFile() if (!settings) { @@ -1040,6 +1123,7 @@ export class McpHub { const serverConfig = { url: serverUrl, + type: transportType, disabled: false, autoApprove: [], } @@ -1076,6 +1160,9 @@ export class McpHub { */ public async deleteServerRPC(serverName: string): Promise { try { + // Clear OAuth data BEFORE removing from config (while we still have the connection/URL) + await this.clearOAuthForConnection(serverName) + const settingsPath = await this.getMcpSettingsFilePath() const content = await fs.readFile(settingsPath, "utf-8") const config = JSON.parse(content) @@ -1175,6 +1262,70 @@ export class McpHub { //console.log("[MCP Debug] Notification callback cleared") } + /** + * Initiates OAuth flow for a server + * Opens browser to authorization URL + */ + async initiateOAuth(serverName: string): Promise { + const connection = this.connections.find((conn) => conn.server.name === serverName) + if (!connection) { + throw new Error(`No connection found for server: ${serverName}`) + } + + // Extract serverUrl from config + const config = JSON.parse(connection.server.config) + const serverUrl = config.url + if (!serverUrl) { + throw new Error(`No URL found in config for server: ${serverName}`) + } + + // Start OAuth flow - opens the SDK-generated authorization URL in browser + await this.mcpOAuthManager.startOAuthFlow(serverName, serverUrl) + } + + /** + * Completes OAuth flow after callback + * Validates state, calls finishAuth, and reconnects + */ + async completeOAuth(serverHash: string, code: string, state: string | null): Promise { + // Find the connection by matching the server hash + const connection = this.connections.find((conn) => { + const config = JSON.parse(conn.server.config) + if (config.url) { + const hash = getServerAuthHash(conn.server.name, config.url) + return hash === serverHash + } + return false + }) + + if (!connection) { + throw new Error(`No connection found for server hash: ${serverHash}`) + } + + // Validate state for CSRF protection (if provided) + if (state && !this.mcpOAuthManager.validateAndClearState(serverHash, state)) { + throw new Error("Invalid OAuth state - possible CSRF attack") + } + + // Call finishAuth on the transport - SDK handles token exchange + // finishAuth is only available on SSE and StreamableHTTP transports + if (connection.transport instanceof SSEClientTransport || connection.transport instanceof StreamableHTTPClientTransport) { + await connection.transport.finishAuth(code) + } else { + throw new Error("OAuth is only supported for SSE and HTTP transports") + } + + console.log(`[McpOAuth] Authentication completed for ${connection.server.name}`) + + // Update server status + connection.server.oauthAuthStatus = "authenticated" + connection.server.oauthRequired = true + connection.server.error = "" + + // Restart connection to complete setup with authenticated transport + await this.restartConnection(connection.server.name) + } + async dispose(): Promise { this.removeAllFileWatchers() for (const connection of this.connections) { diff --git a/src/services/mcp/McpOAuthManager.ts b/src/services/mcp/McpOAuthManager.ts new file mode 100644 index 00000000..a75b9c7a --- /dev/null +++ b/src/services/mcp/McpOAuthManager.ts @@ -0,0 +1,363 @@ +import { StateManager } from "@core/storage/StateManager" +import { OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.js" +import type { OAuthClientInformationFull, OAuthClientMetadata, OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js" +import crypto from "crypto" +import { HostProvider } from "@/hosts/host-provider" +import { openExternal } from "@/utils/env" +import { getMcpServerCallbackPath, getServerAuthHash } from "@/utils/mcpAuth" + +/** + * Structure for all OAuth data stored in the single mcpOAuthSecrets JSON + */ +interface McpOAuthSecrets { + [serverHash: string]: { + tokens?: OAuthTokens + tokens_saved_at?: number + client_info?: OAuthClientInformationFull + code_verifier?: string + oauth_state?: string + oauth_state_timestamp?: number + pending_auth_url?: string + } +} + +/** + * Helper to read OAuth secrets from storage + */ +function getMcpOAuthSecrets(): McpOAuthSecrets { + const stateManager = StateManager.get() + const secretsJson = stateManager.getSecretKey("mcpOAuthSecrets") + if (!secretsJson) { + return {} + } + try { + return JSON.parse(secretsJson) as McpOAuthSecrets + } catch (error) { + console.error("[McpOAuth] Failed to parse MCP OAuth secrets:", error) + return {} + } +} + +/** + * Helper to save OAuth secrets to storage + */ +function saveMcpOAuthSecrets(secrets: McpOAuthSecrets): void { + const stateManager = StateManager.get() + stateManager.setSecret("mcpOAuthSecrets", JSON.stringify(secrets)) +} + +/** + * Implementation of OAuthClientProvider for Cline + * Manages OAuth state and token storage for a single MCP server + */ +class ClineOAuthClientProvider implements OAuthClientProvider { + private serverName: string + private serverUrl: string + private _redirectUrl: string + private serverHash: string + + constructor(serverName: string, serverUrl: string) { + this.serverName = serverName + this.serverUrl = serverUrl + this.serverHash = getServerAuthHash(serverName, serverUrl) + + // Redirect URL will be set when initialize() is called + this._redirectUrl = "" + } + + async initialize(): Promise { + // Get the base callback URL and construct full redirect URL + const baseCallbackUrl = await HostProvider.get().getCallbackUrl() + const callbackPath = getMcpServerCallbackPath(this.serverName, this.serverUrl) + this._redirectUrl = `${baseCallbackUrl}${callbackPath}` + } + + get redirectUrl(): string { + return this._redirectUrl + } + + get clientMetadata(): OAuthClientMetadata { + return { + redirect_uris: [this._redirectUrl], + token_endpoint_auth_method: "none", + grant_types: ["authorization_code", "refresh_token"], + response_types: ["code"], + client_name: "Cline", + client_uri: "https://cline.bot", + software_id: "cline", + } + } + + state(): string { + // State is managed through storage, not instance variable + return crypto.randomBytes(32).toString("hex") + } + + async clientInformation(): Promise { + const secrets = getMcpOAuthSecrets() + return secrets[this.serverHash]?.client_info + } + + async saveClientInformation(clientInformation: OAuthClientInformationFull): Promise { + const secrets = getMcpOAuthSecrets() + if (!secrets[this.serverHash]) { + secrets[this.serverHash] = {} + } + secrets[this.serverHash].client_info = clientInformation + saveMcpOAuthSecrets(secrets) + } + + async tokens(): Promise { + // Called by the SDK to check if we have valid tokens + // This is called: + // - During connection setup (to check if auth is needed) + // - Before each request (to include Authorization header) + // - During token refresh (to get refresh_token) + // + // IMPORTANT: We should return expired tokens if they have a refresh_token + // The SDK will automatically attempt to refresh them + // Only return undefined if we have NO tokens at all + + const secrets = getMcpOAuthSecrets() + const serverData = secrets[this.serverHash] + + if (!serverData?.tokens) { + return undefined + } + + // Check token expiration if timestamp exists + if (serverData.tokens_saved_at && serverData.tokens.expires_in) { + const expiresInMs = serverData.tokens.expires_in * 1000 + + if (serverData.tokens_saved_at + expiresInMs < Date.now()) { + // Token is expired + // If we have a refresh_token, return the expired tokens so SDK can refresh + // Otherwise return undefined to trigger full re-authentication + if (serverData.tokens.refresh_token) { + console.log(`[McpOAuth] Token expired for ${this.serverName}, will attempt refresh`) + return serverData.tokens + } else { + return undefined + } + } + } + + return serverData.tokens + } + + async saveTokens(tokens: OAuthTokens): Promise { + // Called by the SDK after successful token exchange + // Flow: finishAuth(code) → SDK's auth() → exchangeAuthorization() → THIS METHOD + // Stores tokens in the single mcpOAuthSecrets JSON for persistence + console.log(`[McpOAuth] Tokens saved for ${this.serverName}`) + + const secrets = getMcpOAuthSecrets() + if (!secrets[this.serverHash]) { + secrets[this.serverHash] = {} + } + + secrets[this.serverHash].tokens = tokens + secrets[this.serverHash].tokens_saved_at = Date.now() + saveMcpOAuthSecrets(secrets) + } + + async redirectToAuthorization(authorizationUrl: URL): Promise { + // ======================================================================== + // IMPORTANT: This is called AUTOMATICALLY by the MCP SDK during connection + // ======================================================================== + // + // Flow: + // 1. Extension loads → McpHub.connectToServer() is called + // 2. authProvider.tokens() returns undefined (no tokens yet) + // 3. client.connect(transport) is called + // 4. SDK detects no tokens → calls auth(provider, {serverUrl}) + // 5. SDK internally calls startAuthorization() to generate OAuth URL + // 6. SDK calls THIS METHOD with the generated authorizationUrl + // 7. SDK throws UnauthorizedError (caught by McpHub to show "Authenticate" button) + // + // Our Strategy: + // - Store the auth URL and state but DON'T open browser yet + // - Wait for user to explicitly click "Authenticate" button + // - When clicked, retrieve stored URL and open browser (see startOAuthFlow()) + // + // This prevents automatic browser popups on every extension load! + // ======================================================================== + + // Guard: Check if we already have valid tokens + // If tokens exist, this method shouldn't be called (SDK would use them) + // But if it is called, don't overwrite existing auth state + const existingTokens = await this.tokens() + if (existingTokens && existingTokens.access_token) { + console.warn(`[McpOAuth] Preserving existing tokens for ${this.serverName}`) + return + } + + // Generate and add state parameter for CSRF protection + const state = crypto.randomBytes(32).toString("hex") + authorizationUrl.searchParams.set("state", state) + + // Save state, timestamp, and the complete auth URL for later use + // These will be used when the user clicks "Authenticate" button + const secrets = getMcpOAuthSecrets() + if (!secrets[this.serverHash]) { + secrets[this.serverHash] = {} + } + + secrets[this.serverHash].oauth_state = state + secrets[this.serverHash].oauth_state_timestamp = Date.now() + secrets[this.serverHash].pending_auth_url = authorizationUrl.toString() + saveMcpOAuthSecrets(secrets) + + console.log(`[McpOAuth] OAuth required for ${this.serverName} - user must click Authenticate button`) + } + + async saveCodeVerifier(codeVerifier: string): Promise { + // Called by SDK when starting authorization flow (PKCE) + // The verifier is used later in finishAuth() to exchange the auth code for tokens + const secrets = getMcpOAuthSecrets() + if (!secrets[this.serverHash]) { + secrets[this.serverHash] = {} + } + secrets[this.serverHash].code_verifier = codeVerifier + saveMcpOAuthSecrets(secrets) + } + + async codeVerifier(): Promise { + // Called by SDK during finishAuth() to retrieve the PKCE verifier + // Used to prove that the same client that started auth is finishing it + const secrets = getMcpOAuthSecrets() + const verifier = secrets[this.serverHash]?.code_verifier + + if (!verifier) { + throw new Error(`No code verifier found for ${this.serverName}`) + } + + return verifier + } + + /** + * Check if provider has valid authentication + */ + async isAuthenticated(): Promise { + const tokens = await this.tokens() + return Boolean(tokens && tokens.access_token) + } + + /** + * Get the server hash for this provider + */ + getServerHash(): string { + return this.serverHash + } +} + +/** + * Manages OAuth authentication for MCP servers + * Creates and manages OAuthClientProvider instances and handles token storage + */ +export class McpOAuthManager { + private providers: Map = new Map() + // OAuth state parameter timeout - prevents replay attacks + // The state is used for CSRF protection during the redirect back from the OAuth provider + // Users typically complete the OAuth flow within seconds/minutes of clicking "Authenticate" + // but we allow 10 minutes in case they get distracted or need to create an account + // After 10 minutes, the state expires and user must click "Authenticate" again for security + private readonly STATE_EXPIRY_MS = 10 * 60 * 1000 // 10 minutes + + /** + * Gets or creates an OAuthClientProvider for a server + * Note: This is async now because we need to initialize the redirect URL + */ + async getOrCreateProvider(serverName: string, serverUrl: string): Promise { + const key = `${serverName}:${serverUrl}` + if (this.providers.has(key)) { + return this.providers.get(key)! + } + + // Create provider + const provider = new ClineOAuthClientProvider(serverName, serverUrl) + await provider.initialize() // Sets the redirect URL + this.providers.set(key, provider) + return provider + } + + /** + * Validates and clears stored OAuth state using hash-based lookup + */ + validateAndClearState(serverHash: string, state: string): boolean { + const secrets = getMcpOAuthSecrets() + const serverData = secrets[serverHash] + + if (!serverData?.oauth_state) { + console.error(`No stored state found for server hash: ${serverHash}`) + return false + } + + // Check if state has expired + if (serverData.oauth_state_timestamp) { + if (Date.now() - serverData.oauth_state_timestamp > this.STATE_EXPIRY_MS) { + console.error(`OAuth state expired for server hash: ${serverHash}`) + // Clear expired state + delete serverData.oauth_state + delete serverData.oauth_state_timestamp + saveMcpOAuthSecrets(secrets) + return false + } + } + + // Validate state matches + const isValid = serverData.oauth_state === state + + // Clear state after validation + delete serverData.oauth_state + delete serverData.oauth_state_timestamp + saveMcpOAuthSecrets(secrets) + + return isValid + } + + /** + * Opens the browser to the stored OAuth URL when user clicks "Authenticate" + * + * This retrieves the authorization URL that was stored by redirectToAuthorization() + * when the SDK auto-detected that OAuth was needed during connection. + * + * Flow: + * 1. User sees "Authenticate" button (because UnauthorizedError was caught) + * 2. User clicks button → UI calls authenticateMcpServer RPC + * 3. Controller calls mcpHub.initiateOAuth() + * 4. McpHub calls THIS METHOD + * 5. We retrieve the stored auth URL (generated by SDK, includes state) + * 6. We open browser to that URL + * 7. User authorizes → callback with code → completeOAuth() + */ + async startOAuthFlow(serverName: string, serverUrl: string): Promise { + const serverHash = getServerAuthHash(serverName, serverUrl) + const secrets = getMcpOAuthSecrets() + const storedAuthUrl = secrets[serverHash]?.pending_auth_url + + if (storedAuthUrl) { + // Use the URL that the SDK generated (with state already added in redirectToAuthorization) + await openExternal(storedAuthUrl) + } else { + // Fallback: if no stored URL, the SDK hasn't been triggered yet + // This could happen if the server was just added but connection hasn't been attempted + throw new Error(`No pending authorization URL found for ${serverName}. Please try restarting the server first.`) + } + } + + /** + * Clears all OAuth data for a server (used when server is deleted) + */ + async clearServerAuth(serverName: string, serverUrl: string): Promise { + const key = `${serverName}:${serverUrl}` + const serverHash = getServerAuthHash(serverName, serverUrl) + + this.providers.delete(key) + + // Clear all OAuth-related data for this server + const secrets = getMcpOAuthSecrets() + delete secrets[serverHash] + saveMcpOAuthSecrets(secrets) + } +} diff --git a/src/services/mcp/schemas.ts b/src/services/mcp/schemas.ts index 7fb7ec41..325007ba 100644 --- a/src/services/mcp/schemas.ts +++ b/src/services/mcp/schemas.ts @@ -37,6 +37,7 @@ const createServerTypeSchema = () => { }) .refine((data) => data.type === "stdio", { message: TYPE_ERROR_MESSAGE }), // SSE config (has url field) + // IMPORTANT: The fact that this is listed first before streamableHttp means that when type is not specified, it will default to sse. Since there may be users with older MCP servers configured without a type specified, rearranging this to make streamableHttp first will be a breaking change. BaseConfigSchema.extend({ type: z.literal("sse").optional(), transportType: z.string().optional(), // Support legacy field diff --git a/src/services/mcp/types.ts b/src/services/mcp/types.ts index 9d819fb0..b4f1e6a3 100644 --- a/src/services/mcp/types.ts +++ b/src/services/mcp/types.ts @@ -1,3 +1,4 @@ +import { OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.js" import { Client } from "@modelcontextprotocol/sdk/client/index.js" import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js" import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js" @@ -12,6 +13,7 @@ export type McpConnection = { server: McpServer client: Client transport: Transport + authProvider?: OAuthClientProvider } export type McpTransportType = "stdio" | "sse" | "http" diff --git a/src/services/uri/SharedUriHandler.ts b/src/services/uri/SharedUriHandler.ts index bae6741e..33bb4f45 100644 --- a/src/services/uri/SharedUriHandler.ts +++ b/src/services/uri/SharedUriHandler.ts @@ -90,6 +90,20 @@ export class SharedUriHandler { Logger.warn("SharedUriHandler: Missing prompt parameter for task creation") return false } + // Match /mcp-auth/callback/{hash} + case path.match(/^\/mcp-auth\/callback\/[^/]+$/)?.input: { + const serverHash = path.split("/").pop() + const code = query.get("code") + const state = query.get("state") + + if (!code || !serverHash) { + Logger.warn("SharedUriHandler: Missing code or hash in MCP OAuth callback") + return false + } + + await visibleWebview.controller.handleMcpOAuthCallback(serverHash, code, state) + return true + } default: Logger.warn(`SharedUriHandler: Unknown path: ${path}`) return false diff --git a/src/shared/mcp.ts b/src/shared/mcp.ts index 6f562e44..2bca2670 100644 --- a/src/shared/mcp.ts +++ b/src/shared/mcp.ts @@ -19,8 +19,12 @@ export type McpServer = { disabled?: boolean timeout?: number uid?: string + oauthRequired?: boolean + oauthAuthStatus?: McpOAuthAuthStatus } +export type McpOAuthAuthStatus = "authenticated" | "unauthenticated" | "pending" + export type McpTool = { name: string description?: string diff --git a/src/shared/proto-conversions/mcp/mcp-server-conversion.ts b/src/shared/proto-conversions/mcp/mcp-server-conversion.ts index 48c3df85..71e6f88c 100644 --- a/src/shared/proto-conversions/mcp/mcp-server-conversion.ts +++ b/src/shared/proto-conversions/mcp/mcp-server-conversion.ts @@ -5,7 +5,7 @@ import { McpServer as ProtoMcpServer, McpTool as ProtoMcpTool, } from "@shared/proto/cline/mcp" -import { McpResource, McpResourceTemplate, McpServer, McpTool } from "../../mcp" +import { McpOAuthAuthStatus, McpResource, McpResourceTemplate, McpServer, McpTool } from "../../mcp" // Helper to convert TS status to Proto enum function convertMcpStatusToProto(status: McpServer["status"]): McpServerStatus { @@ -33,6 +33,8 @@ export function convertMcpServersToProtoMcpServers(mcpServers: McpServer[]): Pro disabled: server.disabled, timeout: server.timeout, + oauthRequired: server.oauthRequired, + oauthAuthStatus: server.oauthAuthStatus, })) return protoServers } @@ -107,6 +109,8 @@ export function convertProtoMcpServersToMcpServers(protoServers: ProtoMcpServer[ disabled: protoServer.disabled, timeout: protoServer.timeout, + oauthRequired: protoServer.oauthRequired, + oauthAuthStatus: protoServer.oauthAuthStatus === "" ? undefined : (protoServer.oauthAuthStatus as McpOAuthAuthStatus), } }) return mcpServers diff --git a/src/shared/storage/state-keys.ts b/src/shared/storage/state-keys.ts index 008e9f04..0fd2d6eb 100644 --- a/src/shared/storage/state-keys.ts +++ b/src/shared/storage/state-keys.ts @@ -256,6 +256,7 @@ export interface Secrets { minimaxApiKey: string | undefined hicapApiKey: string | undefined aihubmixApiKey: string | undefined + mcpOAuthSecrets: string | undefined nousResearchApiKey: string | undefined } diff --git a/src/utils/mcpAuth.ts b/src/utils/mcpAuth.ts new file mode 100644 index 00000000..842043ca --- /dev/null +++ b/src/utils/mcpAuth.ts @@ -0,0 +1,23 @@ +import crypto from "crypto" + +/** + * Generates a unique hash for an MCP server based on its name and URL. + * Used for creating unique OAuth callback paths and storage keys. + * @param serverName The name of the MCP server. + * @param serverUrl The URL of the MCP server. + * @returns A SHA-256 hash string. + */ +export const getServerAuthHash = (serverName: string, serverUrl: string): string => { + return crypto.createHash("sha256").update(`${serverName}:${serverUrl}`).digest("hex") +} + +/** + * Generates the unique OAuth callback path for a specific MCP server. + * @param serverName The name of the MCP server. + * @param serverUrl The URL of the MCP server. + * @returns The callback path string (e.g., /mcp-auth/callback/). + */ +export const getMcpServerCallbackPath = (serverName: string, serverUrl: string): string => { + const hash = getServerAuthHash(serverName, serverUrl) + return `/mcp-auth/callback/${hash}` +} diff --git a/webview-ui/src/components/mcp/chat-display/McpResponseDisplay.tsx b/webview-ui/src/components/mcp/chat-display/McpResponseDisplay.tsx index 7e422147..ee328cec 100644 --- a/webview-ui/src/components/mcp/chat-display/McpResponseDisplay.tsx +++ b/webview-ui/src/components/mcp/chat-display/McpResponseDisplay.tsx @@ -20,12 +20,14 @@ const ResponseHeader = styled.div` display: flex; justify-content: space-between; align-items: center; - padding: 9px 10px; + padding: 5px 5px 5px 8px; color: var(--vscode-descriptionForeground); cursor: pointer; user-select: none; border-bottom: 1px dashed var(--vscode-editorGroup-border); margin-bottom: 8px; + font-family: var(--vscode-font-family); + font-size: var(--vscode-font-size); .header-title { display: flex; diff --git a/webview-ui/src/components/mcp/configuration/tabs/add-server/AddRemoteServerForm.tsx b/webview-ui/src/components/mcp/configuration/tabs/add-server/AddRemoteServerForm.tsx index 2436f351..261ba033 100644 --- a/webview-ui/src/components/mcp/configuration/tabs/add-server/AddRemoteServerForm.tsx +++ b/webview-ui/src/components/mcp/configuration/tabs/add-server/AddRemoteServerForm.tsx @@ -1,18 +1,20 @@ import { EmptyRequest } from "@shared/proto/cline/common" import { AddRemoteMcpServerRequest, McpServers } from "@shared/proto/cline/mcp" import { convertProtoMcpServersToMcpServers } from "@shared/proto-conversions/mcp/mcp-server-conversion" -import { VSCodeButton, VSCodeLink, VSCodeTextField } from "@vscode/webview-ui-toolkit/react" +import { VSCodeButton, VSCodeLink, VSCodeRadio, VSCodeRadioGroup, VSCodeTextField } from "@vscode/webview-ui-toolkit/react" import { useState } from "react" import { LINKS } from "@/constants" import { useExtensionState } from "@/context/ExtensionStateContext" import { McpServiceClient } from "@/services/grpc-client" +type TransportType = "streamableHttp" | "sse" + const AddRemoteServerForm = ({ onServerAdded }: { onServerAdded: () => void }) => { const [serverName, setServerName] = useState("") const [serverUrl, setServerUrl] = useState("") + const [transportType, setTransportType] = useState("streamableHttp") const [isSubmitting, setIsSubmitting] = useState(false) const [error, setError] = useState("") - const [showConnectingMessage, setShowConnectingMessage] = useState(false) const { setMcpServers } = useExtensionState() const handleSubmit = async (e: React.FormEvent) => { @@ -37,13 +39,13 @@ const AddRemoteServerForm = ({ onServerAdded }: { onServerAdded: () => void }) = setError("") setIsSubmitting(true) - setShowConnectingMessage(true) try { const servers: McpServers = await McpServiceClient.addRemoteMcpServer( AddRemoteMcpServerRequest.create({ serverName: serverName.trim(), serverUrl: serverUrl.trim(), + transportType: transportType, }), ) @@ -55,11 +57,9 @@ const AddRemoteServerForm = ({ onServerAdded }: { onServerAdded: () => void }) = setServerName("") setServerUrl("") onServerAdded() - setShowConnectingMessage(false) } catch (error) { setIsSubmitting(false) setError(error instanceof Error ? error.message : "Failed to add server") - setShowConnectingMessage(false) } } @@ -101,19 +101,29 @@ const AddRemoteServerForm = ({ onServerAdded }: { onServerAdded: () => void }) = +
+ + { + const value = (e.target as HTMLInputElement).value as TransportType + setTransportType(value) + }} + value={transportType}> + + Streamable HTTP + + + SSE (Legacy) + + +
+ {error &&
{error}
} -
- - {isSubmitting ? "Adding..." : "Add Server"} - - - {showConnectingMessage && ( -
- Connecting to server... This may take a few seconds. -
- )} -
+ + {isSubmitting ? "Connecting..." : "Add Server"} + {
e.stopPropagation()} - style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}> -
- - {tool.name} + style={{ display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: "4px" }}> +
+ + {tool.name}
{serverName && autoApprovalSettings.actions.useMcp && ( - + Auto-approve )} diff --git a/webview-ui/src/components/mcp/configuration/tabs/installed/server-row/ServerRow.tsx b/webview-ui/src/components/mcp/configuration/tabs/installed/server-row/ServerRow.tsx index 4523372e..8f0574e3 100644 --- a/webview-ui/src/components/mcp/configuration/tabs/installed/server-row/ServerRow.tsx +++ b/webview-ui/src/components/mcp/configuration/tabs/installed/server-row/ServerRow.tsx @@ -299,16 +299,31 @@ const ServerRow = ({ }}> {server.error}
- - {server.status === "connecting" || isRestarting ? "Retrying..." : "Retry Connection"} - + {server.oauthRequired && server.oauthAuthStatus === "unauthenticated" ? ( + { + e.stopPropagation() + McpServiceClient.authenticateMcpServer(StringRequest.create({ value: server.name })) + }} + style={{ + width: "calc(100% - 20px)", + margin: "0 10px 10px 10px", + }}> + Authenticate + + ) : ( + + {server.status === "connecting" || isRestarting ? "Retrying..." : "Retry Connection"} + + )} - {server.tools.map((tool) => ( - - ))} {server.name && autoApprovalSettings.actions.useMcp && ( tool.autoApprove)} data-tool="all-tools" onChange={handleAutoApproveChange} - style={{ marginTop: "4px", marginBottom: "4px" }}> + style={{ marginBottom: "4px", fontSize: "11px" }}> Auto-approve all tools )} + {server.tools.map((tool) => ( + + ))}
) : (