Skip to content

🗂️ refactor: Make MCPSubMenu consistent with MCPSelect #8650

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion api/server/routes/mcp.js
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,8 @@ router.post('/:serverName/reinitialize', requireJwtAuth, async (req, res) => {

logger.info(`[MCP Reinitialize] Reinitializing server: ${serverName}`);

const config = await loadCustomConfig();
const printConfig = false;
const config = await loadCustomConfig(printConfig);
if (!config || !config.mcpServers || !config.mcpServers[serverName]) {
return res.status(404).json({
error: `MCP server '${serverName}' not found in configuration`,
Expand Down
315 changes: 20 additions & 295 deletions client/src/components/Chat/Input/MCPSelect.tsx
Original file line number Diff line number Diff line change
@@ -1,114 +1,21 @@
import { useQueryClient } from '@tanstack/react-query';
import { Constants, QueryKeys } from 'librechat-data-provider';
import type { TUpdateUserPlugins, TPlugin } from 'librechat-data-provider';
import React, { memo, useCallback, useState, useMemo, useRef } from 'react';
import { useUpdateUserPluginsMutation } from 'librechat-data-provider/react-query';
import MCPConfigDialog, { ConfigFieldDetail } from '~/components/ui/MCP/MCPConfigDialog';
import { useMCPServerInitialization } from '~/hooks/MCP/useMCPServerInitialization';
import React, { memo, useCallback } from 'react';
import MCPConfigDialog from '~/components/ui/MCP/MCPConfigDialog';
import MCPServerStatusIcon from '~/components/ui/MCP/MCPServerStatusIcon';
import { useToastContext, useBadgeRowContext } from '~/Providers';
import MultiSelect from '~/components/ui/MultiSelect';
import { MCPIcon } from '~/components/svg';
import { useLocalize } from '~/hooks';
import { useMCPServerManager } from '~/hooks/MCP/useMCPServerManager';

function MCPSelect() {
const localize = useLocalize();
const { showToast } = useToastContext();
const { mcpSelect, startupConfig } = useBadgeRowContext();
const { mcpValues, setMCPValues, mcpToolDetails, isPinned } = mcpSelect;

// Get all configured MCP servers from config that allow chat menu
const configuredServers = useMemo(() => {
if (!startupConfig?.mcpServers) {
return [];
}
return Object.entries(startupConfig.mcpServers)
.filter(([, config]) => config.chatMenu !== false)
.map(([serverName]) => serverName);
}, [startupConfig?.mcpServers]);

const [isConfigModalOpen, setIsConfigModalOpen] = useState(false);
const [selectedToolForConfig, setSelectedToolForConfig] = useState<TPlugin | null>(null);
const previousFocusRef = useRef<HTMLElement | null>(null);

const queryClient = useQueryClient();

const updateUserPluginsMutation = useUpdateUserPluginsMutation({
onSuccess: async () => {
showToast({ message: localize('com_nav_mcp_vars_updated'), status: 'success' });

// tools so we dont leave tools available for use in chat if we revoke and thus kill mcp server
// auth values so customUserVars flags are updated in customUserVarsSection
// connection status so connection indicators are updated in the dropdown
await Promise.all([
queryClient.refetchQueries([QueryKeys.tools]),
queryClient.refetchQueries([QueryKeys.mcpAuthValues]),
queryClient.refetchQueries([QueryKeys.mcpConnectionStatus]),
]);
},
onError: (error: unknown) => {
console.error('Error updating MCP auth:', error);
showToast({
message: localize('com_nav_mcp_vars_update_error'),
status: 'error',
});
},
});

// Use the shared initialization hook
const { initializeServer, isInitializing, connectionStatus, cancelOAuthFlow, isCancellable } =
useMCPServerInitialization({
onSuccess: (serverName) => {
// Add to selected values after successful initialization
const currentValues = mcpValues ?? [];
if (!currentValues.includes(serverName)) {
setMCPValues([...currentValues, serverName]);
}
},
onError: (serverName) => {
// Find the tool/server configuration
const tool = mcpToolDetails?.find((t) => t.name === serverName);
const serverConfig = startupConfig?.mcpServers?.[serverName];
const serverStatus = connectionStatus[serverName];

// Check if this server would show a config button
const hasAuthConfig =
(tool?.authConfig && tool.authConfig.length > 0) ||
(serverConfig?.customUserVars && Object.keys(serverConfig.customUserVars).length > 0);

// Only open dialog if the server would have shown a config button
// (disconnected/error states always show button, connected only shows if hasAuthConfig)
const wouldShowButton =
!serverStatus ||
serverStatus.connectionState === 'disconnected' ||
serverStatus.connectionState === 'error' ||
(serverStatus.connectionState === 'connected' && hasAuthConfig);

if (!wouldShowButton) {
return; // Don't open dialog if no button would be shown
}

// Create tool object if it doesn't exist
const configTool = tool || {
name: serverName,
pluginKey: `${Constants.mcp_prefix}${serverName}`,
authConfig: serverConfig?.customUserVars
? Object.entries(serverConfig.customUserVars).map(([key, config]) => ({
authField: key,
label: config.title,
description: config.description,
}))
: [],
authenticated: false,
};

previousFocusRef.current = document.activeElement as HTMLElement;

// Open the config dialog on error
setSelectedToolForConfig(configTool);
setIsConfigModalOpen(true);
},
});
const {
configuredServers,
mcpValues,
isPinned,
placeholderText,
batchToggleServers,
getServerStatusIconProps,
getConfigDialogProps,
localize,
} = useMCPServerManager();

const renderSelectedValues = useCallback(
(values: string[], placeholder?: string) => {
Expand All @@ -123,137 +30,9 @@ function MCPSelect() {
[localize],
);

const handleConfigSave = useCallback(
(targetName: string, authData: Record<string, string>) => {
if (selectedToolForConfig && selectedToolForConfig.name === targetName) {
// Use the pluginKey directly since it's already in the correct format
console.log(
`[MCP Select] Saving config for ${targetName}, pluginKey: ${`${Constants.mcp_prefix}${targetName}`}`,
);
const payload: TUpdateUserPlugins = {
pluginKey: `${Constants.mcp_prefix}${targetName}`,
action: 'install',
auth: authData,
};
updateUserPluginsMutation.mutate(payload);
}
},
[selectedToolForConfig, updateUserPluginsMutation],
);

const handleConfigRevoke = useCallback(
(targetName: string) => {
if (selectedToolForConfig && selectedToolForConfig.name === targetName) {
// Use the pluginKey directly since it's already in the correct format
const payload: TUpdateUserPlugins = {
pluginKey: `${Constants.mcp_prefix}${targetName}`,
action: 'uninstall',
auth: {},
};
updateUserPluginsMutation.mutate(payload);

// Remove the server from selected values after revoke
const currentValues = mcpValues ?? [];
const filteredValues = currentValues.filter((name) => name !== targetName);
setMCPValues(filteredValues);
}
},
[selectedToolForConfig, updateUserPluginsMutation, mcpValues, setMCPValues],
);

const handleSave = useCallback(
(authData: Record<string, string>) => {
if (selectedToolForConfig) {
handleConfigSave(selectedToolForConfig.name, authData);
}
},
[selectedToolForConfig, handleConfigSave],
);

const handleRevoke = useCallback(() => {
if (selectedToolForConfig) {
handleConfigRevoke(selectedToolForConfig.name);
}
}, [selectedToolForConfig, handleConfigRevoke]);

const handleDialogOpenChange = useCallback((open: boolean) => {
setIsConfigModalOpen(open);

// Restore focus when dialog closes
if (!open && previousFocusRef.current) {
// Use setTimeout to ensure the dialog has fully closed before restoring focus
setTimeout(() => {
if (previousFocusRef.current && typeof previousFocusRef.current.focus === 'function') {
previousFocusRef.current.focus();
}
previousFocusRef.current = null;
}, 0);
}
}, []);

// Get connection status for all MCP servers (now from hook)
// Remove the duplicate useMCPConnectionStatusQuery since it's in the hook

// Modified setValue function that attempts to initialize disconnected servers
const filteredSetMCPValues = useCallback(
(values: string[]) => {
// Separate connected and disconnected servers
const connectedServers: string[] = [];
const disconnectedServers: string[] = [];

values.forEach((serverName) => {
const serverStatus = connectionStatus[serverName];
if (serverStatus?.connectionState === 'connected') {
connectedServers.push(serverName);
} else {
disconnectedServers.push(serverName);
}
});

// Only set connected servers as selected values
setMCPValues(connectedServers);

// Attempt to initialize each disconnected server (once)
disconnectedServers.forEach((serverName) => {
initializeServer(serverName);
});
},
[connectionStatus, setMCPValues, initializeServer],
);

const renderItemContent = useCallback(
(serverName: string, defaultContent: React.ReactNode) => {
const tool = mcpToolDetails?.find((t) => t.name === serverName);
const serverStatus = connectionStatus[serverName];
const serverConfig = startupConfig?.mcpServers?.[serverName];

const handleConfigClick = (e: React.MouseEvent) => {
e.stopPropagation();
e.preventDefault();

previousFocusRef.current = document.activeElement as HTMLElement;

const configTool = tool || {
name: serverName,
pluginKey: `${Constants.mcp_prefix}${serverName}`,
authConfig: serverConfig?.customUserVars
? Object.entries(serverConfig.customUserVars).map(([key, config]) => ({
authField: key,
label: config.title,
description: config.description,
}))
: [],
authenticated: false,
};
setSelectedToolForConfig(configTool);
setIsConfigModalOpen(true);
};

const handleCancelClick = (e: React.MouseEvent) => {
e.stopPropagation();
e.preventDefault();
cancelOAuthFlow(serverName);
};
const statusIconProps = getServerStatusIconProps(serverName);

// Common wrapper for the main content (check mark + text)
// Ensures Check & Text are adjacent and the group takes available space.
Expand All @@ -267,22 +46,7 @@ function MCPSelect() {
</button>
);

// Check if this server has customUserVars to configure
const hasCustomUserVars =
serverConfig?.customUserVars && Object.keys(serverConfig.customUserVars).length > 0;

const statusIcon = (
<MCPServerStatusIcon
serverName={serverName}
serverStatus={serverStatus}
tool={tool}
onConfigClick={handleConfigClick}
isInitializing={isInitializing(serverName)}
canCancel={isCancellable(serverName)}
onCancel={handleCancelClick}
hasCustomUserVars={hasCustomUserVars}
/>
);
const statusIcon = statusIconProps && <MCPServerStatusIcon {...statusIconProps} />;

if (statusIcon) {
return (
Expand All @@ -295,14 +59,7 @@ function MCPSelect() {

return mainContentWrapper;
},
[
isInitializing,
isCancellable,
mcpToolDetails,
cancelOAuthFlow,
connectionStatus,
startupConfig?.mcpServers,
],
[getServerStatusIconProps],
);

// Don't render if no servers are selected and not pinned
Expand All @@ -315,14 +72,14 @@ function MCPSelect() {
return null;
}

const placeholderText =
startupConfig?.interface?.mcpServers?.placeholder || localize('com_ui_mcp_servers');
const configDialogProps = getConfigDialogProps();

return (
<>
<MultiSelect
items={configuredServers}
selectedValues={mcpValues ?? []}
setSelectedValues={filteredSetMCPValues}
setSelectedValues={batchToggleServers}
defaultSelectedValues={mcpValues ?? []}
renderSelectedValues={renderSelectedValues}
renderItemContent={renderItemContent}
Expand All @@ -333,39 +90,7 @@ function MCPSelect() {
selectItemsClassName="border border-blue-600/50 bg-blue-500/10 hover:bg-blue-700/10"
selectClassName="group relative inline-flex items-center justify-center md:justify-start gap-1.5 rounded-full border border-border-medium text-sm font-medium transition-all md:w-full size-9 p-2 md:p-3 bg-transparent shadow-sm hover:bg-surface-hover hover:shadow-md active:shadow-inner"
/>
{selectedToolForConfig && (
<MCPConfigDialog
serverName={selectedToolForConfig.name}
serverStatus={connectionStatus[selectedToolForConfig.name]}
isOpen={isConfigModalOpen}
onOpenChange={handleDialogOpenChange}
fieldsSchema={(() => {
const schema: Record<string, ConfigFieldDetail> = {};
if (selectedToolForConfig?.authConfig) {
selectedToolForConfig.authConfig.forEach((field) => {
schema[field.authField] = {
title: field.label,
description: field.description,
};
});
}
return schema;
})()}
initialValues={(() => {
const initial: Record<string, string> = {};
// Note: Actual initial values might need to be fetched if they are stored user-specifically
if (selectedToolForConfig?.authConfig) {
selectedToolForConfig.authConfig.forEach((field) => {
initial[field.authField] = ''; // Or fetched value
});
}
return initial;
})()}
onSave={handleSave}
onRevoke={handleRevoke}
isSubmitting={updateUserPluginsMutation.isLoading}
/>
)}
{configDialogProps && <MCPConfigDialog {...configDialogProps} />}
</>
);
}
Expand Down
Loading