From 7b5ae7a50fc45d49fde88f9c71ee0299557ccd5a Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 24 Sep 2025 15:30:08 -0700 Subject: [PATCH] fix: MCP types and sse/http fallback logic --- core/config/load.ts | 34 ++- core/config/yaml/loadYaml.ts | 11 +- core/config/yaml/yamlToContinueConfig.ts | 9 +- core/context/mcp/MCPConnection.ts | 247 +++++++++++------- core/context/mcp/MCPManagerSingleton.ts | 8 +- core/context/mcp/json/loadJsonMcpConfigs.ts | 163 ++++++++---- core/core.ts | 25 +- core/index.d.ts | 3 +- core/protocol/core.ts | 20 +- extensions/cli/src/services/MCPService.ts | 165 +++++++----- .../constants/MessageTypes.kt | 2 + .../pages/config/sections/ToolsSection.tsx | 20 +- packages/config-yaml/src/browser.ts | 1 + 13 files changed, 446 insertions(+), 262 deletions(-) diff --git a/core/config/load.ts b/core/config/load.ts index 02bbc50c0..999f87342 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -26,6 +26,7 @@ import { IdeType, ILLM, ILLMLogger, + InternalMcpOptions, LLMOptions, ModelDescription, RerankerDescription, @@ -58,6 +59,7 @@ import { } from "../util/paths"; import { localPathToUri } from "../util/pathToUri"; +import { loadJsonMcpConfigs } from "../context/mcp/json/loadJsonMcpConfigs"; import CustomContextProviderClass from "../context/providers/CustomContextProvider"; import { PolicySingleton } from "../control-plane/PolicySingleton"; import { getBaseToolDefinitions } from "../tools"; @@ -551,22 +553,26 @@ async function intermediateToFinalConfig({ if (orgPolicy?.policy?.allowMcpServers === false) { await mcpManager.shutdown(); } else { - mcpManager.setConnections( - (config.experimental?.modelContextProtocolServers ?? []).map( - (server, index) => ({ - id: `continue-mcp-server-${index + 1}`, - name: `MCP Server`, - requestOptions: mergeConfigYamlRequestOptions( - server.transport.type !== "stdio" - ? server.transport.requestOptions - : undefined, - config.requestOptions, - ), - ...server.transport, - }), + const mcpOptions: InternalMcpOptions[] = ( + config.experimental?.modelContextProtocolServers ?? [] + ).map((server, index) => ({ + id: `continue-mcp-server-${index + 1}`, + name: `MCP Server`, + requestOptions: mergeConfigYamlRequestOptions( + server.transport.type !== "stdio" + ? server.transport.requestOptions + : undefined, + config.requestOptions, ), - false, + ...server.transport, + })); + const { errors: jsonMcpErrors, mcpServers } = await loadJsonMcpConfigs( + ide, + true, ); + errors.push(...jsonMcpErrors); + mcpOptions.push(...mcpServers); + mcpManager.setConnections(mcpOptions, false); } // Handle experimental modelRole config values for apply and edit diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 983391e46..d1b27a5e9 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -32,6 +32,7 @@ import { modifyAnyConfigWithSharedConfig } from "../sharedConfig"; import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand"; import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand"; +import { loadJsonMcpConfigs } from "../../context/mcp/json/loadJsonMcpConfigs"; import { getControlPlaneEnvSync } from "../../control-plane/env"; import { PolicySingleton } from "../../control-plane/PolicySingleton"; import { getBaseToolDefinitions } from "../../tools"; @@ -393,11 +394,17 @@ export async function configYamlToContinueConfig(options: { if (orgPolicy?.policy?.allowMcpServers === false) { await mcpManager.shutdown(); } else { - const internalConfigs: InternalMcpOptions[] = (config.mcpServers ?? []).map( + const mcpOptions: InternalMcpOptions[] = (config.mcpServers ?? []).map( (server) => convertYamlMcpConfigToInternalMcpOptions(server, config.requestOptions), ); - mcpManager.setConnections(internalConfigs, false, { ide }); + const { errors: jsonMcpErrors, mcpServers } = await loadJsonMcpConfigs( + ide, + true, + ); + localErrors.push(...jsonMcpErrors); + mcpOptions.push(...mcpServers); + mcpManager.setConnections(mcpOptions, false, { ide }); } return { config: continueConfig, errors: localErrors }; diff --git a/core/config/yaml/yamlToContinueConfig.ts b/core/config/yaml/yamlToContinueConfig.ts index d1823ebd5..ad435aea8 100644 --- a/core/config/yaml/yamlToContinueConfig.ts +++ b/core/config/yaml/yamlToContinueConfig.ts @@ -36,12 +36,13 @@ export function convertYamlMcpConfigToInternalMcpOptions( config: MCPServer, globalRequestOptions?: RequestOptions, ): InternalMcpOptions { - const { connectionTimeout, faviconUrl, name } = config; - const base = { + const { connectionTimeout, faviconUrl, name, sourceFile } = config; + const shared = { id: name, name, faviconUrl: faviconUrl, timeout: connectionTimeout, + sourceFile, }; // Stdio if ("command" in config) { @@ -52,7 +53,7 @@ export function convertYamlMcpConfigToInternalMcpOptions( args, cwd, env, - ...base, + ...shared, }; return stdioOptions; } @@ -67,7 +68,7 @@ export function convertYamlMcpConfigToInternalMcpOptions( requestOptions, globalRequestOptions, ), - ...base, + ...shared, }; return httpSseConfig; } diff --git a/core/context/mcp/MCPConnection.ts b/core/context/mcp/MCPConnection.ts index e286f753d..33893c2a7 100644 --- a/core/context/mcp/MCPConnection.ts +++ b/core/context/mcp/MCPConnection.ts @@ -11,6 +11,10 @@ import { Agent as HttpsAgent } from "https"; import { IDE, InternalMcpOptions, + InternalSseMcpOptions, + InternalStdioMcpOptions, + InternalStreamableHttpMcpOptions, + InternalWebsocketMcpOptions, MCPConnectionStatus, MCPPrompt, MCPResource, @@ -177,22 +181,63 @@ class MCPConnection { }); }), (async () => { - this.transport = await this.constructTransportAsync(this.options); - - try { - await this.client.connect(this.transport); - } catch (error) { - // Allow the case where for whatever reason is already connected - if ( - error instanceof Error && - error.message.startsWith( - "StdioClientTransport already started", - ) - ) { - await this.client.close(); - await this.client.connect(this.transport); + if ("command" in this.options) { + // STDIO: no need to check type, just if command is present + const transport = await this.constructStdioTransport( + this.options, + ); + try { + await this.client.connect(transport, {}); + } catch (error) { + // Allow the case where for whatever reason is already connected + if ( + error instanceof Error && + error.message.startsWith( + "StdioClientTransport already started", + ) + ) { + await this.client.close(); + await this.client.connect(transport); + this.transport = transport; + } else { + throw error; + } + } + } else { + // SSE/HTTP: if type isn't explicit: try http and fall back to sse + if (this.options.type === "sse") { + const transport = this.constructSseTransport(this.options); + await this.client.connect(transport, {}); + } else if (this.options.type === "streamable-http") { + const transport = this.constructHttpTransport(this.options); + await this.client.connect(transport, {}); + } else if (this.options.type === "websocket") { + const transport = this.constructWebsocketTransport( + this.options, + ); + await this.client.connect(transport, {}); } else { - throw error; + try { + const transport = this.constructHttpTransport({ + ...this.options, + type: "streamable-http", + }); + await this.client.connect(transport, {}); + this.transport = transport; + } catch (e) { + try { + const transport = this.constructSseTransport({ + ...this.options, + type: "sse", + }); + await this.client.connect(transport, {}); + this.transport = transport; + } catch (e) { + throw new Error( + `MCP config with no URL and type specified failed both sse and http connection: ${e instanceof Error ? e.message : String(e)}`, + ); + } + } } } @@ -201,7 +246,6 @@ class MCPConnection { // this.client.setNotificationHandler(, notification => { // console.log(notification) // }) - const capabilities = this.client.getServerCapabilities(); // Resources <—> Context Provider @@ -355,94 +399,99 @@ class MCPConnection { }; } - private async constructTransportAsync( - options: InternalMcpOptions, - ): Promise { - switch (options.type) { - case "stdio": - const env: Record = options.env - ? { ...options.env } - : {}; + private constructWebsocketTransport( + options: InternalWebsocketMcpOptions, + ): WebSocketClientTransport { + return new WebSocketClientTransport(new URL(options.url)); + } - if (process.env.PATH !== undefined) { - // Set the initial PATH from process.env - env.PATH = process.env.PATH; + private constructSseTransport( + options: InternalSseMcpOptions, + ): SSEClientTransport { + const sseAgent = + options.requestOptions?.verifySsl === false + ? new HttpsAgent({ rejectUnauthorized: false }) + : undefined; - // For non-Windows platforms, try to get the PATH from user shell - if (process.platform !== "win32") { - try { - const shellEnvPath = await getEnvPathFromUserShell(); - if (shellEnvPath && shellEnvPath !== process.env.PATH) { - env.PATH = shellEnvPath; - } - } catch (err) { - console.error("Error getting PATH:", err); - } - } - } - - // Resolve the command and args for the current platform - const { command, args } = this.resolveCommandForPlatform( - options.command, - options.args || [], - ); - - const transport = new StdioClientTransport({ - command, - args, - env, - cwd: options.cwd, - stderr: "pipe", - }); - - // Capture stdio output for better error reporting - - transport.stderr?.on("data", (data: Buffer) => { - this.stdioOutput.stderr += data.toString(); - }); - - return transport; - case "websocket": - return new WebSocketClientTransport(new URL(options.url)); - case "sse": - const sseAgent = - options.requestOptions?.verifySsl === false - ? new HttpsAgent({ rejectUnauthorized: false }) - : undefined; - - return new SSEClientTransport(new URL(options.url), { - eventSourceInit: { - fetch: (input, init) => - fetch(input, { - ...init, - headers: { - ...init?.headers, - ...options.requestOptions?.headers, - }, - ...(sseAgent && { agent: sseAgent }), - }), - }, - requestInit: { - headers: options.requestOptions?.headers, + return new SSEClientTransport(new URL(options.url), { + eventSourceInit: { + fetch: (input, init) => + fetch(input, { + ...init, + headers: { + ...init?.headers, + ...options.requestOptions?.headers, + }, ...(sseAgent && { agent: sseAgent }), - }, - }); - case "streamable-http": - const { url, requestOptions } = options; - const streamableAgent = - requestOptions?.verifySsl === false - ? new HttpsAgent({ rejectUnauthorized: false }) - : undefined; + }), + }, + requestInit: { + headers: options.requestOptions?.headers, + ...(sseAgent && { agent: sseAgent }), + }, + }); + } - return new StreamableHTTPClientTransport(new URL(url), { - requestInit: { - headers: requestOptions?.headers, - ...(streamableAgent && { agent: streamableAgent }), - }, - }); - default: - throw new Error(`Unsupported transport type: ${options.type}`); + private constructHttpTransport( + options: InternalStreamableHttpMcpOptions, + ): StreamableHTTPClientTransport { + const { url, requestOptions } = options; + const streamableAgent = + requestOptions?.verifySsl === false + ? new HttpsAgent({ rejectUnauthorized: false }) + : undefined; + + return new StreamableHTTPClientTransport(new URL(url), { + requestInit: { + headers: requestOptions?.headers, + ...(streamableAgent && { agent: streamableAgent }), + }, + }); + } + + private async constructStdioTransport( + options: InternalStdioMcpOptions, + ): Promise { + const env: Record = options.env ? { ...options.env } : {}; + + if (process.env.PATH !== undefined) { + // Set the initial PATH from process.env + env.PATH = process.env.PATH; + + // For non-Windows platforms, try to get the PATH from user shell + if (process.platform !== "win32") { + try { + const shellEnvPath = await getEnvPathFromUserShell(); + if (shellEnvPath && shellEnvPath !== process.env.PATH) { + env.PATH = shellEnvPath; + } + } catch (err) { + console.error("Error getting PATH:", err); + } + } } + + // Resolve the command and args for the current platform + const { command, args } = this.resolveCommandForPlatform( + options.command, + options.args || [], + ); + + const transport = new StdioClientTransport({ + command, + args, + env, + cwd: options.cwd, + stderr: "pipe", + }); + + // Capture stdio output for better error reporting + + transport.stderr?.on("data", (data: Buffer) => { + this.stdioOutput.stderr += data.toString(); + }); + + return transport; } } diff --git a/core/context/mcp/MCPManagerSingleton.ts b/core/context/mcp/MCPManagerSingleton.ts index 92dba9fbd..1f28eea8e 100644 --- a/core/context/mcp/MCPManagerSingleton.ts +++ b/core/context/mcp/MCPManagerSingleton.ts @@ -108,13 +108,13 @@ export class MCPManagerSingleton { if (a.type !== b.type) { return false; } - if (a.type === "stdio" && b.type === "stdio") { + if ("command" in a && "command" in b) { return ( a.command === b.command && JSON.stringify(a.args) === JSON.stringify(b.args) && this.compareEnv(a.env, b.env) ); - } else if (a.type !== "stdio" && b.type !== "stdio") { + } else if ("url" in a && "url" in b) { return a.url === b.url; } return false; @@ -174,8 +174,8 @@ export class MCPManagerSingleton { })); } - setStatus(server: MCPServerStatus, status: MCPServerStatus["status"]) { - this.connections.get(server.id)!.status = status; + setStatus(serverId: string, status: MCPServerStatus["status"]) { + this.connections.get(serverId)!.status = status; } async getPrompt( diff --git a/core/context/mcp/json/loadJsonMcpConfigs.ts b/core/context/mcp/json/loadJsonMcpConfigs.ts index 4e90396d3..c259b3fb9 100644 --- a/core/context/mcp/json/loadJsonMcpConfigs.ts +++ b/core/context/mcp/json/loadJsonMcpConfigs.ts @@ -1,5 +1,14 @@ +import { + ConfigValidationError, + convertJsonMcpConfigToYamlMcpConfig, + McpJsonConfig, + mcpServerConfigFileSchema, + mcpServersJsonSchema, +} from "@continuedev/config-yaml"; +import * as JSONC from "comment-json"; import ignore from "ignore"; -import { IDE } from "../../.."; +import { IDE, InternalMcpOptions } from "../../.."; +import { convertYamlMcpConfigToInternalMcpOptions } from "../../../config/yaml/yamlToContinueConfig"; import { DEFAULT_IGNORE_DIRS, DEFAULT_IGNORE_FILETYPES, @@ -7,56 +16,31 @@ import { import { walkDir } from "../../../indexing/walkDir"; import { getGlobalFolderWithName } from "../../../util/paths"; import { localPathToUri } from "../../../util/pathToUri"; -import { joinPathsToUri } from "../../../util/uri"; - -async function getDefinitionFilesInDir( - ide: IDE, - dir: string, -): Promise<{ path: string; content: string }[]> { - try { - let assistantFilePaths: string[]; - if (fileExtType === "yaml") { - assistantFilePaths = uris.filter( - (p) => p.endsWith(".yaml") || p.endsWith(".yml"), - ); - } else if (fileExtType === "markdown") { - assistantFilePaths = uris.filter((p) => p.endsWith(".md")); - } else { - assistantFilePaths = uris.filter( - (p) => p.endsWith(".yaml") || p.endsWith(".yml") || p.endsWith(".md"), - ); - } - - const results = assistantFilePaths.map(async (uri) => { - const content = await ide.readFile(uri); // make a try catch - return { path: uri, content }; - }); - return Promise.all(results); - } catch (e) { - console.error(e); - return []; - } -} +import { getUriPathBasename, joinPathsToUri } from "../../../util/uri"; /** * This method searches in both ~/.continue and workspace .continue * for all YAML/Markdown files in the specified subdirectory, for example .continue/assistants or .continue/prompts */ -export async function getJsonConfigs( +export async function loadJsonMcpConfigs( ide: IDE, includeGlobal: boolean, -): Promise<{ path: string; content: string }[]> { - const dirsToCheck = await ide.getWorkspaceDirs(); - if (includeGlobal) { - dirsToCheck.push(localPathToUri(getGlobalFolderWithName("mcpServers"))); - } +): Promise<{ + mcpServers: InternalMcpOptions[]; + errors: ConfigValidationError[]; +}> { + const errors: ConfigValidationError[] = []; - const fullDirs = dirsToCheck.map((dir) => + // Get dirs + const workspaceDirs = await ide.getWorkspaceDirs(); + const mcpDirs = workspaceDirs.map((dir) => joinPathsToUri(dir, ".continue", "mcpServers"), ); + if (includeGlobal) { + mcpDirs.push(localPathToUri(getGlobalFolderWithName("mcpServers"))); + } - const exists = await ide.fileExists(dir); - + // Get json files and their contents const overrideDefaultIgnores = ignore() .add( DEFAULT_IGNORE_FILETYPES.filter( @@ -65,19 +49,92 @@ export async function getJsonConfigs( ) .add(DEFAULT_IGNORE_DIRS); - const uris = await walkDir(dir, ide, { - overrideDefaultIgnores, - source: "get mcp json files", - }); + const jsonFiles: { uri: string; content: string }[] = []; - // Get all definition files from the directories - const definitionFiles = ( - await Promise.all( - fullDirs.map((dir) => - getDefinitionFilesInDir(ide, dir, options.fileExtType), - ), - ) - ).flat(); + await Promise.all( + mcpDirs.map(async (dir) => { + const exists = await ide.fileExists(dir); + if (!exists) { + return; + } + try { + const uris = await walkDir(dir, ide, { + overrideDefaultIgnores, + source: "get mcp json files", + }); + const jsonUris = uris.filter((uri) => uri.endsWith(".json")); + await Promise.all( + jsonUris.map(async (uri) => { + try { + const content = await ide.readFile(uri); + jsonFiles.push({ uri, content }); + } catch (e) { + errors.push({ + fatal: false, + message: `Failed to read MCP server JSON file at ${uri}: ${e instanceof Error ? e.message : String(e)}`, + }); + } + }), + ); + } catch (e) { + errors.push({ + fatal: false, + message: `Failed to check for MCP JSON files in ${dir}: ${e instanceof Error ? e.message : String(e)}`, + }); + } + }), + ); - return definitionFiles; + const validJsonConfigs: { name: string; mcpJson: McpJsonConfig }[] = []; + for (const file of jsonFiles) { + try { + const json = JSONC.parse(file.content); + const claudeFileParsed = mcpServerConfigFileSchema.safeParse(json); + + // Try parsing as a file with mcpServers and multiple servers (claude-esque format) + if (claudeFileParsed.success) { + validJsonConfigs.push( + ...Object.entries(claudeFileParsed.data.mcpServers).map( + ([name, mcpJson]) => ({ + name, + mcpJson, + }), + ), + ); + claudeFileParsed.data; + } else { + // Try parsing as single JSON file + const singleConfigParsed = mcpServersJsonSchema.safeParse(json); + if (singleConfigParsed.success) { + validJsonConfigs.push({ + mcpJson: singleConfigParsed.data, + name: getUriPathBasename(file.uri).replace(".json", ""), + }); + } else { + errors.push({ + fatal: false, + message: `MCP JSON file at ${file.uri} doesn't match a supported MCP JSON configuration format`, + }); + } + } + } catch (e) { + errors.push({ + fatal: false, + message: `Error parsing MCP JSON file at ${file.uri}: ${e instanceof Error ? e.message : String(e)}`, + }); + } + } + + // Two levels of conversion for now. + const yamlConfigs = validJsonConfigs.map((c) => + convertJsonMcpConfigToYamlMcpConfig(c.name, c.mcpJson), + ); + const mcpServers = yamlConfigs.map((c) => + convertYamlMcpConfigToInternalMcpOptions(c.yamlConfig), + ); + // Parse and convert files + return { + mcpServers, + errors, + }; } diff --git a/core/core.ts b/core/core.ts index 8fd24c15a..31f4f20b9 100644 --- a/core/core.ts +++ b/core/core.ts @@ -508,15 +508,26 @@ 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); + MCPManagerSingleton.getInstance().setStatus( + msg.data.serverId, + "authenticating", + ); + const status = await performAuth( + msg.data.serverId, + msg.data.serverUrl, + this.ide, + ); if (status === "AUTHORIZED") { - await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); + await MCPManagerSingleton.getInstance().refreshConnection( + msg.data.serverId, + ); } }); on("mcp/removeAuthentication", async (msg) => { - removeMCPAuth(msg.data, this.ide); - await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); + removeMCPAuth(msg.data.serverUrl, this.ide); + await MCPManagerSingleton.getInstance().refreshConnection( + msg.data.serverId, + ); }); // Context providers @@ -1244,7 +1255,9 @@ export class Core { uri.endsWith("CLAUDE.md") || uri.endsWith(SYSTEM_PROMPT_DOT_FILE) || (uri.includes(".continue") && - (uri.endsWith(".yaml") || uri.endsWith("yml"))) || + (uri.endsWith(".yaml") || + uri.endsWith(".yml") || + uri.endsWith(".json"))) || BLOCK_TYPES.some((blockType) => uri.includes(`.continue/${blockType}`), ) diff --git a/core/index.d.ts b/core/index.d.ts index 164019014..8650c6ae2 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1325,6 +1325,7 @@ type BaseInternalMCPOptions = { faviconUrl?: string; timeout?: number; requestOptions?: RequestOptions; + sourceFile?: string; }; export type InternalStdioMcpOptions = BaseInternalMCPOptions & { @@ -1346,7 +1347,7 @@ export type InternalSseMcpOptions = BaseInternalMCPOptions & { }; export type InternalWebsocketMcpOptions = BaseInternalMCPOptions & { - type: "websocket"; + type: "websocket"; // websocket requires explicit type url: string; }; diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 82ef174a7..bf383a2d5 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -14,6 +14,7 @@ import { SharedConfigSchema } from "../config/sharedConfig"; import { GlobalContextModelSelections } from "../util/GlobalContext"; import { + BaseSessionMetadata, BrowserSerializedContinueConfig, ChatMessage, CompiledMessagesResult, @@ -27,7 +28,6 @@ import { FileSymbolMap, IdeSettings, LLMFullCompletionOptions, - MCPServerStatus, MessageOption, ModelDescription, PromptLog, @@ -35,7 +35,6 @@ import { RangeInFileWithNextEditInfo, SerializedContinueConfig, Session, - BaseSessionMetadata, SiteIndexingConfig, SlashCommandDescWithSource, StreamDiffLinesPayload, @@ -159,9 +158,20 @@ export type ToCoreFromIdeOrWebviewProtocol = { description: string | undefined; }, ]; - "mcp/startAuthentication": [MCPServerStatus, void]; - "mcp/removeAuthentication": [MCPServerStatus, void]; - + "mcp/startAuthentication": [ + { + serverId: string; + serverUrl: string; + }, + void, + ]; + "mcp/removeAuthentication": [ + { + serverId: string; + serverUrl: string; + }, + void, + ]; "context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap]; "context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]]; "autocomplete/complete": [AutocompleteInput, string[]]; diff --git a/extensions/cli/src/services/MCPService.ts b/extensions/cli/src/services/MCPService.ts index 8088894e0..048f1ef03 100644 --- a/extensions/cli/src/services/MCPService.ts +++ b/extensions/cli/src/services/MCPService.ts @@ -3,11 +3,15 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; -import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; import { getErrorString } from "../util/error.js"; import { logger } from "../util/logger.js"; +import { + HttpMcpServer, + SseMcpServer, + StdioMcpServer, +} from "node_modules/@continuedev/config-yaml/dist/schemas/mcp/index.js"; import { BaseService, ServiceWithDependencies } from "./BaseService.js"; import { serviceContainer } from "./ServiceContainer.js"; import { @@ -217,19 +221,7 @@ export class MCPService this.updateState(); try { - const client = new Client( - { name: "continue-cli-client", version: "1.0.0" }, - { capabilities: {} }, - ); - - const transport = await this.constructTransport(serverConfig); - - logger.debug("Connecting to MCP server", { - name: serverName, - command: serverConfig.command, - }); - - await client.connect(transport, {}); + const client = await this.getConnectedClient(serverConfig); connection.client = client; connection.status = "connected"; @@ -349,66 +341,101 @@ export class MCPService } /** - * Construct transport based on server configuration + * Construct transport based on server configuration and connect client */ - private async constructTransport( + private async getConnectedClient( serverConfig: MCPServerConfig, - ): Promise { - const transportType = serverConfig.type || "stdio"; + ): Promise { + const client = new Client( + { name: "continue-cli-client", version: "1.0.0" }, + { capabilities: {} }, + ); - switch (transportType) { - case "stdio": - if (!serverConfig.command) { - throw new Error( - "MCP server command is not specified for stdio transport", + if ("command" in serverConfig) { + // STDIO: no need to check type, just if command is present + logger.debug("Connecting to MCP server", { + name: serverConfig.name, + command: serverConfig.command, + }); + const transport = this.constructStdioTransport(serverConfig); + await client.connect(transport, {}); + } else { + // SSE/HTTP: if type isn't explicit: try http and fall back to sse + logger.debug("Connecting to MCP server", { + name: serverConfig.name, + url: serverConfig.url, + }); + + if (serverConfig.type === "sse") { + const transport = this.constructSseTransport(serverConfig); + await client.connect(transport, {}); + } else if (serverConfig.type === "streamable-http") { + const transport = this.constructHttpTransport(serverConfig); + await client.connect(transport, {}); + } else { + try { + const transport = this.constructHttpTransport(serverConfig); + await client.connect(transport, {}); + } catch (e) { + logger.debug( + "MCP Connection: http connection failed, falling back to sse connection", + { + name: serverConfig.name, + }, ); + try { + const transport = this.constructSseTransport(serverConfig); + await client.connect(transport, {}); + } catch (e) { + throw new Error( + `MCP config with no URL and type specified failed both sse and http connection: ${e instanceof Error ? e.message : String(e)}`, + ); + } } - - const env: Record = serverConfig.env || {}; - if (process.env.PATH !== undefined) { - env.PATH = process.env.PATH; - } - - return new StdioClientTransport({ - command: serverConfig.command, - args: serverConfig.args || [], - env, - cwd: serverConfig.cwd, - stderr: "ignore", - }); - - case "sse": - if (!serverConfig.url) { - throw new Error("MCP server URL is not specified for SSE transport"); - } - return new SSEClientTransport(new URL(serverConfig.url), { - eventSourceInit: { - fetch: (input, init) => - fetch(input, { - ...init, - headers: { - ...init?.headers, - ...(serverConfig.requestOptions?.headers as - | Record - | undefined), - }, - }), - }, - requestInit: { headers: serverConfig.requestOptions?.headers }, - }); - - case "streamable-http": - if (!serverConfig.url) { - throw new Error( - "MCP server URL is not specified for streamable-http transport", - ); - } - return new StreamableHTTPClientTransport(new URL(serverConfig.url), { - requestInit: { headers: serverConfig.requestOptions?.headers }, - }); - - default: - throw new Error(`Unsupported transport type: ${transportType}`); + } } + + return client; + } + + private constructSseTransport( + serverConfig: SseMcpServer, + ): SSEClientTransport { + return new SSEClientTransport(new URL(serverConfig.url), { + eventSourceInit: { + fetch: (input, init) => + fetch(input, { + ...init, + headers: { + ...init?.headers, + ...serverConfig.requestOptions?.headers, + }, + }), + }, + requestInit: { headers: serverConfig.requestOptions?.headers }, + }); + } + private constructHttpTransport( + serverConfig: HttpMcpServer, + ): StreamableHTTPClientTransport { + return new StreamableHTTPClientTransport(new URL(serverConfig.url), { + requestInit: { headers: serverConfig.requestOptions?.headers }, + }); + } + private constructStdioTransport( + serverConfig: StdioMcpServer, + ): StdioClientTransport { + const env: Record = serverConfig.env || {}; + if (process.env.PATH !== undefined) { + env.PATH = process.env.PATH; + } + + return new StdioClientTransport({ + command: serverConfig.command, + args: serverConfig.args || [], + env, + cwd: serverConfig.cwd, + stderr: "ignore", + }); } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt index 63484d9eb..f9d82e377 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt @@ -92,6 +92,8 @@ class MessageTypes { "config/updateSharedConfig", "config/updateSelectedModel", "mcp/reloadServer", + "mcp/startAuthentication", + "mcp/removeAuthentication", "mcp/getPrompt", "context/getContextItems", "context/getSymbolsForFiles", diff --git a/gui/src/pages/config/sections/ToolsSection.tsx b/gui/src/pages/config/sections/ToolsSection.tsx index c94c97a9e..34ded2874 100644 --- a/gui/src/pages/config/sections/ToolsSection.tsx +++ b/gui/src/pages/config/sections/ToolsSection.tsx @@ -53,13 +53,23 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) { }; const onAuthenticate = async () => { - updateMCPServerStatus("authenticating"); - await ideMessenger.request("mcp/startAuthentication", server); + if ("url" in server) { + updateMCPServerStatus("authenticating"); + await ideMessenger.request("mcp/startAuthentication", { + serverId: server.id, + serverUrl: server.url, + }); + } }; const onRemoveAuth = async () => { - updateMCPServerStatus("authenticating"); - await ideMessenger.request("mcp/removeAuthentication", server); + if ("url" in server) { + updateMCPServerStatus("authenticating"); + await ideMessenger.request("mcp/removeAuthentication", { + serverId: server.id, + serverUrl: server.url, + }); + } }; const onRefresh = async () => { @@ -162,7 +172,7 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) {
- {server.isProtectedResource && ( + {server.isProtectedResource && "url" in server && (