From cda958f54db6c9616f46a94031cecfd06796d4a8 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 20 Mar 2025 15:17:47 -0700 Subject: [PATCH 01/12] show errors, codeblock for wouldliketo message --- core/context/mcp/index.ts | 2 +- .../components/mainInput/ContextItemsPeek.tsx | 18 +++++- gui/src/components/mainInput/MentionList.tsx | 56 +------------------ gui/src/components/mainInput/icons.ts | 56 +++++++++++++++++++ gui/src/pages/gui/ToolCallDiv/ToolCall.tsx | 12 +++- gui/src/redux/thunks/callTool.ts | 5 +- 6 files changed, 89 insertions(+), 60 deletions(-) create mode 100644 gui/src/components/mainInput/icons.ts diff --git a/core/context/mcp/index.ts b/core/context/mcp/index.ts index ec6d3903a..588b063e9 100644 --- a/core/context/mcp/index.ts +++ b/core/context/mcp/index.ts @@ -195,7 +195,7 @@ class MCPConnection { faviconUrl, readonly: false, type: "function", - wouldLikeTo: `use the ${name} ${tool.name} tool`, + wouldLikeTo: "", uri: encodeMCPToolUri(mcpId, tool.name), })); diff --git a/gui/src/components/mainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/ContextItemsPeek.tsx index 9e7d34070..9cd140d2c 100644 --- a/gui/src/components/mainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/ContextItemsPeek.tsx @@ -14,6 +14,7 @@ import { selectIsGatheringContext } from "../../redux/slices/sessionSlice"; import FileIcon from "../FileIcon"; import SafeImg from "../SafeImg"; import { getIconFromDropdownItem } from "./MentionList"; +import { NAMED_ICONS } from "./icons"; interface ContextItemsPeekProps { contextItems?: ContextItemWithId[]; @@ -59,13 +60,28 @@ function ContextItemsPeekItem({ contextItem }: ContextItemsPeekItemProps) { const dimensions = "18px"; if (contextItem.icon) { + const NamedIcon = contextItem.icon + ? NAMED_ICONS[contextItem.icon] + : undefined; return ( + + + ) : null + } /> ); } diff --git a/gui/src/components/mainInput/MentionList.tsx b/gui/src/components/mainInput/MentionList.tsx index 94324b75e..98e798d12 100644 --- a/gui/src/components/mainInput/MentionList.tsx +++ b/gui/src/components/mainInput/MentionList.tsx @@ -1,25 +1,8 @@ import { ArrowRightIcon, - ArrowUpOnSquareIcon, AtSymbolIcon, - Bars3BottomLeftIcon, BoltIcon, - BookOpenIcon, - BugAntIcon, - CircleStackIcon, - CodeBracketIcon, - CommandLineIcon, - CpuChipIcon, - DocumentTextIcon, - ExclamationTriangleIcon, - FolderIcon, - FolderOpenIcon, - GlobeAltIcon, - MagnifyingGlassIcon, - PaperClipIcon, PlusIcon, - SparklesIcon, - TrashIcon, } from "@heroicons/react/24/outline"; import { Editor } from "@tiptap/react"; import { @@ -46,50 +29,15 @@ import FileIcon from "../FileIcon"; import SafeImg from "../SafeImg"; import AddDocsDialog from "../dialogs/AddDocsDialog"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; -import { DiscordIcon } from "../svg/DiscordIcon"; -import { GithubIcon } from "../svg/GithubIcon"; -import { GitlabIcon } from "../svg/GitlabIcon"; -import { GoogleIcon } from "../svg/GoogleIcon"; +import { NAMED_ICONS } from "./icons"; import { ComboBoxItem, ComboBoxItemType } from "./types"; -const ICONS_FOR_DROPDOWN: { [key: string]: any } = { - file: FolderIcon, - code: CodeBracketIcon, - terminal: CommandLineIcon, - diff: PlusIcon, - search: MagnifyingGlassIcon, - url: GlobeAltIcon, - open: FolderOpenIcon, - codebase: SparklesIcon, - problems: ExclamationTriangleIcon, - folder: FolderIcon, - docs: BookOpenIcon, - web: GlobeAltIcon, - clipboard: PaperClipIcon, - database: CircleStackIcon, - postgres: CircleStackIcon, - debugger: BugAntIcon, - os: CpuChipIcon, - tree: Bars3BottomLeftIcon, - "prompt-files": DocumentTextIcon, - "repo-map": FolderIcon, - "/clear": TrashIcon, - "/share": ArrowUpOnSquareIcon, - "/cmd": CommandLineIcon, - issue: GithubIcon, - discord: DiscordIcon, - google: GoogleIcon, - "gitlab-mr": GitlabIcon, - http: GlobeAltIcon, - trash: TrashIcon, -}; - export function getIconFromDropdownItem( id: string | undefined, type: ComboBoxItemType, ) { const typeIcon = type === "contextProvider" ? AtSymbolIcon : BoltIcon; - return id ? (ICONS_FOR_DROPDOWN[id] ?? typeIcon) : typeIcon; + return id ? (NAMED_ICONS[id] ?? typeIcon) : typeIcon; } function DropdownIcon(props: { className?: string; item: ComboBoxItem }) { diff --git a/gui/src/components/mainInput/icons.ts b/gui/src/components/mainInput/icons.ts new file mode 100644 index 000000000..42b80da66 --- /dev/null +++ b/gui/src/components/mainInput/icons.ts @@ -0,0 +1,56 @@ +import { + ArrowUpOnSquareIcon, + Bars3BottomLeftIcon, + BookOpenIcon, + BugAntIcon, + CircleStackIcon, + CodeBracketIcon, + CommandLineIcon, + CpuChipIcon, + DocumentTextIcon, + ExclamationTriangleIcon, + FolderIcon, + FolderOpenIcon, + GlobeAltIcon, + MagnifyingGlassIcon, + PaperClipIcon, + PlusIcon, + SparklesIcon, + TrashIcon, +} from "@heroicons/react/24/outline"; +import { DiscordIcon } from "../svg/DiscordIcon"; +import { GithubIcon } from "../svg/GithubIcon"; +import { GitlabIcon } from "../svg/GitlabIcon"; +import { GoogleIcon } from "../svg/GoogleIcon"; + +export const NAMED_ICONS: { [key: string]: any } = { + file: FolderIcon, + code: CodeBracketIcon, + terminal: CommandLineIcon, + diff: PlusIcon, + search: MagnifyingGlassIcon, + url: GlobeAltIcon, + open: FolderOpenIcon, + codebase: SparklesIcon, + problems: ExclamationTriangleIcon, + folder: FolderIcon, + docs: BookOpenIcon, + web: GlobeAltIcon, + clipboard: PaperClipIcon, + database: CircleStackIcon, + postgres: CircleStackIcon, + debugger: BugAntIcon, + os: CpuChipIcon, + tree: Bars3BottomLeftIcon, + "prompt-files": DocumentTextIcon, + "repo-map": FolderIcon, + "/clear": TrashIcon, + "/share": ArrowUpOnSquareIcon, + "/cmd": CommandLineIcon, + issue: GithubIcon, + discord: DiscordIcon, + google: GoogleIcon, + "gitlab-mr": GitlabIcon, + http: GlobeAltIcon, + trash: TrashIcon, +}; diff --git a/gui/src/pages/gui/ToolCallDiv/ToolCall.tsx b/gui/src/pages/gui/ToolCallDiv/ToolCall.tsx index 9a79ea17d..6473fe70c 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolCall.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolCall.tsx @@ -29,7 +29,7 @@ export function ToolCallDisplay(props: ToolCallDisplayProps) { tool.wouldLikeTo, props.toolCallState.parsedArgs, ); - return rendered; + return rendered.trim(); }, [props.toolCallState, tool]); const args: [string, any][] = useMemo(() => { @@ -61,7 +61,15 @@ export function ToolCallDisplay(props: ToolCallDisplayProps) { )}
- Continue wants to {wouldLikeToMessage.trim()} + Continue wants to{" "} + {wouldLikeToMessage ? ( + {wouldLikeToMessage} + ) : ( + <> + use the {tool?.displayTitle}{" "} + tool + + )}
{!!args.length ? ( diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts index 75b075288..34ae00390 100644 --- a/gui/src/redux/thunks/callTool.ts +++ b/gui/src/redux/thunks/callTool.ts @@ -57,10 +57,11 @@ export const callTool = createAsyncThunk( toolCallId: toolCallState.toolCallId, toolOutput: [ { - name: "Tool Call Failed", + icon: "problems", + name: "Tool Call Error", description: "Tool Call Failed", content: `The tool call failed with the message:\n\n${result.error}\n\nPlease try something else or request further instructions.`, - hidden: true, + hidden: false, }, ], }), From 7df9c604840dc75ad35aa6289ab7a60660895c92 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 20 Mar 2025 19:02:24 -0700 Subject: [PATCH 02/12] mcp loading fixes and duplicate tools --- core/config/load.ts | 59 +-- core/config/profile/doLoadConfig.ts | 89 ++++- core/config/yaml/loadYaml.ts | 58 +-- core/context/mcp/index.ts | 356 +++++++++++------- core/core.ts | 4 + core/index.d.ts | 96 +++-- .../InputToolbar/ToggleToolsButton.tsx | 30 +- .../InputToolbar/ToolDropdownItem.tsx | 39 +- 8 files changed, 464 insertions(+), 267 deletions(-) diff --git a/core/config/load.ts b/core/config/load.ts index a198f37bf..de14a8f02 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -28,7 +28,6 @@ import { IdeType, ILLM, LLMOptions, - MCPOptions, ModelDescription, RerankerDescription, SerializedContinueConfig, @@ -521,6 +520,8 @@ async function intermediateToFinalConfig( contextProviders, models, tools: allTools, + mcpServerStatuses: [], + slashCommands: config.slashCommands ?? [], modelsByRole: { chat: models, edit: models, @@ -541,53 +542,16 @@ async function intermediateToFinalConfig( }, }; - // Apply MCP if specified + // Trigger MCP server refreshes (Config is reloaded again once connected!) const mcpManager = MCPManagerSingleton.getInstance(); - function getMcpId(options: MCPOptions) { - return JSON.stringify(options); - } - if (config.experimental?.modelContextProtocolServers) { - await mcpManager.removeUnusedConnections( - config.experimental.modelContextProtocolServers.map(getMcpId), - ); - } - - if (config.experimental?.modelContextProtocolServers) { - const abortController = new AbortController(); - const mcpConnectionTimeout = setTimeout( - () => abortController.abort(), - 5000, - ); - - await Promise.allSettled( - config.experimental.modelContextProtocolServers?.map( - async (server, index) => { - try { - const mcpId = getMcpId(server); - const mcpConnection = mcpManager.createConnection(mcpId, server); - await mcpConnection.modifyConfig( - continueConfig, - mcpId, - abortController.signal, - "MCP Server", - server.faviconUrl, - ); - } catch (e) { - let errorMessage = "Failed to load MCP server"; - if (e instanceof Error) { - errorMessage += ": " + e.message; - } - errors.push({ - fatal: false, - message: errorMessage, - }); - } finally { - clearTimeout(mcpConnectionTimeout); - } - }, - ) || [], - ); - } + mcpManager.setConnections( + (config.experimental?.modelContextProtocolServers ?? []).map((server) => ({ + id: JSON.stringify(server), + name: "MCP Server", + ...server, + })), + false, + ); // Handle experimental modelRole config values for apply and edit const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title; @@ -681,6 +645,7 @@ async function finalToBrowserConfig( rules: final.rules, docs: final.docs, tools: final.tools, + mcpServerStatuses: final.mcpServerStatuses, tabAutocompleteOptions: final.tabAutocompleteOptions, usePlatform: await useHub(ide.getIdeSettings()), modelsByRole: Object.fromEntries( diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 224b7b64e..10e4e73e9 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -12,12 +12,17 @@ import { IDE, IdeSettings, SerializedContinueConfig, + Tool, } from "../../"; +import { constructMcpSlashCommand } from "../../commands/slash/mcp"; +import { MCPManagerSingleton } from "../../context/mcp"; +import MCPContextProvider from "../../context/providers/MCPContextProvider"; import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js"; import { ControlPlaneClient } from "../../control-plane/client.js"; import { getControlPlaneEnv } from "../../control-plane/env.js"; import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js"; import ContinueProxy from "../../llm/llms/stubs/ContinueProxy"; +import { encodeMCPToolUri } from "../../tools/callTool"; import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths"; import { localPathOrUriToPath } from "../../util/pathToUri"; import { Telemetry } from "../../util/posthog"; @@ -93,15 +98,89 @@ export default async function doLoadConfig( configLoadInterrupted = result.configLoadInterrupted; } - // Rectify model selections for each role - if (newConfig) { - newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId); - } - if (configLoadInterrupted || !newConfig) { return { errors, config: newConfig, configLoadInterrupted: true }; } + // TODO using config result but result with non-fatal errors is an antipattern? + // Remove ability have undefined errors, just have an array + errors = [...(errors ?? [])]; + + // Rectify model selections for each role + newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId); + + // Add things from MCP servers + const mcpManager = MCPManagerSingleton.getInstance(); + const mcpServerStatuses = mcpManager.getStatuses(); + + // Slightly hacky just need connection's client to make slash command for now + const serializableStatuses = mcpServerStatuses.map((server) => { + const { client, ...rest } = server; + return rest; + }); + newConfig.mcpServerStatuses = serializableStatuses; + + for (const server of mcpServerStatuses) { + if (server.status === "connected") { + const serverTools: Tool[] = server.tools.map((tool) => ({ + displayTitle: server.name + " " + tool.name, + function: { + description: tool.description, + name: tool.name, + parameters: tool.inputSchema, + }, + faviconUrl: server.faviconUrl, + readonly: false, + type: "function" as const, + wouldLikeTo: "", + uri: encodeMCPToolUri(server.id, tool.name), + })); + newConfig.tools.push(...serverTools); + + const serverSlashCommands = server.prompts.map((prompt) => + constructMcpSlashCommand( + server.client, + prompt.name, + prompt.description, + prompt.arguments?.map((a: any) => a.name), + ), + ); + newConfig.slashCommands.push(...serverSlashCommands); + + const submenuItems = server.resources.map((resource) => ({ + title: resource.name, + description: resource.description, + id: resource.uri, + icon: server.faviconUrl, + })); + if (submenuItems.length > 0) { + const serverContextProvider = new MCPContextProvider({ + submenuItems, + mcpId: server.id, + }); + newConfig.contextProviders.push(serverContextProvider); + } + } + } + + // Detect duplicate tool names + const counts: Record = {}; + newConfig.tools.forEach((tool) => { + if (counts[tool.function.name]) { + counts[tool.function.name] = counts[tool.function.name] + 1; + } else { + counts[tool.function.name] = 1; + } + }); + Object.entries(counts).forEach(([toolName, count]) => { + if (count > 1) { + errors.push({ + fatal: false, + message: `Duplicate tool name ${toolName} detected (${count} tools). Permissions will conflict and usage may be unpredictable`, + }); + } + }); + newConfig.allowAnonymousTelemetry = newConfig.allowAnonymousTelemetry && (await ide.isTelemetryEnabled()); diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index d946b4754..4aba17ae4 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -112,6 +112,7 @@ async function configYamlToContinueConfig( slashCommands: [], models: [], tools: allTools, + mcpServerStatuses: [], systemMessage: config.rules?.join("\n"), experimental: { modelContextProtocolServers: config.mcpServers?.map((mcpServer) => ({ @@ -368,52 +369,19 @@ async function configYamlToContinueConfig( continueConfig.contextProviders.push(new DocsContextProvider({})); } - // Apply MCP if specified + // Trigger MCP server refreshes (Config is reloaded again once connected!) const mcpManager = MCPManagerSingleton.getInstance(); - if (config.mcpServers) { - await mcpManager.removeUnusedConnections( - config.mcpServers.map((s) => s.name), - ); - } - - await Promise.allSettled( - config.mcpServers?.map(async (server) => { - const abortController = new AbortController(); - const mcpConnectionTimeout = setTimeout( - () => abortController.abort(), - 5000, - ); - - try { - const mcpId = server.name; - const mcpConnection = mcpManager.createConnection(mcpId, { - transport: { - type: "stdio", - args: [], - ...server, - }, - }); - - await mcpConnection.modifyConfig( - continueConfig, - mcpId, - abortController.signal, - server.name, - server.faviconUrl, - ); - } catch (e) { - let errorMessage = `Failed to load MCP server ${server.name}`; - if (e instanceof Error) { - errorMessage += ": " + e.message; - } - localErrors.push({ - fatal: false, - message: errorMessage, - }); - } finally { - clearTimeout(mcpConnectionTimeout); - } - }) ?? [], + mcpManager.setConnections( + (config.mcpServers ?? []).map((server) => ({ + id: JSON.stringify(server), + name: server.name, + transport: { + type: "stdio", + args: [], + ...server, + }, + })), + false, ); return { config: continueConfig, errors: localErrors }; diff --git a/core/context/mcp/index.ts b/core/context/mcp/index.ts index 588b063e9..c546c3bdf 100644 --- a/core/context/mcp/index.ts +++ b/core/context/mcp/index.ts @@ -4,16 +4,21 @@ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js" import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js"; import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; -import { ContinueConfig, MCPOptions, SlashCommand, Tool } from "../.."; -import { constructMcpSlashCommand } from "../../commands/slash/mcp"; -import { encodeMCPToolUri } from "../../tools/callTool"; -import MCPContextProvider from "../providers/MCPContextProvider"; +import { + MCPConnectionStatus, + MCPOptions, + MCPPrompt, + MCPServerStatus, +} from "../.."; export class MCPManagerSingleton { private static instance: MCPManagerSingleton; + public onConnectionsRefreshed?: () => void; private connections: Map = new Map(); + private abortController: AbortController = new AbortController(); + private constructor() {} public static getInstance(): MCPManagerSingleton { @@ -46,18 +51,83 @@ export class MCPManagerSingleton { this.connections.delete(id); } - async removeUnusedConnections(keepIds: string[]) { - const toRemove = Array.from(this.connections.keys()).filter( - (k) => !keepIds.includes(k), + setConnections(servers: MCPOptions[], forceRefresh: boolean) { + // Remove any connections that are no longer in config + this.connections.entries().forEach(([id, connection]) => { + if (!servers.find((s) => s.id === id)) { + connection.abortController.abort(); + void connection.client.close(); + this.connections.delete(id); + } + }); + + // Add any connections that are not yet in manager + servers.forEach((server) => { + if (!this.connections.has(server.id)) { + this.connections.set(server.id, new MCPConnection(server)); + } + }); + + // NOTE the id is made by stringifying the options + void this.refreshConnections(forceRefresh); + } + + async refreshConnections(force: boolean) { + this.abortController.abort(); + this.abortController = new AbortController(); + await Promise.race([ + new Promise((resolve) => { + this.abortController.signal.addEventListener("abort", () => { + resolve(undefined); + }); + }), + (async () => { + await Promise.all( + this.connections.values().map(async (connection) => { + await connection.connectClient(force, this.abortController.signal); + }), + ); + if (this.onConnectionsRefreshed) { + this.onConnectionsRefreshed(); + } + })(), + ]); + } + + getStatuses(): (MCPServerStatus & { client: Client })[] { + return Array.from( + this.connections.values().map((connection) => ({ + ...connection.getStatus(), + client: connection.client, + })), ); - await Promise.all(toRemove.map((id) => this.removeConnection(id))); } } +interface MCPTool { + name: string; + description?: string; + inputSchema: {}; +} + +type MCPResources = Awaited>["resources"]; + +const DEFAULT_MCP_TIMEOUT = 20_000; // 10 seconds + class MCPConnection { public client: Client; private transport: Transport; + private connectionPromise: Promise | null = null; + public abortController: AbortController; + + public status: MCPConnectionStatus = "not-connected"; + public errors: string[] = []; + + public prompts: MCPPrompt[] = []; + public tools: MCPTool[] = []; + public resources: MCPResources = []; + constructor(private readonly options: MCPOptions) { this.transport = this.constructTransport(options); @@ -70,6 +140,8 @@ class MCPConnection { capabilities: {}, }, ); + + this.abortController = new AbortController(); } private constructTransport(options: MCPOptions): Transport { @@ -95,131 +167,157 @@ class MCPConnection { } } - private isConnected: boolean = false; - private connectPromise: Promise | null = null; - - private async connectClient() { - if (this.isConnected) { - // Already connected - return; - } - - if (this.connectPromise) { - // Connection is already in progress; wait for it to complete - await this.connectPromise; - return; - } - - this.connectPromise = (async () => { - await this.client.connect(this.transport); - this.isConnected = true; - })(); - - try { - await this.connectPromise; - } finally { - // Reset the promise so future attempts can try again if necessary - this.connectPromise = null; - } + getStatus(): MCPServerStatus { + return { + ...this.options, + errors: this.errors, + prompts: this.prompts, + resources: this.resources, + tools: this.tools, + status: this.status, + }; } - async modifyConfig( - config: ContinueConfig, - mcpId: string, - signal: AbortSignal, - name: string, - faviconUrl: string | undefined, - ) { - try { - await Promise.race([ - this.connectClient(), - new Promise((_, reject) => { - signal.addEventListener("abort", () => - reject(new Error("Connection timed out")), - ); - }), - ]); - } catch (error) { - if (error instanceof Error) { - const msg = error.message.toLowerCase(); - if (msg.includes("spawn") && msg.includes("enoent")) { - const command = msg.split(" ")[1]; - throw new Error( - `command "${command}" not found. To use this MCP server, install the ${command} CLI.`, - ); - } else if ( - !error.message.startsWith("StdioClientTransport already started") - ) { - // don't throw error if it's just a "server already running" case - throw error; + async connectClient(forceRefresh: boolean, externalSignal: AbortSignal) { + if (!forceRefresh) { + // Already connected + if (this.status === "connected") { + return; + } + + // Connection is already in progress; wait for it to complete + if (this.connectionPromise) { + await this.connectionPromise; + return; + } + } + + this.status = "connecting"; + this.tools = []; + this.prompts = []; + this.resources = []; + this.errors = []; + + this.abortController.abort(); + this.abortController = new AbortController(); + + this.connectionPromise = Promise.race([ + // If aborted by a refresh or other, cancel and don't do anything + new Promise((resolve) => { + externalSignal.addEventListener("abort", () => { + resolve(undefined); + }); + }), + new Promise((resolve) => { + this.abortController.signal.addEventListener("abort", () => { + resolve(undefined); + }); + }), + (async () => { + const timeoutController = new AbortController(); + const connectionTimeout = setTimeout( + () => timeoutController.abort(), + this.options.timeout ?? DEFAULT_MCP_TIMEOUT, + ); + + try { + await Promise.race([ + new Promise((_, reject) => { + timeoutController.signal.addEventListener("abort", () => { + reject(new Error("Connection timed out")); + }); + }), + (async () => { + await this.client.connect(this.transport); + + const capabilities = this.client.getServerCapabilities(); + + // Resources <—> Context Provider + if (capabilities?.resources) { + try { + const { resources } = await this.client.listResources( + {}, + { signal: timeoutController.signal }, + ); + this.resources = resources; + } catch (e) { + let errorMessage = `Error loading resources for MCP Server ${this.options.name}`; + if (e instanceof Error) { + errorMessage += `: ${e.message}`; + } + this.errors.push(errorMessage); + } + } + + // Tools <—> Tools + if (capabilities?.tools) { + try { + const { tools } = await this.client.listTools( + {}, + { signal: timeoutController.signal }, + ); + this.tools = tools; + } catch (e) { + let errorMessage = `Error loading tools for MCP Server ${this.options.name}`; + if (e instanceof Error) { + errorMessage += `: ${e.message}`; + } + this.errors.push(errorMessage); + } + } + + // Prompts <—> Slash commands + if (capabilities?.prompts) { + try { + const { prompts } = await this.client.listPrompts( + {}, + { signal: timeoutController.signal }, + ); + this.prompts = prompts; + } catch (e) { + let errorMessage = `Error loading prompts for MCP Server ${this.options.name}`; + if (e instanceof Error) { + errorMessage += `: ${e.message}`; + } + this.errors.push(errorMessage); + } + } + + this.status = "connected"; + })(), + ]); + } catch (error) { + // Catch the case where for whatever reason is already connected + if ( + error instanceof Error && + error.message.startsWith("StdioClientTransport already started") + ) { + this.status = "connected"; + return; + } + + // Otherwise it's a connection error + let errorMessage = `Failed to connect to MCP server ${this.options.name}`; + if (error instanceof Error) { + const msg = error.message.toLowerCase(); + if (msg.includes("spawn") && msg.includes("enoent")) { + const command = msg.split(" ")[1]; + errorMessage += `command "${command}" not found. To use this MCP server, install the ${command} CLI.`; + } else { + errorMessage += ": " + error.message; + } + } + + this.status = "error"; + this.errors.push(errorMessage); + } finally { + this.connectionPromise = null; + clearTimeout(connectionTimeout); } - } else { - throw error; - } - } + })(), + ]); - const capabilities = this.client.getServerCapabilities(); - - // Resources <—> Context Provider - if (capabilities?.resources) { - const { resources } = await this.client.listResources({}, { signal }); - const submenuItems = resources.map((resource: any) => ({ - title: resource.name, - description: resource.description, - id: resource.uri, - icon: faviconUrl, - })); - - if (!config.contextProviders) { - config.contextProviders = []; - } - - config.contextProviders.push( - new MCPContextProvider({ - submenuItems, - mcpId, - }), - ); - } - - // Tools <—> Tools - if (capabilities?.tools) { - const { tools } = await this.client.listTools({}, { signal }); - const continueTools: Tool[] = tools.map((tool: any) => ({ - displayTitle: name + " " + tool.name, - function: { - description: tool.description, - name: tool.name, - parameters: tool.inputSchema, - }, - faviconUrl, - readonly: false, - type: "function", - wouldLikeTo: "", - uri: encodeMCPToolUri(mcpId, tool.name), - })); - - config.tools = [...continueTools, ...config.tools]; - } - - // Prompts <—> Slash commands - if (capabilities?.prompts) { - const { prompts } = await this.client.listPrompts({}, { signal }); - if (!config.slashCommands) { - config.slashCommands = []; - } - - const slashCommands: SlashCommand[] = prompts.map((prompt: any) => - constructMcpSlashCommand( - this.client, - prompt.name, - prompt.description, - prompt.arguments?.map((a: any) => a.name), - ), - ); - - config.slashCommands.push(...slashCommands); - } + await this.connectionPromise; } } diff --git a/core/core.ts b/core/core.ts index 629aa84ca..aa0561697 100644 --- a/core/core.ts +++ b/core/core.ts @@ -43,6 +43,7 @@ import { } from "."; import { isLocalAssistantFile } from "./config/loadLocalAssistants"; +import { MCPManagerSingleton } from "./context/mcp"; import { shouldIgnore } from "./indexing/shouldIgnore"; import { walkDirCache } from "./indexing/walkDir"; import { llmStreamChat } from "./llm/streamChat"; @@ -120,6 +121,9 @@ export class Core { this.messenger, ); + const mcpManager = MCPManagerSingleton.getInstance(); + mcpManager.onConnectionsRefreshed = this.configHandler.reloadConfig; + this.configHandler.onConfigUpdate(async (result) => { const serializedResult = await this.configHandler.getSerializedConfig(); this.messenger.send("configUpdate", { diff --git a/core/index.d.ts b/core/index.d.ts index 6926179bf..37d17296b 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -43,13 +43,13 @@ export interface IndexingProgressUpdate { desc: string; shouldClearIndexes?: boolean; status: - | "loading" - | "indexing" - | "done" - | "failed" - | "paused" - | "disabled" - | "cancelled"; + | "loading" + | "indexing" + | "done" + | "failed" + | "paused" + | "disabled" + | "cancelled"; debugInfo?: string; } @@ -316,7 +316,12 @@ export interface CompletionOptions extends BaseCompletionOptions { model: string; } -export type ChatMessageRole = "user" | "assistant" | "thinking" | "system" | "tool"; +export type ChatMessageRole = + | "user" + | "assistant" + | "thinking" + | "system" + | "tool"; export type TextMessagePart = { type: "text"; @@ -692,10 +697,10 @@ export interface IDE { getCurrentFile(): Promise< | undefined | { - isUntitled: boolean; - path: string; - contents: string; - } + isUntitled: boolean; + path: string; + contents: string; + } >; getLastFileSaveTimestamp?(): number; @@ -879,11 +884,11 @@ export interface CustomCommand { export interface Prediction { type: "content"; content: - | string - | { - type: "text"; - text: string; - }[]; + | string + | { + type: "text"; + text: string; + }[]; } export interface ToolExtras { @@ -1042,8 +1047,36 @@ export interface SSEOptions { export type TransportOptions = StdioOptions | WebSocketOptions | SSEOptions; export interface MCPOptions { + name: string; + id: string; transport: TransportOptions; faviconUrl?: string; + timeout?: number; +} + +export type MCPConnectionStatus = + | "connecting" + | "connected" + | "error" + | "not-connected"; + +export interface MCPPrompt { + name: string; + description?: string; + arguments?: { + name: string; + description?: string; + required?: boolean; + }[]; +} + +export interface MCPServerStatus extends MCPOptions { + status: MCPConnectionStatus; + errors: string[]; + + prompts: MCPPrompt[]; + tools: MCPTool[]; + resources: MCPResource[]; } export interface ContinueUIConfig { @@ -1069,6 +1102,11 @@ export interface ExperimentalModelRoles { applyCodeBlock?: string; } +export interface ExperimentalMCPOptions { + transport: TransportOptions; + faviconUrl?: string; +} + export type EditStatus = | "not-started" | "streaming" @@ -1152,7 +1190,7 @@ export interface ExperimentalConfig { * This is needed to crawl a large number of documentation sites that are dynamically rendered. */ useChromiumForDocsCrawling?: boolean; - modelContextProtocolServers?: MCPOptions[]; + modelContextProtocolServers?: ExperimentalMCPOptions[]; } export interface AnalyticsConfig { @@ -1223,9 +1261,9 @@ export interface Config { embeddingsProvider?: EmbeddingsProviderDescription | ILLM; /** The model that Continue will use for tab autocompletions. */ tabAutocompleteModel?: - | CustomLLM - | ModelDescription - | (CustomLLM | ModelDescription)[]; + | CustomLLM + | ModelDescription + | (CustomLLM | ModelDescription)[]; /** Options for tab autocomplete */ tabAutocompleteOptions?: Partial; /** UI styles customization */ @@ -1246,8 +1284,8 @@ export interface ContinueConfig { systemMessage?: string; completionOptions?: BaseCompletionOptions; requestOptions?: RequestOptions; - slashCommands?: SlashCommand[]; - contextProviders?: IContextProvider[]; + slashCommands: SlashCommand[]; + contextProviders: IContextProvider[]; disableSessionTitles?: boolean; disableIndexing?: boolean; userToken?: string; @@ -1257,6 +1295,7 @@ export interface ContinueConfig { analytics?: AnalyticsConfig; docs?: SiteIndexingConfig[]; tools: Tool[]; + mcpServerStatuses: MCPServerStatus[]; rules?: string[]; modelsByRole: Record; selectedModelByRole: Record; @@ -1269,8 +1308,8 @@ export interface BrowserSerializedContinueConfig { systemMessage?: string; completionOptions?: BaseCompletionOptions; requestOptions?: RequestOptions; - slashCommands?: SlashCommandDescription[]; - contextProviders?: ContextProviderDescription[]; + slashCommands: SlashCommandDescription[]; + contextProviders: ContextProviderDescription[]; disableIndexing?: boolean; disableSessionTitles?: boolean; userToken?: string; @@ -1279,6 +1318,7 @@ export interface BrowserSerializedContinueConfig { analytics?: AnalyticsConfig; docs?: SiteIndexingConfig[]; tools: Tool[]; + mcpServerStatuses: MCPServerStatus[]; rules?: string[]; usePlatform: boolean; tabAutocompleteOptions?: Partial; @@ -1319,9 +1359,9 @@ export type PackageDetailsSuccess = PackageDetails & { export type PackageDocsResult = { packageInfo: ParsedPackageInfo; } & ( - | { error: string; details?: never } - | { details: PackageDetailsSuccess; error?: never } - ); + | { error: string; details?: never } + | { details: PackageDetailsSuccess; error?: never } +); export interface TerminalOptions { reuseTerminal?: boolean; diff --git a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx index 20dae9160..fd85fcc1b 100644 --- a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx +++ b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx @@ -4,17 +4,17 @@ import { WrenchScrewdriverIcon as WrenchScrewdriverIconOutline, } from "@heroicons/react/24/outline"; import { WrenchScrewdriverIcon as WrenchScrewdriverIconSolid } from "@heroicons/react/24/solid"; -import { useEffect, useRef, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { useDispatch } from "react-redux"; import { lightGray, vscForeground } from "../.."; import { useAppSelector } from "../../../redux/hooks"; +import { selectIsInEditMode } from "../../../redux/slices/sessionSlice"; import { toggleUseTools } from "../../../redux/slices/uiSlice"; import { ToolTip } from "../../gui/Tooltip"; import InfoHover from "../../InfoHover"; import HoverItem from "./HoverItem"; import PopoverTransition from "./PopoverTransition"; import ToolDropdownItem from "./ToolDropdownItem"; -import { selectIsInEditMode } from "../../../redux/slices/sessionSlice"; interface ToolDropdownProps { disabled: boolean; @@ -50,6 +50,23 @@ export default function ToolDropdown(props: ToolDropdownProps) { } }, [isDropdownOpen]); + const tools = useAppSelector((store) => store.config.config.tools); + + // Detect duplicate tool names + const duplicateDetection = useMemo(() => { + const counts: Record = {}; + tools.forEach((tool) => { + if (counts[tool.function.name]) { + counts[tool.function.name] = counts[tool.function.name] + 1; + } else { + counts[tool.function.name] = 1; + } + }); + return Object.fromEntries( + Object.entries(counts).map(([k, v]) => [k, v > 1]), + ); + }, [tools]); + const isDisabled = props.disabled || isInEditMode; return ( @@ -154,13 +171,18 @@ export default function ToolDropdown(props: ToolDropdownProps) {
- {availableTools.map((tool: any) => ( + {availableTools.map((tool) => ( - + ))}
diff --git a/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx b/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx index 5df66f147..4e2a3fd66 100644 --- a/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx +++ b/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx @@ -1,17 +1,20 @@ +import { InformationCircleIcon } from "@heroicons/react/24/outline"; import { Tool } from "core"; import { useEffect } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; +import { useAppSelector } from "../../../redux/hooks"; import { addTool, toggleToolSetting } from "../../../redux/slices/uiSlice"; -import { RootState } from "../../../redux/store"; +import { ToolTip } from "../../gui/Tooltip"; interface ToolDropdownItemProps { tool: Tool; + duplicatesDetected: boolean; } function ToolDropdownItem(props: ToolDropdownItemProps) { const dispatch = useDispatch(); - const settings = useSelector( - (state: RootState) => state.ui.toolSettings[props.tool.function.name], + const settings = useAppSelector( + (state) => state.ui.toolSettings[props.tool.function.name], ); useEffect(() => { @@ -34,6 +37,29 @@ function ToolDropdownItem(props: ToolDropdownItemProps) { }} > + {props.duplicatesDetected ? ( + <> + + + +

+ Duplicate tool name{" "} + {props.tool.function.name}{" "} + + detected. Permissions will conflict and usage may be + unpredictable + +

+
+ + ) : null} {props.tool.faviconUrl && ( )} {props.tool.displayTitle}{" "} - {/* */}
{(settings === "allowedWithPermission" || settings === undefined) && ( From 2c0582dc086a618b6218e372b8501609449f42a3 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 21 Mar 2025 10:14:07 -0700 Subject: [PATCH 03/12] MCP servers section in more page --- core/config/load.ts | 12 +- core/config/profile/doLoadConfig.ts | 4 +- core/config/yaml/loadYaml.ts | 2 +- core/context/mcp/index.ts | 45 +++-- core/core.ts | 9 +- core/index.d.ts | 18 ++ core/protocol/core.ts | 6 + core/protocol/passThrough.ts | 1 + .../constants/MessageTypes.kt | 1 + gui/src/pages/More/MCPServersPreview.tsx | 180 ++++++++++++++++++ gui/src/pages/More/More.tsx | 5 + gui/src/redux/slices/configSlice.ts | 1 + 12 files changed, 257 insertions(+), 27 deletions(-) create mode 100644 gui/src/pages/More/MCPServersPreview.tsx diff --git a/core/config/load.ts b/core/config/load.ts index de14a8f02..6597b86ae 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -545,11 +545,13 @@ async function intermediateToFinalConfig( // Trigger MCP server refreshes (Config is reloaded again once connected!) const mcpManager = MCPManagerSingleton.getInstance(); mcpManager.setConnections( - (config.experimental?.modelContextProtocolServers ?? []).map((server) => ({ - id: JSON.stringify(server), - name: "MCP Server", - ...server, - })), + (config.experimental?.modelContextProtocolServers ?? []).map( + (server, index) => ({ + id: `continue-mcp-server-${index + 1}`, + name: `MCP Server ${index + 1}`, + ...server, + }), + ), false, ); diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 10e4e73e9..8065718d9 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -149,7 +149,7 @@ export default async function doLoadConfig( const submenuItems = server.resources.map((resource) => ({ title: resource.name, - description: resource.description, + description: resource.description ?? resource.name, id: resource.uri, icon: server.faviconUrl, })); @@ -176,7 +176,7 @@ export default async function doLoadConfig( if (count > 1) { errors.push({ fatal: false, - message: `Duplicate tool name ${toolName} detected (${count} tools). Permissions will conflict and usage may be unpredictable`, + message: `Duplicate (${count}) tools named "${toolName}" detected. Permissions will conflict and usage may be unpredictable`, }); } }); diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 4aba17ae4..1830c80ed 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -373,7 +373,7 @@ async function configYamlToContinueConfig( const mcpManager = MCPManagerSingleton.getInstance(); mcpManager.setConnections( (config.mcpServers ?? []).map((server) => ({ - id: JSON.stringify(server), + id: server.name, name: server.name, transport: { type: "stdio", diff --git a/core/context/mcp/index.ts b/core/context/mcp/index.ts index c546c3bdf..e48d73319 100644 --- a/core/context/mcp/index.ts +++ b/core/context/mcp/index.ts @@ -8,7 +8,9 @@ import { MCPConnectionStatus, MCPOptions, MCPPrompt, + MCPResource, MCPServerStatus, + MCPTool, } from "../.."; export class MCPManagerSingleton { @@ -52,9 +54,12 @@ export class MCPManagerSingleton { } setConnections(servers: MCPOptions[], forceRefresh: boolean) { + let refresh = false; + // Remove any connections that are no longer in config - this.connections.entries().forEach(([id, connection]) => { + Array.from(this.connections.entries()).forEach(([id, connection]) => { if (!servers.find((s) => s.id === id)) { + refresh = true; connection.abortController.abort(); void connection.client.close(); this.connections.delete(id); @@ -64,12 +69,26 @@ 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)); } }); // NOTE the id is made by stringifying the options - void this.refreshConnections(forceRefresh); + if (refresh) { + void this.refreshConnections(forceRefresh); + } + } + + async refreshConnection(serverId: string) { + const connection = this.connections.get(serverId); + if (!connection) { + throw new Error(`MCP Connection ${serverId} not found`); + } + await connection.connectClient(true, this.abortController.signal); + if (this.onConnectionsRefreshed) { + this.onConnectionsRefreshed(); + } } async refreshConnections(force: boolean) { @@ -83,7 +102,7 @@ export class MCPManagerSingleton { }), (async () => { await Promise.all( - this.connections.values().map(async (connection) => { + Array.from(this.connections.values()).map(async (connection) => { await connection.connectClient(force, this.abortController.signal); }), ); @@ -95,23 +114,13 @@ export class MCPManagerSingleton { } getStatuses(): (MCPServerStatus & { client: Client })[] { - return Array.from( - this.connections.values().map((connection) => ({ - ...connection.getStatus(), - client: connection.client, - })), - ); + return Array.from(this.connections.values()).map((connection) => ({ + ...connection.getStatus(), + client: connection.client, + })); } } -interface MCPTool { - name: string; - description?: string; - inputSchema: {}; -} - -type MCPResources = Awaited>["resources"]; - const DEFAULT_MCP_TIMEOUT = 20_000; // 10 seconds class MCPConnection { @@ -126,7 +135,7 @@ class MCPConnection { public prompts: MCPPrompt[] = []; public tools: MCPTool[] = []; - public resources: MCPResources = []; + public resources: MCPResource[] = []; constructor(private readonly options: MCPOptions) { this.transport = this.constructTransport(options); diff --git a/core/core.ts b/core/core.ts index aa0561697..f011ccd95 100644 --- a/core/core.ts +++ b/core/core.ts @@ -122,7 +122,11 @@ export class Core { ); const mcpManager = MCPManagerSingleton.getInstance(); - mcpManager.onConnectionsRefreshed = this.configHandler.reloadConfig; + mcpManager.onConnectionsRefreshed = async () => { + // This ensures that it triggers a NEW load after waiting for config promise to finish + await this.configHandler.loadConfig(); + await this.configHandler.reloadConfig(); + }; this.configHandler.onConfigUpdate(async (result) => { const serializedResult = await this.configHandler.getSerializedConfig(); @@ -348,6 +352,9 @@ export class Core { return await this.configHandler.listOrganizations(); }); + on("mcp/reloadServer", async (msg) => { + mcpManager.refreshConnection(msg.data.id); + }); // Context providers on("context/addDocs", async (msg) => { void this.docsService.indexAndAdd(msg.data); diff --git a/core/index.d.ts b/core/index.d.ts index 37d17296b..6a6614b61 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1070,6 +1070,24 @@ export interface MCPPrompt { }[]; } +// Leaving here to ideate on +// export type ContinueConfigSource = "local-yaml" | "local-json" | "hub-assistant" | "hub" + +export interface MCPResource { + name: string; + uri: string; + description?: string; + mimeType?: string; +} +export interface MCPTool { + name: string; + description?: string; + inputSchema: { + type: "object"; + properties?: Record; + }; +} + export interface MCPServerStatus extends MCPOptions { status: MCPConnectionStatus; errors: string[]; diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 3ab9f1448..09d5ba5a9 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -94,6 +94,12 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, ContextItemWithId[], ]; + "mcp/reloadServer": [ + { + id: string; + }, + void, + ]; "context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap]; "context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]]; "autocomplete/complete": [AutocompleteInput, string[]]; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 30cf5417c..b4cf5185b 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -26,6 +26,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "config/openProfile", "config/updateSharedConfig", "config/updateSelectedModel", + "mcp/reloadServer", "context/getContextItems", "context/getSymbolsForFiles", "context/loadSubmenuItems", 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 fcf9a468b..7bce39c81 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 @@ -94,6 +94,7 @@ class MessageTypes { "config/openProfile", "config/updateSharedConfig", "config/updateSelectedModel", + "mcp/reloadServer", "context/getContextItems", "context/getSymbolsForFiles", "context/loadSubmenuItems", diff --git a/gui/src/pages/More/MCPServersPreview.tsx b/gui/src/pages/More/MCPServersPreview.tsx new file mode 100644 index 000000000..2cdc62e21 --- /dev/null +++ b/gui/src/pages/More/MCPServersPreview.tsx @@ -0,0 +1,180 @@ +import { + CircleStackIcon, + CommandLineIcon, + InformationCircleIcon, + WrenchScrewdriverIcon, +} from "@heroicons/react/24/outline"; +import { MCPServerStatus } from "core"; +import { useContext } from "react"; +import { SecondaryButton } from "../../components"; +import { ToolTip } from "../../components/gui/Tooltip"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { updateConfig } from "../../redux/slices/configSlice"; + +interface MCPServerStatusProps { + server: MCPServerStatus; +} +function MCPServerPreview({ server }: MCPServerStatusProps) { + const ideMessenger = useContext(IdeMessengerContext); + const config = useAppSelector((store) => store.config.config); + const dispatch = useAppDispatch(); + const toolsTooltipId = `${server.id}-tools`; + const promptsTooltipId = `${server.id}-prompts`; + const resourcesTooltipId = `${server.id}-resources`; + const errorsTooltipId = `${server.id}-errors`; + + async function onRefresh() { + // optimistic config update + dispatch( + updateConfig({ + ...config, + mcpServerStatuses: config.mcpServerStatuses.map((s) => + s.id === server.id + ? { + ...s, + status: "connecting", + } + : s, + ), + }), + ); + ideMessenger.post("mcp/reloadServer", { + id: server.id, + }); + } + + return ( +
+

{server.name}

+
+ {server.status === "not-connected" ? ( +
+
+ Not connected +
+ ) : server.status === "connected" ? ( +
+
+ Connected +
+ ) : server.status === "connecting" ? ( +
+
+ Connecting... +
+ ) : ( +
+
+ Error + + + {server.errors.map((error, idx) => ( + {error} + ))} + {server.errors.length === 0 ? ( + No known errors + ) : null} + +
+ )} + + Refresh + +
+
+ {/* Tools */} +
+ + {`Tools: ${server.tools.length}`} +
+ + {server.tools.map((tool, idx) => ( + {tool.name} + ))} + {server.tools.length === 0 ? ( + No tools + ) : null} + + + {/* Prompts */} +
+ + {`Prompts: ${server.prompts.length}`} +
+ + {server.prompts.map((prompt, idx) => ( + {prompt.name} + ))} + {server.prompts.length === 0 ? ( + No prompts + ) : null} + + {/* Resources */} +
+ + {`Resources: ${server.resources.length}`} +
+ + {server.resources.map((resource, idx) => ( + {resource.name} + ))} + {server.resources.length === 0 ? ( + No resources + ) : null} + +
+
+ ); +} +function MCPServersPreview() { + const servers = useAppSelector( + (store) => store.config.config.mcpServerStatuses, + ); + const ideMessenger = useContext(IdeMessengerContext); + + return ( +
+
+

MCP Servers

+
+ +
+
+ {servers.length === 0 && ( + { + ideMessenger.post("config/openProfile", { + profileId: undefined, + }); + }} + > + Add MCP Servers + + )} +
+ {servers.map((server, idx) => ( + + ))} +
+
+ ); +} + +export default MCPServersPreview; diff --git a/gui/src/pages/More/More.tsx b/gui/src/pages/More/More.tsx index 0adcc1849..a528559bc 100644 --- a/gui/src/pages/More/More.tsx +++ b/gui/src/pages/More/More.tsx @@ -15,6 +15,7 @@ import { saveCurrentSession } from "../../redux/thunks/session"; import { AccountButton } from "../config/AccountButton"; import IndexingProgress from "./IndexingProgress"; import KeyboardShortcuts from "./KeyboardShortcuts"; +import MCPServersPreview from "./MCPServersPreview"; import MoreHelpRow from "./MoreHelpRow"; import { RulesPreview } from "./RulesPreview"; @@ -66,6 +67,10 @@ function MorePage() {
+
+ +
+

Help center

diff --git a/gui/src/redux/slices/configSlice.ts b/gui/src/redux/slices/configSlice.ts index 39cf8bb60..3092f01c5 100644 --- a/gui/src/redux/slices/configSlice.ts +++ b/gui/src/redux/slices/configSlice.ts @@ -23,6 +23,7 @@ const EMPTY_CONFIG: BrowserSerializedContinueConfig = { contextProviders: [], models: [], tools: [], + mcpServerStatuses: [], usePlatform: true, modelsByRole: { chat: [], From 6345a415912e9c7645539bd63b060cd285eae49e Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 21 Mar 2025 10:29:23 -0700 Subject: [PATCH 04/12] mcp server UI updates --- .../InputToolbar/ToggleToolsButton.tsx | 4 +- gui/src/pages/More/MCPServersPreview.tsx | 84 +++++++++++-------- 2 files changed, 49 insertions(+), 39 deletions(-) diff --git a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx index fd85fcc1b..a626003f4 100644 --- a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx +++ b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx @@ -128,9 +128,9 @@ export default function ToolDropdown(props: ToolDropdownProps) { > -
+

{server.name}

- {server.status === "not-connected" ? ( -
-
- Not connected -
- ) : server.status === "connected" ? ( -
-
- Connected -
- ) : server.status === "connecting" ? ( -
-
- Connecting... -
- ) : ( -
-
- Error - - - {server.errors.map((error, idx) => ( - {error} - ))} - {server.errors.length === 0 ? ( - No known errors - ) : null} - -
- )} - + {server.status === "not-connected" ? ( +
+
+ Not connected +
+ ) : server.status === "connected" ? ( +
+
+ Connected +
+ ) : server.status === "connecting" ? ( +
+
+ Connecting... +
+ ) : ( +
+
+ Error +
+ )} + {server.errors.length ? ( + <> + + + {server.errors.map((error, idx) => ( + {error} + ))} + {server.errors.length === 0 ? ( + No known errors + ) : null} + + + ) : null} +
+
- Refresh - +
+ +
+ Refresh +
{/* Tools */} From c4ab5a2f226764e777095546dc3f0a34b9776250 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 21 Mar 2025 11:20:52 -0700 Subject: [PATCH 05/12] tool policies dialog --- .../InputToolbar/ToggleToolsButton.tsx | 164 +++--------------- .../InputToolbar/ToolDropdownItem.tsx | 24 +-- .../InputToolbar/ToolPermissionsDialog.tsx | 64 +++++++ 3 files changed, 103 insertions(+), 149 deletions(-) create mode 100644 gui/src/components/mainInput/InputToolbar/ToolPermissionsDialog.tsx diff --git a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx index a626003f4..52850d991 100644 --- a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx +++ b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx @@ -1,71 +1,39 @@ -import { Listbox } from "@headlessui/react"; import { EllipsisHorizontalCircleIcon as EllipsisHorizontalIcon, WrenchScrewdriverIcon as WrenchScrewdriverIconOutline, } from "@heroicons/react/24/outline"; import { WrenchScrewdriverIcon as WrenchScrewdriverIconSolid } from "@heroicons/react/24/solid"; -import { useEffect, useMemo, useRef, useState } from "react"; -import { useDispatch } from "react-redux"; -import { lightGray, vscForeground } from "../.."; -import { useAppSelector } from "../../../redux/hooks"; +import { useState } from "react"; +import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; import { selectIsInEditMode } from "../../../redux/slices/sessionSlice"; -import { toggleUseTools } from "../../../redux/slices/uiSlice"; +import { + setDialogMessage, + setShowDialog, + toggleUseTools, +} from "../../../redux/slices/uiSlice"; import { ToolTip } from "../../gui/Tooltip"; -import InfoHover from "../../InfoHover"; import HoverItem from "./HoverItem"; -import PopoverTransition from "./PopoverTransition"; -import ToolDropdownItem from "./ToolDropdownItem"; +import ToolPermissionsDialog from "./ToolPermissionsDialog"; -interface ToolDropdownProps { +interface ToggleToolsButtonProps { disabled: boolean; } -export default function ToolDropdown(props: ToolDropdownProps) { - const buttonRef = useRef(null); - const dispatch = useDispatch(); - const [isDropdownOpen, setDropdownOpen] = useState(false); +export default function ToggleToolsButton(props: ToggleToolsButtonProps) { + const dispatch = useAppDispatch(); const [isHovered, setIsHovered] = useState(false); const useTools = useAppSelector((state) => state.ui.useTools); - const availableTools = useAppSelector((state) => state.config.config.tools); - const [showAbove, setShowAbove] = useState(false); const isInEditMode = useAppSelector(selectIsInEditMode); const ToolsIcon = useTools ? WrenchScrewdriverIconSolid : WrenchScrewdriverIconOutline; - useEffect(() => { - const checkPosition = () => { - if (buttonRef.current) { - const rect = buttonRef.current.getBoundingClientRect(); - const windowHeight = window.innerHeight; - const spaceBelow = windowHeight - rect.bottom; - setShowAbove(spaceBelow < 250); - } - }; - - if (isDropdownOpen) { - checkPosition(); - } - }, [isDropdownOpen]); - - const tools = useAppSelector((store) => store.config.config.tools); - - // Detect duplicate tool names - const duplicateDetection = useMemo(() => { - const counts: Record = {}; - tools.forEach((tool) => { - if (counts[tool.function.name]) { - counts[tool.function.name] = counts[tool.function.name] + 1; - } else { - counts[tool.function.name] = 1; - } - }); - return Object.fromEntries( - Object.entries(counts).map(([k, v]) => [k, v > 1]), - ); - }, [tools]); + function showTools() { + dispatch(setDialogMessage()); + dispatch(setShowDialog(true)); + } const isDisabled = props.disabled || isInEditMode; @@ -100,98 +68,18 @@ export default function ToolDropdown(props: ToolDropdownProps) { {useTools && !isDisabled && ( <> Tools - -
- {}} - as="div" - onClick={(e) => e.stopPropagation()} - disabled={isDisabled} - > - {({ open }) => ( - <> - { - e.stopPropagation(); - setDropdownOpen(!isDropdownOpen); - }} - className="text-lightgray flex cursor-pointer items-center border-none bg-transparent px-0 outline-none" - aria-disabled={isDisabled} - > - - - setDropdownOpen(false)} - > - -
-
- Tool policies{" "} - -

- - Automatic: - {" "} - Can be used without asking -

-

- - Allowed: - {" "} - Will ask before using -

-

- - Disabled: - {" "} - Cannot be used -

-
- } - /> -
-
-
- {availableTools.map((tool) => ( - - - - ))} -
- - - - )} - +
{ + e.stopPropagation(); + showTools(); + }} + className="text-lightgray flex cursor-pointer items-center" + aria-disabled={isDisabled} + > +
+ Tool policies )}
diff --git a/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx b/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx index 4e2a3fd66..64a36c959 100644 --- a/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx +++ b/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx @@ -29,14 +29,14 @@ function ToolDropdownItem(props: ToolDropdownItemProps) { return (
{ dispatch(toggleToolSetting(props.tool.function.name)); e.stopPropagation(); e.preventDefault(); }} > - +
{props.duplicatesDetected ? ( <> ) : null} - {props.tool.faviconUrl && ( - {props.tool.displayTitle} - )} - {props.tool.displayTitle}{" "} - + + {props.tool.faviconUrl && ( + {props.tool.displayTitle} + )} + {props.tool.displayTitle}{" "} + +
{(settings === "allowedWithPermission" || settings === undefined) && ( Allowed diff --git a/gui/src/components/mainInput/InputToolbar/ToolPermissionsDialog.tsx b/gui/src/components/mainInput/InputToolbar/ToolPermissionsDialog.tsx new file mode 100644 index 000000000..e8ca63718 --- /dev/null +++ b/gui/src/components/mainInput/InputToolbar/ToolPermissionsDialog.tsx @@ -0,0 +1,64 @@ +import { useMemo } from "react"; +import { useAppSelector } from "../../../redux/hooks"; +import InfoHover from "../../InfoHover"; +import ToolDropdownItem from "./ToolDropdownItem"; + +const ToolPermissionsDialog = () => { + const availableTools = useAppSelector((state) => state.config.config.tools); + + // Detect duplicate tool names + const duplicateDetection = useMemo(() => { + const counts: Record = {}; + availableTools.forEach((tool) => { + if (counts[tool.function.name]) { + counts[tool.function.name] = counts[tool.function.name] + 1; + } else { + counts[tool.function.name] = 1; + } + }); + return Object.fromEntries( + Object.entries(counts).map(([k, v]) => [k, v > 1]), + ); + }, [availableTools]); + + return ( +
+
+

Tool policies

+ +

+ Automatic: Can be used + without asking +

+

+ Allowed: Will ask + before using +

+

+ Disabled: Cannot be used +

+
+ } + /> +
+
+ {availableTools.map((tool) => ( + + ))} +
+
+ ); +}; + +export default ToolPermissionsDialog; From 03e7d5d1e931af67deeb81a9cae0852dc9bdd3a4 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 21 Mar 2025 11:35:38 -0700 Subject: [PATCH 06/12] tool groupe name --- core/config/profile/doLoadConfig.ts | 1 + core/index.d.ts | 1 + core/tools/builtIn.ts | 3 ++- core/tools/definitions/createNewFile.ts | 3 ++- core/tools/definitions/exactSearch.ts | 3 ++- .../definitions/readCurrentlyOpenFile.ts | 3 ++- core/tools/definitions/readFile.ts | 3 ++- core/tools/definitions/runTerminalCommand.ts | 3 ++- core/tools/definitions/searchWeb.ts | 3 ++- core/tools/definitions/viewDiff.ts | 3 ++- core/tools/definitions/viewRepoMap.ts | 3 ++- core/tools/definitions/viewSubdirectory.ts | 3 ++- .../InputToolbar/ToolDropdownItem.tsx | 19 ++++++++++--------- 13 files changed, 32 insertions(+), 19 deletions(-) diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 8065718d9..33bdf9b6c 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -134,6 +134,7 @@ export default async function doLoadConfig( type: "function" as const, wouldLikeTo: "", uri: encodeMCPToolUri(server.id, tool.name), + group: server.name, })); newConfig.tools.push(...serverTools); diff --git a/core/index.d.ts b/core/index.d.ts index 6a6614b61..f73fec9ce 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -912,6 +912,7 @@ export interface Tool { readonly: boolean; uri?: string; faviconUrl?: string; + group: string; } interface ToolChoice { diff --git a/core/tools/builtIn.ts b/core/tools/builtIn.ts index d15db456c..268cbb9a8 100644 --- a/core/tools/builtIn.ts +++ b/core/tools/builtIn.ts @@ -8,4 +8,5 @@ export enum BuiltInToolNames { ExactSearch = "builtin_exact_search", SearchWeb = "builtin_search_web", ViewDiff = "builtin_view_diff", -} \ No newline at end of file +} +export const BUILT_IN_GROUP_NAME = "Built-In"; diff --git a/core/tools/definitions/createNewFile.ts b/core/tools/definitions/createNewFile.ts index 7af42d6a8..f932ae87b 100644 --- a/core/tools/definitions/createNewFile.ts +++ b/core/tools/definitions/createNewFile.ts @@ -1,10 +1,11 @@ import { Tool } from "../.."; -import { BuiltInToolNames } from "../builtIn"; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; export const createNewFileTool: Tool = { type: "function", displayTitle: "Create New File", wouldLikeTo: "create a new file", + group: BUILT_IN_GROUP_NAME, readonly: false, function: { name: BuiltInToolNames.CreateNewFile, diff --git a/core/tools/definitions/exactSearch.ts b/core/tools/definitions/exactSearch.ts index 8358b55da..400adbd9e 100644 --- a/core/tools/definitions/exactSearch.ts +++ b/core/tools/definitions/exactSearch.ts @@ -1,11 +1,12 @@ import { Tool } from "../.."; -import { BuiltInToolNames } from "../builtIn"; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; export const exactSearchTool: Tool = { type: "function", displayTitle: "Exact Search", wouldLikeTo: 'search for "{{{ query }}}" in the repository', readonly: true, + group: BUILT_IN_GROUP_NAME, function: { name: BuiltInToolNames.ExactSearch, description: "Perform an exact search over the repository using ripgrep.", diff --git a/core/tools/definitions/readCurrentlyOpenFile.ts b/core/tools/definitions/readCurrentlyOpenFile.ts index 5abc2edb1..75a0e8169 100644 --- a/core/tools/definitions/readCurrentlyOpenFile.ts +++ b/core/tools/definitions/readCurrentlyOpenFile.ts @@ -1,11 +1,12 @@ import { Tool } from "../.."; -import { BuiltInToolNames } from "../builtIn"; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; export const readCurrentlyOpenFileTool: Tool = { type: "function", displayTitle: "Read Currently Open File", wouldLikeTo: "read the current file", readonly: true, + group: BUILT_IN_GROUP_NAME, function: { name: BuiltInToolNames.ReadCurrentlyOpenFile, description: diff --git a/core/tools/definitions/readFile.ts b/core/tools/definitions/readFile.ts index 4f5366e23..53d381e62 100644 --- a/core/tools/definitions/readFile.ts +++ b/core/tools/definitions/readFile.ts @@ -1,11 +1,12 @@ import { Tool } from "../.."; -import { BuiltInToolNames } from "../builtIn"; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; export const readFileTool: Tool = { type: "function", displayTitle: "Read File", wouldLikeTo: "read {{{ filepath }}}", readonly: true, + group: BUILT_IN_GROUP_NAME, function: { name: BuiltInToolNames.ReadFile, description: diff --git a/core/tools/definitions/runTerminalCommand.ts b/core/tools/definitions/runTerminalCommand.ts index 1b526009a..2b7882167 100644 --- a/core/tools/definitions/runTerminalCommand.ts +++ b/core/tools/definitions/runTerminalCommand.ts @@ -1,11 +1,12 @@ import { Tool } from "../.."; -import { BuiltInToolNames } from "../builtIn"; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; export const runTerminalCommandTool: Tool = { type: "function", displayTitle: "Run Terminal Command", wouldLikeTo: "run a terminal command", readonly: false, + group: BUILT_IN_GROUP_NAME, function: { name: BuiltInToolNames.RunTerminalCommand, description: diff --git a/core/tools/definitions/searchWeb.ts b/core/tools/definitions/searchWeb.ts index dfbcb04f7..7e2724a7c 100644 --- a/core/tools/definitions/searchWeb.ts +++ b/core/tools/definitions/searchWeb.ts @@ -1,12 +1,13 @@ import { Tool } from "../.."; -import { BuiltInToolNames } from "../builtIn"; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; export const searchWebTool: Tool = { type: "function", displayTitle: "Search Web", wouldLikeTo: 'search the web for "{{{ query }}}"', readonly: true, + group: BUILT_IN_GROUP_NAME, function: { name: BuiltInToolNames.SearchWeb, description: diff --git a/core/tools/definitions/viewDiff.ts b/core/tools/definitions/viewDiff.ts index e54086d05..3da0c71a9 100644 --- a/core/tools/definitions/viewDiff.ts +++ b/core/tools/definitions/viewDiff.ts @@ -1,12 +1,13 @@ import { Tool } from "../.."; -import { BuiltInToolNames } from "../builtIn"; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; export const viewDiffTool: Tool = { type: "function", displayTitle: "View Diff", wouldLikeTo: "view a diff", readonly: true, + group: BUILT_IN_GROUP_NAME, function: { name: BuiltInToolNames.ViewDiff, description: "View the current diff of working changes", diff --git a/core/tools/definitions/viewRepoMap.ts b/core/tools/definitions/viewRepoMap.ts index 9cf3d319d..60d671177 100644 --- a/core/tools/definitions/viewRepoMap.ts +++ b/core/tools/definitions/viewRepoMap.ts @@ -1,12 +1,13 @@ import { Tool } from "../.."; -import { BuiltInToolNames } from "../builtIn"; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; export const viewRepoMapTool: Tool = { type: "function", displayTitle: "View Repo Map", wouldLikeTo: "view the repository map", readonly: true, + group: BUILT_IN_GROUP_NAME, function: { name: BuiltInToolNames.ViewRepoMap, description: "View the repository map", diff --git a/core/tools/definitions/viewSubdirectory.ts b/core/tools/definitions/viewSubdirectory.ts index 70b7524bd..b78daba76 100644 --- a/core/tools/definitions/viewSubdirectory.ts +++ b/core/tools/definitions/viewSubdirectory.ts @@ -1,11 +1,12 @@ import { Tool } from "../.."; -import { BuiltInToolNames } from "../builtIn"; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; export const viewSubdirectoryTool: Tool = { type: "function", displayTitle: "View Subdirectory", wouldLikeTo: 'view the contents of "{{{ directory_path }}}"', readonly: true, + group: BUILT_IN_GROUP_NAME, function: { name: BuiltInToolNames.ViewSubdirectory, description: "View the contents of a subdirectory", diff --git a/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx b/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx index 64a36c959..c75ea5847 100644 --- a/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx +++ b/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx @@ -29,21 +29,22 @@ function ToolDropdownItem(props: ToolDropdownItemProps) { return (
{ dispatch(toggleToolSetting(props.tool.function.name)); e.stopPropagation(); e.preventDefault(); }} > -
+
{props.duplicatesDetected ? ( <> - - +
+ +
) : null} - + {props.tool.faviconUrl && (
-
+
{(settings === "allowedWithPermission" || settings === undefined) && ( Allowed )} From edbf7d0b00ffffc5487ec61540c52403d93c60da Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 21 Mar 2025 12:53:15 -0700 Subject: [PATCH 07/12] down to duplicates --- core/config/profile/doLoadConfig.ts | 1 + core/llm/llm.test.ts | 1 + .../InputToolbar/ToolDropdownItem.tsx | 4 +-- .../InputToolbar/ToolPermissionsDialog.tsx | 31 ++++++++++++++----- gui/src/pages/More/MCPServersPreview.tsx | 2 +- 5 files changed, 29 insertions(+), 10 deletions(-) diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 33bdf9b6c..3429f2be4 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -230,6 +230,7 @@ export default async function doLoadConfig( newConfig, controlPlaneProxyInfo, ); + debugger; return { config: newConfig, errors, configLoadInterrupted: false }; } diff --git a/core/llm/llm.test.ts b/core/llm/llm.test.ts index ff897d5a3..efd98ae00 100644 --- a/core/llm/llm.test.ts +++ b/core/llm/llm.test.ts @@ -142,6 +142,7 @@ function testLLM( type: "function", wouldLikeTo: "Say hello", readonly: true, + group: "Hello", }, ], toolChoice: { diff --git a/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx b/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx index c75ea5847..26a681c75 100644 --- a/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx +++ b/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx @@ -29,7 +29,7 @@ function ToolDropdownItem(props: ToolDropdownItemProps) { return (
{ dispatch(toggleToolSetting(props.tool.function.name)); e.stopPropagation(); @@ -69,7 +69,7 @@ function ToolDropdownItem(props: ToolDropdownItemProps) { className="h-4 w-4" /> )} - {props.tool.displayTitle}{" "} + {props.tool.function.name}{" "}
diff --git a/gui/src/components/mainInput/InputToolbar/ToolPermissionsDialog.tsx b/gui/src/components/mainInput/InputToolbar/ToolPermissionsDialog.tsx index e8ca63718..6c0153dbe 100644 --- a/gui/src/components/mainInput/InputToolbar/ToolPermissionsDialog.tsx +++ b/gui/src/components/mainInput/InputToolbar/ToolPermissionsDialog.tsx @@ -1,3 +1,4 @@ +import { Tool } from "core"; import { useMemo } from "react"; import { useAppSelector } from "../../../redux/hooks"; import InfoHover from "../../InfoHover"; @@ -6,6 +7,17 @@ import ToolDropdownItem from "./ToolDropdownItem"; const ToolPermissionsDialog = () => { const availableTools = useAppSelector((state) => state.config.config.tools); + const toolsByGroup = useMemo(() => { + const byGroup: Record = {}; + for (const tool of availableTools) { + if (!byGroup[tool.group]) { + byGroup[tool.group] = []; + } + byGroup[tool.group].push(tool); + } + return Object.entries(byGroup); + }, [availableTools]); + // Detect duplicate tool names const duplicateDetection = useMemo(() => { const counts: Record = {}; @@ -48,13 +60,18 @@ const ToolPermissionsDialog = () => { } />
-
- {availableTools.map((tool) => ( - +
+ {toolsByGroup.map(([groupName, tools]) => ( +
+

{groupName}

+ {tools.map((tool) => ( + + ))} +
))}
diff --git a/gui/src/pages/More/MCPServersPreview.tsx b/gui/src/pages/More/MCPServersPreview.tsx index ac380e099..3d12a8f81 100644 --- a/gui/src/pages/More/MCPServersPreview.tsx +++ b/gui/src/pages/More/MCPServersPreview.tsx @@ -47,7 +47,7 @@ function MCPServerPreview({ server }: MCPServerStatusProps) { return (
-

{server.name}

+

{server.name}

{server.status === "not-connected" ? ( From a52bf60c903d49e12017fbd158276273042ee206 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 21 Mar 2025 12:59:19 -0700 Subject: [PATCH 08/12] fix duplicate tool entries --- core/config/yaml/loadYaml.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 1830c80ed..32d016010 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -111,7 +111,7 @@ async function configYamlToContinueConfig( const continueConfig: ContinueConfig = { slashCommands: [], models: [], - tools: allTools, + tools: [...allTools], mcpServerStatuses: [], systemMessage: config.rules?.join("\n"), experimental: { From 74024a217246ee9fe1dd971ef21a4df1de7c9d83 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 21 Mar 2025 13:01:39 -0700 Subject: [PATCH 09/12] remove debugger --- core/config/profile/doLoadConfig.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 3429f2be4..33bdf9b6c 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -230,7 +230,6 @@ export default async function doLoadConfig( newConfig, controlPlaneProxyInfo, ); - debugger; return { config: newConfig, errors, configLoadInterrupted: false }; } From 0a98d8775d27539ea42420e588592c65bffb03b2 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 21 Mar 2025 14:45:38 -0700 Subject: [PATCH 10/12] tool group toggle --- core/context/mcp/index.ts | 8 +++- gui/src/components/gui/Switch.tsx | 9 ++++- .../InputToolbar/ToolDropdownItem.tsx | 27 ++++++++----- .../InputToolbar/ToolPermissionsDialog.tsx | 40 ++++++++++++++----- gui/src/redux/slices/uiSlice.ts | 16 ++++++++ gui/src/redux/store.ts | 2 +- gui/src/redux/thunks/streamNormalInput.ts | 5 ++- 7 files changed, 82 insertions(+), 25 deletions(-) diff --git a/core/context/mcp/index.ts b/core/context/mcp/index.ts index e48d73319..3f26844f0 100644 --- a/core/context/mcp/index.ts +++ b/core/context/mcp/index.ts @@ -87,7 +87,7 @@ export class MCPManagerSingleton { } await connection.connectClient(true, this.abortController.signal); if (this.onConnectionsRefreshed) { - this.onConnectionsRefreshed(); + await this.onConnectionsRefreshed(); } } @@ -239,6 +239,12 @@ class MCPConnection { (async () => { await this.client.connect(this.transport); + // TODO register server notification handlers + // this.client.transport?.onmessage(msg => console.log()) + // this.client.setNotificationHandler(, notification => { + // console.log(notification) + // }) + const capabilities = this.client.getServerCapabilities(); // Resources <—> Context Provider diff --git a/gui/src/components/gui/Switch.tsx b/gui/src/components/gui/Switch.tsx index 8957038ac..068bb17c3 100644 --- a/gui/src/components/gui/Switch.tsx +++ b/gui/src/components/gui/Switch.tsx @@ -4,20 +4,27 @@ type ToggleSwitchProps = { isToggled: boolean; onToggle: () => void; text: string; + size?: number; }; const ToggleSwitch: React.FC = ({ isToggled, onToggle, text, + size = 16, }) => { return (
{text}
-
- {(settings === "allowedWithPermission" || settings === undefined) && ( - Allowed - )} - {settings === "allowedWithoutPermission" && ( - Automatic - )} - {settings === "disabled" && ( - Disabled - )} -
+ {props.excluded ? ( + Excluded + ) : ( +
+ {(settings === "allowedWithPermission" || settings === undefined) && ( + Ask First + )} + {settings === "allowedWithoutPermission" && ( + Automatic + )} + {settings === "disabled" && ( + Excluded + )} +
+ )}
); } diff --git a/gui/src/components/mainInput/InputToolbar/ToolPermissionsDialog.tsx b/gui/src/components/mainInput/InputToolbar/ToolPermissionsDialog.tsx index 6c0153dbe..731e27a34 100644 --- a/gui/src/components/mainInput/InputToolbar/ToolPermissionsDialog.tsx +++ b/gui/src/components/mainInput/InputToolbar/ToolPermissionsDialog.tsx @@ -1,11 +1,17 @@ import { Tool } from "core"; import { useMemo } from "react"; -import { useAppSelector } from "../../../redux/hooks"; +import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; +import { toggleToolGroupSetting } from "../../../redux/slices/uiSlice"; +import ToggleSwitch from "../../gui/Switch"; import InfoHover from "../../InfoHover"; import ToolDropdownItem from "./ToolDropdownItem"; const ToolPermissionsDialog = () => { const availableTools = useAppSelector((state) => state.config.config.tools); + const toolGroupSettings = useAppSelector( + (store) => store.ui.toolGroupSettings, + ); + const dispatch = useAppDispatch(); const toolsByGroup = useMemo(() => { const byGroup: Record = {}; @@ -60,17 +66,31 @@ const ToolPermissionsDialog = () => { } />
-
+
{toolsByGroup.map(([groupName, tools]) => ( -
-

{groupName}

- {tools.map((tool) => ( - +
+

{groupName}

+ dispatch(toggleToolGroupSetting(groupName))} + text="" + size={12} /> - ))} +
+
+ {tools.map((tool) => ( + + ))} + {toolGroupSettings[groupName] === "exclude" && ( +
+ )} +
))}
diff --git a/gui/src/redux/slices/uiSlice.ts b/gui/src/redux/slices/uiSlice.ts index 8b03d30f3..d46445468 100644 --- a/gui/src/redux/slices/uiSlice.ts +++ b/gui/src/redux/slices/uiSlice.ts @@ -12,6 +12,8 @@ type ToolSetting = | "allowedWithoutPermission" | "disabled"; +type ToolGroupSetting = "include" | "exclude"; + type UIState = { showDialog: boolean; dialogMessage: string | JSX.Element | undefined; @@ -22,6 +24,7 @@ type UIState = { shouldAddFileForEditing: boolean; useTools: boolean; toolSettings: { [toolName: string]: ToolSetting }; + toolGroupSettings: { [toolGroupName: string]: ToolGroupSetting }; ttsActive: boolean; }; @@ -51,6 +54,9 @@ export const uiSlice = createSlice({ [BuiltInToolNames.SearchWeb]: "allowedWithoutPermission", [BuiltInToolNames.ViewDiff]: "allowedWithoutPermission", }, + toolGroupSettings: { + BUILT_IN_GROUP_NAME: "include", + }, } as UIState, reducers: { setOnboardingCard: ( @@ -109,6 +115,15 @@ export const uiSlice = createSlice({ break; } }, + toggleToolGroupSetting: (state, action: PayloadAction) => { + const setting = state.toolGroupSettings[action.payload] ?? "include"; + + if (setting === "include") { + state.toolGroupSettings[action.payload] = "exclude"; + } else { + state.toolGroupSettings[action.payload] = "include"; + } + }, setTTSActive: (state, { payload }: PayloadAction) => { state.ttsActive = payload; }, @@ -124,6 +139,7 @@ export const { setHasDismissedExploreDialog, toggleUseTools, toggleToolSetting, + toggleToolGroupSetting, addTool, setTTSActive, } = uiSlice.actions; diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 0e7e5f805..2cb7d2ded 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -58,7 +58,7 @@ const saveSubsetFilters = [ // Don't persist any of the edit state for now createFilter("editModeState", []), createFilter("config", ["defaultModelTitle"]), - createFilter("ui", ["toolSettings", "useTools"]), + createFilter("ui", ["toolSettings", "toolGroupSettings", "useTools"]), createFilter("indexing", []), createFilter("tabs", ["tabs"]), ]; diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index c49d79195..76c05f4ec 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -30,6 +30,7 @@ export const streamNormalInput = createAsyncThunk< const state = getState(); const defaultModel = selectDefaultModel(state); const toolSettings = state.ui.toolSettings; + const toolGroupSettings = state.ui.toolGroupSettings; const streamAborter = state.session.streamAborter; const useTools = state.ui.useTools; if (!defaultModel) { @@ -47,7 +48,9 @@ export const streamNormalInput = createAsyncThunk< completionOptions: includeTools ? { tools: state.config.config.tools.filter( - (tool) => toolSettings[tool.function.name] !== "disabled", + (tool) => + toolSettings[tool.function.name] !== "disabled" && + toolGroupSettings[tool.group] !== "exclude", ), } : {}, From ac277b969d4b6b52ecda0a089eb7c4f333e40e39 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 21 Mar 2025 14:59:21 -0700 Subject: [PATCH 11/12] fix refresh --- core/context/mcp/index.ts | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/core/context/mcp/index.ts b/core/context/mcp/index.ts index 3f26844f0..7e77561bf 100644 --- a/core/context/mcp/index.ts +++ b/core/context/mcp/index.ts @@ -87,7 +87,7 @@ export class MCPManagerSingleton { } await connection.connectClient(true, this.abortController.signal); if (this.onConnectionsRefreshed) { - await this.onConnectionsRefreshed(); + this.onConnectionsRefreshed(); } } @@ -237,7 +237,23 @@ class MCPConnection { }); }), (async () => { - await this.client.connect(this.transport); + this.transport = this.constructTransport(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); + } else { + throw error; + } + } // TODO register server notification handlers // this.client.transport?.onmessage(msg => console.log()) @@ -302,15 +318,6 @@ class MCPConnection { })(), ]); } catch (error) { - // Catch the case where for whatever reason is already connected - if ( - error instanceof Error && - error.message.startsWith("StdioClientTransport already started") - ) { - this.status = "connected"; - return; - } - // Otherwise it's a connection error let errorMessage = `Failed to connect to MCP server ${this.options.name}`; if (error instanceof Error) { From 5e8eec3878210e8101c2228752d911f1f286bc0f Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 21 Mar 2025 15:02:39 -0700 Subject: [PATCH 12/12] fix tsc --- core/config/profile/doLoadConfig.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 33bdf9b6c..53c35528d 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -175,7 +175,7 @@ export default async function doLoadConfig( }); Object.entries(counts).forEach(([toolName, count]) => { if (count > 1) { - errors.push({ + errors!.push({ fatal: false, message: `Duplicate (${count}) tools named "${toolName}" detected. Permissions will conflict and usage may be unpredictable`, });