mirror of
https://github.com/danny-avila/LibreChat.git
synced 2025-12-27 13:48:51 +01:00
🏗️ feat: Dynamic MCP Server Infrastructure with Access Control (#10787)
* Feature: Dynamic MCP Server with Full UI Management * 🚦 feat: Add MCP Connection Status icons to MCPBuilder panel (#10805) * feature: Add MCP server connection status icons to MCPBuilder panel * refactor: Simplify MCPConfigDialog rendering in MCPBuilderPanel --------- Co-authored-by: Atef Bellaaj <slalom.bellaaj@external.daimlertruck.com> Co-authored-by: Danny Avila <danny@librechat.ai> * fix: address code review feedback for MCP server management - Fix OAuth secret preservation to avoid mutating input parameter by creating a merged config copy in ServerConfigsDB.update() - Improve error handling in getResourcePermissionsMap to propagate critical errors instead of silently returning empty Map - Extract duplicated MCP server filter logic by exposing selectableServers from useMCPServerManager hook and using it in MCPSelect component * test: Update PermissionService tests to throw errors on invalid resource types - Changed the test for handling invalid resource types to ensure it throws an error instead of returning an empty permissions map. - Updated the expectation to check for the specific error message when an invalid resource type is provided. * feat: Implement retry logic for MCP server creation to handle race conditions - Enhanced the createMCPServer method to include retry logic with exponential backoff for handling duplicate key errors during concurrent server creation. - Updated tests to verify that all concurrent requests succeed and that unique server names are generated. - Added a helper function to identify MongoDB duplicate key errors, improving error handling during server creation. * refactor: StatusIcon to use CircleCheck for connected status - Replaced the PlugZap icon with CircleCheck in the ConnectedStatusIcon component to better represent the connected state. - Ensured consistent icon usage across the component for improved visual clarity. * test: Update AccessControlService tests to throw errors on invalid resource types - Modified the test for invalid resource types to ensure it throws an error with a specific message instead of returning an empty permissions map. - This change enhances error handling and improves test coverage for the AccessControlService. * fix: Update error message for missing server name in MCP server retrieval - Changed the error message returned when the server name is not provided from 'MCP ID is required' to 'Server name is required' for better clarity and accuracy in the API response. --------- Co-authored-by: Atef Bellaaj <slalom.bellaaj@external.daimlertruck.com> Co-authored-by: Danny Avila <danny@librechat.ai>
This commit is contained in:
parent
41c0a96d39
commit
99f8bd2ce6
103 changed files with 7978 additions and 1003 deletions
|
|
@ -1,5 +1,5 @@
|
|||
export * from './useMCPConnectionStatus';
|
||||
export * from './useMCPSelect';
|
||||
export * from './useVisibleTools';
|
||||
export { useMCPServerManager } from './useMCPServerManager';
|
||||
export * from './useMCPServerManager';
|
||||
export { useRemoveMCPTool } from './useRemoveMCPTool';
|
||||
|
|
|
|||
|
|
@ -1,11 +1,12 @@
|
|||
import { useCallback, useState, useMemo, useRef, useEffect } from 'react';
|
||||
import { useToastContext } from '@librechat/client';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { Constants, QueryKeys, MCPOptions } from 'librechat-data-provider';
|
||||
import { Constants, QueryKeys, MCPOptions, ResourceType } from 'librechat-data-provider';
|
||||
import {
|
||||
useCancelMCPOAuthMutation,
|
||||
useUpdateUserPluginsMutation,
|
||||
useReinitializeMCPServerMutation,
|
||||
useGetAllEffectivePermissionsQuery,
|
||||
} from 'librechat-data-provider/react-query';
|
||||
import type { TUpdateUserPlugins, TPlugin, MCPServersResponse } from 'librechat-data-provider';
|
||||
import type { ConfigFieldDetail } from '~/common';
|
||||
|
|
@ -15,9 +16,9 @@ import { useGetStartupConfig, useMCPServersQuery } from '~/data-provider';
|
|||
export interface MCPServerDefinition {
|
||||
serverName: string;
|
||||
config: MCPOptions;
|
||||
mcp_id?: string;
|
||||
_id?: string; // MongoDB ObjectId for database servers (used for permissions)
|
||||
dbId?: string; // MongoDB ObjectId for database servers (used for permissions)
|
||||
effectivePermissions: number; // Permission bits (VIEW=1, EDIT=2, DELETE=4, SHARE=8)
|
||||
consumeOnly?: boolean;
|
||||
}
|
||||
|
||||
interface ServerState {
|
||||
|
|
@ -36,35 +37,44 @@ export function useMCPServerManager({ conversationId }: { conversationId?: strin
|
|||
|
||||
const { data: loadedServers, isLoading } = useMCPServersQuery();
|
||||
|
||||
// Fetch effective permissions for all MCP servers
|
||||
const { data: permissionsMap } = useGetAllEffectivePermissionsQuery(ResourceType.MCPSERVER);
|
||||
|
||||
const [isConfigModalOpen, setIsConfigModalOpen] = useState(false);
|
||||
const [selectedToolForConfig, setSelectedToolForConfig] = useState<TPlugin | null>(null);
|
||||
const previousFocusRef = useRef<HTMLElement | null>(null);
|
||||
const configuredServers = useMemo(() => {
|
||||
if (!loadedServers) return [];
|
||||
return Object.keys(loadedServers).filter((name) => loadedServers[name]?.chatMenu !== false);
|
||||
}, [loadedServers]);
|
||||
|
||||
const availableMCPServers: MCPServerDefinition[] = useMemo<MCPServerDefinition[]>(() => {
|
||||
const definitions: MCPServerDefinition[] = [];
|
||||
if (loadedServers) {
|
||||
for (const [serverName, metadata] of Object.entries(loadedServers)) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const { _id, mcp_id, effectivePermissions, author, updatedAt, createdAt, ...config } =
|
||||
metadata;
|
||||
const { dbId, consumeOnly, ...config } = metadata;
|
||||
|
||||
// Get effective permissions from the permissions map using _id
|
||||
// Fall back to 1 (VIEW) for YAML-based servers without _id
|
||||
const effectivePermissions = dbId && permissionsMap?.[dbId] ? permissionsMap[dbId] : 1;
|
||||
|
||||
definitions.push({
|
||||
serverName,
|
||||
mcp_id,
|
||||
effectivePermissions: effectivePermissions || 1,
|
||||
dbId,
|
||||
effectivePermissions,
|
||||
consumeOnly,
|
||||
config,
|
||||
});
|
||||
}
|
||||
}
|
||||
return definitions;
|
||||
}, [loadedServers]);
|
||||
}, [loadedServers, permissionsMap]);
|
||||
|
||||
// Memoize filtered servers for useMCPSelect to prevent infinite loops
|
||||
const selectableServers = useMemo(
|
||||
() => availableMCPServers.filter((s) => s.config.chatMenu !== false && !s.consumeOnly),
|
||||
[availableMCPServers],
|
||||
);
|
||||
|
||||
const { mcpValues, setMCPValues, isPinned, setIsPinned } = useMCPSelect({
|
||||
conversationId,
|
||||
servers: availableMCPServers,
|
||||
servers: selectableServers,
|
||||
});
|
||||
const mcpValuesRef = useRef(mcpValues);
|
||||
|
||||
|
|
@ -73,6 +83,14 @@ export function useMCPServerManager({ conversationId }: { conversationId?: strin
|
|||
mcpValuesRef.current = mcpValues;
|
||||
}, [mcpValues]);
|
||||
|
||||
// Check if specific permission bit is set
|
||||
const checkEffectivePermission = useCallback(
|
||||
(effectivePermissions: number, permissionBit: number): boolean => {
|
||||
return (effectivePermissions & permissionBit) !== 0;
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const reinitializeMutation = useReinitializeMCPServerMutation();
|
||||
const cancelOAuthMutation = useCancelMCPOAuthMutation();
|
||||
|
||||
|
|
@ -98,8 +116,8 @@ export function useMCPServerManager({ conversationId }: { conversationId?: strin
|
|||
|
||||
const [serverStates, setServerStates] = useState<Record<string, ServerState>>(() => {
|
||||
const initialStates: Record<string, ServerState> = {};
|
||||
configuredServers.forEach((serverName) => {
|
||||
initialStates[serverName] = {
|
||||
availableMCPServers.forEach((server) => {
|
||||
initialStates[server.serverName] = {
|
||||
isInitializing: false,
|
||||
oauthUrl: null,
|
||||
oauthStartTime: null,
|
||||
|
|
@ -111,7 +129,7 @@ export function useMCPServerManager({ conversationId }: { conversationId?: strin
|
|||
});
|
||||
|
||||
const { connectionStatus } = useMCPConnectionStatus({
|
||||
enabled: !isLoading && configuredServers.length > 0,
|
||||
enabled: !isLoading && availableMCPServers.length > 0,
|
||||
});
|
||||
|
||||
const updateServerState = useCallback((serverName: string, updates: Partial<ServerState>) => {
|
||||
|
|
@ -366,7 +384,12 @@ export function useMCPServerManager({ conversationId }: { conversationId?: strin
|
|||
cancelOAuthMutation.mutate(serverName, {
|
||||
onSuccess: () => {
|
||||
cleanupServerState(serverName);
|
||||
queryClient.invalidateQueries([QueryKeys.mcpConnectionStatus]);
|
||||
Promise.all([
|
||||
queryClient.invalidateQueries([QueryKeys.mcpServers]),
|
||||
queryClient.invalidateQueries([QueryKeys.mcpTools]),
|
||||
queryClient.invalidateQueries([QueryKeys.mcpAuthValues]),
|
||||
queryClient.invalidateQueries([QueryKeys.mcpConnectionStatus]),
|
||||
]);
|
||||
|
||||
showToast({
|
||||
message: localize('com_ui_mcp_oauth_cancelled', { 0: serverName }),
|
||||
|
|
@ -629,6 +652,8 @@ export function useMCPServerManager({ conversationId }: { conversationId?: strin
|
|||
|
||||
return {
|
||||
availableMCPServers,
|
||||
/** MCP servers filtered for chat menu selection (chatMenu !== false && !consumeOnly) */
|
||||
selectableServers,
|
||||
availableMCPServersMap: loadedServers,
|
||||
isLoading,
|
||||
connectionStatus,
|
||||
|
|
@ -655,5 +680,6 @@ export function useMCPServerManager({ conversationId }: { conversationId?: strin
|
|||
handleRevoke,
|
||||
getServerStatusIconProps,
|
||||
getConfigDialogProps,
|
||||
checkEffectivePermission,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import {
|
|||
isAssistantsEndpoint,
|
||||
} from 'librechat-data-provider';
|
||||
import type { TInterfaceConfig, TEndpointsConfig } from 'librechat-data-provider';
|
||||
import MCPBuilderPanel from '~/components/SidePanel/MCPBuilder/MCPBuilderPanel';
|
||||
import type { NavLink } from '~/common';
|
||||
import AgentPanelSwitch from '~/components/SidePanel/Agents/AgentPanelSwitch';
|
||||
import BookmarkPanel from '~/components/SidePanel/Bookmarks/BookmarkPanel';
|
||||
|
|
@ -18,7 +19,6 @@ import PanelSwitch from '~/components/SidePanel/Builder/PanelSwitch';
|
|||
import PromptsAccordion from '~/components/Prompts/PromptsAccordion';
|
||||
import Parameters from '~/components/SidePanel/Parameters/Panel';
|
||||
import FilesPanel from '~/components/SidePanel/Files/Panel';
|
||||
import MCPPanel from '~/components/SidePanel/MCP/MCPPanel';
|
||||
import { useHasAccess, useMCPServerManager } from '~/hooks';
|
||||
|
||||
export default function useSideNavLinks({
|
||||
|
|
@ -60,7 +60,10 @@ export default function useSideNavLinks({
|
|||
permissionType: PermissionTypes.AGENTS,
|
||||
permission: Permissions.CREATE,
|
||||
});
|
||||
|
||||
const hasAccessToUseMCPSettings = useHasAccess({
|
||||
permissionType: PermissionTypes.MCP_SERVERS,
|
||||
permission: Permissions.USE,
|
||||
});
|
||||
const { availableMCPServers } = useMCPServerManager();
|
||||
|
||||
const Links = useMemo(() => {
|
||||
|
|
@ -152,21 +155,13 @@ export default function useSideNavLinks({
|
|||
});
|
||||
}
|
||||
|
||||
if (
|
||||
availableMCPServers &&
|
||||
availableMCPServers.some(
|
||||
(server: any) =>
|
||||
(server.config.customUserVars && Object.keys(server.config.customUserVars).length > 0) ||
|
||||
server.config.isOAuth ||
|
||||
server.config.startup === false,
|
||||
)
|
||||
) {
|
||||
if (hasAccessToUseMCPSettings && availableMCPServers && availableMCPServers.length > 0) {
|
||||
links.push({
|
||||
title: 'com_nav_setting_mcp',
|
||||
label: '',
|
||||
icon: MCPIcon,
|
||||
id: 'mcp-settings',
|
||||
Component: MCPPanel,
|
||||
id: 'mcp-builder',
|
||||
Component: MCPBuilderPanel,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -180,19 +175,20 @@ export default function useSideNavLinks({
|
|||
|
||||
return links;
|
||||
}, [
|
||||
endpointsConfig,
|
||||
interfaceConfig.parameters,
|
||||
keyProvided,
|
||||
endpointType,
|
||||
endpoint,
|
||||
endpointsConfig,
|
||||
keyProvided,
|
||||
hasAccessToAgents,
|
||||
hasAccessToCreateAgents,
|
||||
hasAccessToPrompts,
|
||||
hasAccessToMemories,
|
||||
hasAccessToReadMemories,
|
||||
interfaceConfig.parameters,
|
||||
endpointType,
|
||||
hasAccessToBookmarks,
|
||||
hasAccessToCreateAgents,
|
||||
hidePanel,
|
||||
availableMCPServers,
|
||||
hasAccessToUseMCPSettings,
|
||||
hidePanel,
|
||||
]);
|
||||
|
||||
return Links;
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import { getResourceConfig } from '~/utils';
|
|||
|
||||
/**
|
||||
* Hook to manage resource permission state including current shares, public access, and mutations
|
||||
* @param resourceType - Type of resource (e.g., ResourceType.AGENT, ResourceType.PROMPTGROUP)
|
||||
* @param resourceType - Type of resource (e.g., ResourceType.AGENT, ResourceType.PROMPTGROUP, ResourceType.MCPSERVER)
|
||||
* @param resourceDbId - Database ID of the resource
|
||||
* @param isModalOpen - Whether the modal is open (for effect dependencies)
|
||||
* @returns Object with permission state and update mutation
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue