LibreChat/client/src/hooks/MCP/useMCPServerManager.ts

683 lines
23 KiB
TypeScript
Raw Normal View History

import { useCallback, useState, useMemo, useRef, useEffect } from 'react';
🔌 refactor: MCP UI with Improved Accessibility and Reusable Components (#11118) * feat: enhance MCP server selection UI with new components and improved accessibility * fix(i18n): add missing com_ui_mcp_servers translation key The MCP server menu aria-label was referencing a non-existent translation key. Added the missing key for accessibility. * feat(MCP): enhance MCP components with improved accessibility and focus management * fix(i18n): remove outdated MCP server translation keys * fix(MCPServerList): improve color contrast by updating text color for no MCP servers message * refactor(MCP): Server status components and improve user action handling Updated MCPServerStatusIcon to use a unified icon system for better clarity Introduced new MCPCardActions component for standardized action buttons on server cards Created MCPServerCard component to encapsulate server display logic and actions Enhanced MCPServerList to render MCPServerCard components, improving code organization Added MCPStatusBadge for consistent status representation in dialogs Updated utility functions for status color and text retrieval to align with new design Improved localization keys for better clarity and consistency in user messages * style(MCP): update button and card background styles for improved UI consistency * feat(MCP): implement global server initialization state management using Jotai * refactor(MCP): modularize MCPServerDialog into structured component architecture - Split monolithic dialog into dedicated section components (Auth, BasicInfo, Connection, Transport, Trust) - Extract form logic into useMCPServerForm custom hook - Add utility modules for JSON import and URL handling - Introduce reusable SecretInput component in @librechat/client - Remove deprecated MCPAuth component * style(MCP): update button styles for improved layout and adjust empty state background color * refactor(Radio): enhance component mounting logic and background style updates * refactor(translation): remove unused keys and streamline localization strings
2025-12-28 18:20:15 +01:00
import { useAtom } from 'jotai';
📦 feat: Move Shared Components to `@librechat/client` (#8685) * feat: init @librechat/client * feat: Add common types and interfaces for accessibility, agents, artifacts, assistants, and tools * feat: Add jotai as a peer dependency * fix build client package * feat: cleanup unused types from common/index.ts - Remove 104 unused type exports from packages/client/src/common/index.ts - Keep only 7 actually used exports (93% reduction) - Add cleanup script with enhanced import pattern detection - Support both named imports and namespace imports (* as t) - Create automatic backups and comprehensive documentation - Maintain type safety with build verification - No breaking changes to existing code Kept exports: - TShowToast, Option, OptionWithIcon, DropdownValueSetter - MentionOption, NotificationSeverity, MenuItemProps Scripts: cleanup-common-types-safe.js, README-CLEANUP.md * fix: cleanup * fix: package; refactor: tsconfig * feat: add back `recoil` * fix: move dependencies to peerDependencies in client package * feat: add @librechat/client as a dependency in package.json and package-lock.json * feat: update client package configuration and dependencies - Added new dependencies for Rollup plugins and updated existing ones in package.json and package-lock.json. - Introduced a new Rollup configuration file for building the client package. - Refactored build scripts to include a dedicated build command for the client. - Updated TypeScript configuration for improved module resolution and type declaration output. - Integrated a Toast component from the client package into the main App component. * feat: enhance Rollup configuration for client package - Updated terser plugin settings to preserve directives like 'use client'. - Added custom warning handler to ignore "use client" directive warnings during the build process. * chore: rename package/client build script command * feat: update client package dependencies and Rollup configuration - Added rollup-plugin-postcss to package.json and updated package-lock.json. - Enhanced Rollup configuration to include postcss plugin for CSS handling. - Updated index.ts to export all components from the components directory for better modularity. * feat: add client package directory to update configuration - Included the 'client' package directory in the update.js configuration to ensure it is recognized during updates. * feat: export Toast component in client package - Added export for the Toast component in index.ts to enhance modularity and accessibility of components. * feat: /client transition to @librechat/client * chore: fixed formatting issues * fix: update peer dependencies in @librechat/client to prevent bundling them * fix: correct useSprings implementation in SplitText component * fix: circular dependencies in DataTable * fix: add remaining peer dependencies and match actual versions previously used in `client/package.json` * fix: correct frontend:ci script to include client package build * chore: enhance unused package detection for @librechat/client and improve dependency extraction * fix: add missing peer dependency for @radix-ui/react-collapsible * chore: include "packages/client" in unused i18next keys detection * test: update AgentFooter tests to use document.querySelector for spinner checks test: mock window.matchMedia in setupTests.js for consistent test environment * feat: add react-hook-form dependency and update FormInput component to use its types * chore: linting * refactor: remove unused defaultSelectedValues prop from MCPSelect and MultiSelect components * chore: linting * feat: update GitHub Actions workflow to publish @librechat/client * chore: update GitHub Actions workflow to install and build data-provider and client dependencies * chore: add missing @testing-library/react dependency to client package * chore: update tsconfig.json to exclude additional test files * chore: fix build issues, resolve latest LC changes * chore: move MCP components outside of `~/components/ui` * feat: implement dynamic theme system with environment variable support and Tailwind CSS integration * chore: remove unnecessary logging of sttExternal and ttsExternal in Speech component * chore: squashed cleanup commits chore: move @tanstack/react-virtual to dependencies and remove recoil from package.json chore: move dependencies to peerDependencies in package.json feat: update package.json and rollup.config.js to include jotai and enhance bundling configuration feat: update package.json and rollup.config.js to include jotai and enhance bundling configuration refactor: reorganize exports in index.ts for improved clarity refactor: remove unused types and interfaces from common files refactor: update peer dependencies and improve component typings - Removed duplicate peer dependencies from package.json and organized them. - Updated rollup.config.js to disable TypeScript checking during the build process. - Modified AnimatedTabs component to use React.ReactNode for label and content types, and added TypeScript workarounds for compatibility. - Enhanced Label and Separator components to accept an optional className prop and improved prop spreading. - Updated Slider component to include an optional className prop and refined prop handling for better type safety. refactor: clean up client workflow and update package dependencies refactor: update package dependencies and improve PostCSS and Rollup configurations chore: bump version to 0.1.2 in package.json chore: bump client version to 0.1.2 in package-lock.json chore: bump client version to 0.1.3 and update dependencies chore: bump client version to 0.1.4 and update @react-spring dependencies chore: update package version to 0.1.5 and adjust peer dependencies - Bump version in package.json from 0.1.4 to 0.1.5. - Update peer dependency for @tanstack/react-query to allow version 5.0.0. - Add @tanstack/react-table and @tanstack/react-virtual as dependencies. - Update various dependencies to their latest compatible versions. - Simplify postcss.config.js by removing unnecessary options. - Clean up rollup.config.js by removing ignored PostCSS warnings. - Update CheckboxButton component to cast icon as React JSX element. - Adjust Combobox component's class names for better styling. - Change DropdownPopup component to use React's namespace import. - Modify InputOTP component to use 'any' type for OTPInputContext. - Ensure displayLabel and value in ModelParameters are converted to strings. - Update MultiSearch component's placeholder to ensure it's a string. - Cast selectIcon in MultiSelect as React JSX element for consistency. - Update OGDialogTemplate to cast selectText as React JSX element. - Initialize animationRef in PixelCard with undefined for clarity. - Add TypeScript ignore comments in Select and SelectDropDown components for Radix UI type conflicts. - Ensure title in SelectDropDown is a string and adjust rendering of options. - Update useLocalize hook to cast options as any for compatibility. refactor: code structure; chore: translations cleanup chore: remove unused imports and clean up code in NewChat component refactor: enhance Menu component to support custom render functions for menu items style: update itemClassName in ToolsDropdown for improved UI consistency fix: merge conflicts chore: update @radix-ui/react-accordion to version 1.2.11 * refactor: remove unnecessary TypeScript type assertions in AnimatedTabs, Label, Separator, and Slider components * feat: enhance theme system with localStorage persistence and new theme atoms * chore: bump version of @librechat/client to 0.1.7 * chore: fix ci/cd warnings/errors related to linting and unused localization keys * chore: update dependencies for class-variance-authority, clsx, and match-sorter * chore: bump @librechat/client to v0.1.8 * feat: add utility colors for theme customization and remove unused tailwindConfig * v0.1.9 --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com>
2025-07-27 12:19:01 -04:00
import { useToastContext } from '@librechat/client';
import { useQueryClient } from '@tanstack/react-query';
🏗️ 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>
2025-12-04 21:37:23 +01:00
import { Constants, QueryKeys, MCPOptions, ResourceType } from 'librechat-data-provider';
import {
useCancelMCPOAuthMutation,
useUpdateUserPluginsMutation,
useReinitializeMCPServerMutation,
🏗️ 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>
2025-12-04 21:37:23 +01:00
useGetAllEffectivePermissionsQuery,
} from 'librechat-data-provider/react-query';
import type { TUpdateUserPlugins, TPlugin, MCPServersResponse } from 'librechat-data-provider';
import type { ConfigFieldDetail } from '~/common';
import { useLocalize, useMCPSelect, useMCPConnectionStatus } from '~/hooks';
import { useGetStartupConfig, useMCPServersQuery } from '~/data-provider';
🔌 refactor: MCP UI with Improved Accessibility and Reusable Components (#11118) * feat: enhance MCP server selection UI with new components and improved accessibility * fix(i18n): add missing com_ui_mcp_servers translation key The MCP server menu aria-label was referencing a non-existent translation key. Added the missing key for accessibility. * feat(MCP): enhance MCP components with improved accessibility and focus management * fix(i18n): remove outdated MCP server translation keys * fix(MCPServerList): improve color contrast by updating text color for no MCP servers message * refactor(MCP): Server status components and improve user action handling Updated MCPServerStatusIcon to use a unified icon system for better clarity Introduced new MCPCardActions component for standardized action buttons on server cards Created MCPServerCard component to encapsulate server display logic and actions Enhanced MCPServerList to render MCPServerCard components, improving code organization Added MCPStatusBadge for consistent status representation in dialogs Updated utility functions for status color and text retrieval to align with new design Improved localization keys for better clarity and consistency in user messages * style(MCP): update button and card background styles for improved UI consistency * feat(MCP): implement global server initialization state management using Jotai * refactor(MCP): modularize MCPServerDialog into structured component architecture - Split monolithic dialog into dedicated section components (Auth, BasicInfo, Connection, Transport, Trust) - Extract form logic into useMCPServerForm custom hook - Add utility modules for JSON import and URL handling - Introduce reusable SecretInput component in @librechat/client - Remove deprecated MCPAuth component * style(MCP): update button styles for improved layout and adjust empty state background color * refactor(Radio): enhance component mounting logic and background style updates * refactor(translation): remove unused keys and streamline localization strings
2025-12-28 18:20:15 +01:00
import { mcpServerInitStatesAtom, getServerInitState } from '~/store/mcp';
import type { MCPServerInitState } from '~/store/mcp';
export interface MCPServerDefinition {
serverName: string;
config: MCPOptions;
🏗️ 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>
2025-12-04 21:37:23 +01:00
dbId?: string; // MongoDB ObjectId for database servers (used for permissions)
effectivePermissions: number; // Permission bits (VIEW=1, EDIT=2, DELETE=4, SHARE=8)
🏗️ 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>
2025-12-04 21:37:23 +01:00
consumeOnly?: boolean;
}
🔌 refactor: MCP UI with Improved Accessibility and Reusable Components (#11118) * feat: enhance MCP server selection UI with new components and improved accessibility * fix(i18n): add missing com_ui_mcp_servers translation key The MCP server menu aria-label was referencing a non-existent translation key. Added the missing key for accessibility. * feat(MCP): enhance MCP components with improved accessibility and focus management * fix(i18n): remove outdated MCP server translation keys * fix(MCPServerList): improve color contrast by updating text color for no MCP servers message * refactor(MCP): Server status components and improve user action handling Updated MCPServerStatusIcon to use a unified icon system for better clarity Introduced new MCPCardActions component for standardized action buttons on server cards Created MCPServerCard component to encapsulate server display logic and actions Enhanced MCPServerList to render MCPServerCard components, improving code organization Added MCPStatusBadge for consistent status representation in dialogs Updated utility functions for status color and text retrieval to align with new design Improved localization keys for better clarity and consistency in user messages * style(MCP): update button and card background styles for improved UI consistency * feat(MCP): implement global server initialization state management using Jotai * refactor(MCP): modularize MCPServerDialog into structured component architecture - Split monolithic dialog into dedicated section components (Auth, BasicInfo, Connection, Transport, Trust) - Extract form logic into useMCPServerForm custom hook - Add utility modules for JSON import and URL handling - Introduce reusable SecretInput component in @librechat/client - Remove deprecated MCPAuth component * style(MCP): update button styles for improved layout and adjust empty state background color * refactor(Radio): enhance component mounting logic and background style updates * refactor(translation): remove unused keys and streamline localization strings
2025-12-28 18:20:15 +01:00
// Poll intervals are kept local since they're timer references that can't be serialized
// The init states (isInitializing, isCancellable, etc.) are stored in the global Jotai atom
type PollIntervals = Record<string, NodeJS.Timeout | null>;
✂️ refactor: MCP UI Separation for Agents (#9237) * refactor: MCP UI Separation for Agents (Dustin WIP) feat: separate MCPs into their own lists away from tools + actions and add the status indicator functionality from chat to their dropdown ui fix: spotify mcp was not persisting on agent creation feat: show disconnected saved servers and their tools in agent mcp list in created agents fix: select-all regression fixed (caused by deleting tools we were drawing from for rendering list) fix: dont show all mcps, only those installed in agent in list feat: separate ToolSelectDialog for MCPServerTools fix: uninitialized mcp servers not showing as added in toolselectdialog refactor: reduce looping in AgentPanelContext for categorizing groups and mcps refactor: split ToolSelectDialog and MCPToolSelectDialog functionality (still needs customization for custom user vars) chore: address ESLint comments chore: address ESLint comments feat: one-click initialization on MCP servers in agent builder fix: stop propagation triggering reinit on caret click refactor: split uninitialized MCPs component from initialized MCPs feat: new mcp tool select dialog ui with custom user vars feat: show initialization state for CUV configurable MCPs too chore: remove unused localization string fix: deselecting all tools caused a re-render fix: remove subtools so removal from MCPToolSelectDialog works more consistently feat: added servers have all tools enabled by default feat: mcp server list now alphabetical to prevent annoying ui behavior of servers jumping around depending on tool selection fix: filter out placeholder group mcp tools from any actual tool calls / definitions feat: indicator now takes you to config dialog for uninitialized servers feat: show previously configured mcp servers that are now missing from the yaml feat: select all enabled by default on first add to mcp server list chore: address ESLint comments * refactor: MCP UI Separation for Agents (Danny WIP) chore: remove use of `{serverName}_mcp_{serverName}` chore: import order WIP: separate component concerns refactor: streamline agent mcp tools refactor: unify MCP server handling and improve tool visibility logic, remove unnecessary normalization or sorting, remove nesting button, make variable names clear refactor: rename mcpServerIds to mcpServerNames for clarity and consistency across components refactor: remove groupedMCPTools and toolToServerMap, streamline MCP server handling in context and components to effectively utilize mcpServersMap refactor: optimize tool selection logic by replacing array includes with Set for improved performance chore: add error logging for failed auth URL parsing in ToolCall component refactor: enhance MCP tool handling by improving server name management and updating UI elements for better clarity * refactor: decouple connection status from useMCPServerManager with useMCPConnectionStatus * fix: improve MCP tool validation logic to handle unconfigured servers * chore: enhance log message clarity for MCP server disconnection in updateUserPluginsController * refactor: simplify connection status extraction in useMCPConnectionStatus hook * refactor: improve initializing UX * chore: replace string literal with ResourceType constant in useResourcePermissions * refactor: cleanup code, remove redundancies, rename variables for clarity * chore: add back filtering and sorting for mcp tools dialog * refactor: initializeServer to return response and early return * refactor: enhance server initialization logic and improve UI for OAuth interaction * chore: clarify warning message for unconfigured MCP server in handleTools * refactor: prevent CustomUserVarsSection from submitting tools dialog form * fix: nested button of button issue in UninitializedMCPTool * feat: add functionality to revoke custom user variables in MCPToolSelectDialog --------- Co-authored-by: Danny Avila <danny@librechat.ai>
2025-08-29 19:57:01 -07:00
export function useMCPServerManager({ conversationId }: { conversationId?: string | null } = {}) {
const localize = useLocalize();
const queryClient = useQueryClient();
const { showToast } = useToastContext();
const { data: startupConfig } = useGetStartupConfig(); // Keep for UI config only
const { data: loadedServers, isLoading } = useMCPServersQuery();
🏗️ 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>
2025-12-04 21:37:23 +01:00
// 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 availableMCPServers: MCPServerDefinition[] = useMemo<MCPServerDefinition[]>(() => {
const definitions: MCPServerDefinition[] = [];
if (loadedServers) {
for (const [serverName, metadata] of Object.entries(loadedServers)) {
🏗️ 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>
2025-12-04 21:37:23 +01:00
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,
🏗️ 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>
2025-12-04 21:37:23 +01:00
dbId,
effectivePermissions,
consumeOnly,
config,
});
}
}
return definitions;
🏗️ 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>
2025-12-04 21:37:23 +01:00
}, [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,
🏗️ 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>
2025-12-04 21:37:23 +01:00
servers: selectableServers,
});
const mcpValuesRef = useRef(mcpValues);
// fixes the issue where OAuth flows would deselect all the servers except the one that is being authenticated on success
useEffect(() => {
mcpValuesRef.current = mcpValues;
}, [mcpValues]);
🏗️ 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>
2025-12-04 21:37:23 +01:00
// 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();
const updateUserPluginsMutation = useUpdateUserPluginsMutation({
onSuccess: async () => {
showToast({ message: localize('com_nav_mcp_vars_updated'), status: 'success' });
await Promise.all([
queryClient.invalidateQueries([QueryKeys.mcpServers]),
queryClient.invalidateQueries([QueryKeys.mcpTools]),
queryClient.invalidateQueries([QueryKeys.mcpAuthValues]),
queryClient.invalidateQueries([QueryKeys.mcpConnectionStatus]),
]);
},
onError: (error: unknown) => {
console.error('Error updating MCP auth:', error);
showToast({
message: localize('com_nav_mcp_vars_update_error'),
status: 'error',
});
},
});
🔌 refactor: MCP UI with Improved Accessibility and Reusable Components (#11118) * feat: enhance MCP server selection UI with new components and improved accessibility * fix(i18n): add missing com_ui_mcp_servers translation key The MCP server menu aria-label was referencing a non-existent translation key. Added the missing key for accessibility. * feat(MCP): enhance MCP components with improved accessibility and focus management * fix(i18n): remove outdated MCP server translation keys * fix(MCPServerList): improve color contrast by updating text color for no MCP servers message * refactor(MCP): Server status components and improve user action handling Updated MCPServerStatusIcon to use a unified icon system for better clarity Introduced new MCPCardActions component for standardized action buttons on server cards Created MCPServerCard component to encapsulate server display logic and actions Enhanced MCPServerList to render MCPServerCard components, improving code organization Added MCPStatusBadge for consistent status representation in dialogs Updated utility functions for status color and text retrieval to align with new design Improved localization keys for better clarity and consistency in user messages * style(MCP): update button and card background styles for improved UI consistency * feat(MCP): implement global server initialization state management using Jotai * refactor(MCP): modularize MCPServerDialog into structured component architecture - Split monolithic dialog into dedicated section components (Auth, BasicInfo, Connection, Transport, Trust) - Extract form logic into useMCPServerForm custom hook - Add utility modules for JSON import and URL handling - Introduce reusable SecretInput component in @librechat/client - Remove deprecated MCPAuth component * style(MCP): update button styles for improved layout and adjust empty state background color * refactor(Radio): enhance component mounting logic and background style updates * refactor(translation): remove unused keys and streamline localization strings
2025-12-28 18:20:15 +01:00
// Global atom for init states - shared across all useMCPServerManager instances
// This enables canceling OAuth from both chat dropdown and settings panel
const [serverInitStates, setServerInitStates] = useAtom(mcpServerInitStatesAtom);
// Poll intervals are kept local (not serializable)
const pollIntervalsRef = useRef<PollIntervals>({});
✂️ refactor: MCP UI Separation for Agents (#9237) * refactor: MCP UI Separation for Agents (Dustin WIP) feat: separate MCPs into their own lists away from tools + actions and add the status indicator functionality from chat to their dropdown ui fix: spotify mcp was not persisting on agent creation feat: show disconnected saved servers and their tools in agent mcp list in created agents fix: select-all regression fixed (caused by deleting tools we were drawing from for rendering list) fix: dont show all mcps, only those installed in agent in list feat: separate ToolSelectDialog for MCPServerTools fix: uninitialized mcp servers not showing as added in toolselectdialog refactor: reduce looping in AgentPanelContext for categorizing groups and mcps refactor: split ToolSelectDialog and MCPToolSelectDialog functionality (still needs customization for custom user vars) chore: address ESLint comments chore: address ESLint comments feat: one-click initialization on MCP servers in agent builder fix: stop propagation triggering reinit on caret click refactor: split uninitialized MCPs component from initialized MCPs feat: new mcp tool select dialog ui with custom user vars feat: show initialization state for CUV configurable MCPs too chore: remove unused localization string fix: deselecting all tools caused a re-render fix: remove subtools so removal from MCPToolSelectDialog works more consistently feat: added servers have all tools enabled by default feat: mcp server list now alphabetical to prevent annoying ui behavior of servers jumping around depending on tool selection fix: filter out placeholder group mcp tools from any actual tool calls / definitions feat: indicator now takes you to config dialog for uninitialized servers feat: show previously configured mcp servers that are now missing from the yaml feat: select all enabled by default on first add to mcp server list chore: address ESLint comments * refactor: MCP UI Separation for Agents (Danny WIP) chore: remove use of `{serverName}_mcp_{serverName}` chore: import order WIP: separate component concerns refactor: streamline agent mcp tools refactor: unify MCP server handling and improve tool visibility logic, remove unnecessary normalization or sorting, remove nesting button, make variable names clear refactor: rename mcpServerIds to mcpServerNames for clarity and consistency across components refactor: remove groupedMCPTools and toolToServerMap, streamline MCP server handling in context and components to effectively utilize mcpServersMap refactor: optimize tool selection logic by replacing array includes with Set for improved performance chore: add error logging for failed auth URL parsing in ToolCall component refactor: enhance MCP tool handling by improving server name management and updating UI elements for better clarity * refactor: decouple connection status from useMCPServerManager with useMCPConnectionStatus * fix: improve MCP tool validation logic to handle unconfigured servers * chore: enhance log message clarity for MCP server disconnection in updateUserPluginsController * refactor: simplify connection status extraction in useMCPConnectionStatus hook * refactor: improve initializing UX * chore: replace string literal with ResourceType constant in useResourcePermissions * refactor: cleanup code, remove redundancies, rename variables for clarity * chore: add back filtering and sorting for mcp tools dialog * refactor: initializeServer to return response and early return * refactor: enhance server initialization logic and improve UI for OAuth interaction * chore: clarify warning message for unconfigured MCP server in handleTools * refactor: prevent CustomUserVarsSection from submitting tools dialog form * fix: nested button of button issue in UninitializedMCPTool * feat: add functionality to revoke custom user variables in MCPToolSelectDialog --------- Co-authored-by: Danny Avila <danny@librechat.ai>
2025-08-29 19:57:01 -07:00
const { connectionStatus } = useMCPConnectionStatus({
🏗️ 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>
2025-12-04 21:37:23 +01:00
enabled: !isLoading && availableMCPServers.length > 0,
});
🔌 refactor: MCP UI with Improved Accessibility and Reusable Components (#11118) * feat: enhance MCP server selection UI with new components and improved accessibility * fix(i18n): add missing com_ui_mcp_servers translation key The MCP server menu aria-label was referencing a non-existent translation key. Added the missing key for accessibility. * feat(MCP): enhance MCP components with improved accessibility and focus management * fix(i18n): remove outdated MCP server translation keys * fix(MCPServerList): improve color contrast by updating text color for no MCP servers message * refactor(MCP): Server status components and improve user action handling Updated MCPServerStatusIcon to use a unified icon system for better clarity Introduced new MCPCardActions component for standardized action buttons on server cards Created MCPServerCard component to encapsulate server display logic and actions Enhanced MCPServerList to render MCPServerCard components, improving code organization Added MCPStatusBadge for consistent status representation in dialogs Updated utility functions for status color and text retrieval to align with new design Improved localization keys for better clarity and consistency in user messages * style(MCP): update button and card background styles for improved UI consistency * feat(MCP): implement global server initialization state management using Jotai * refactor(MCP): modularize MCPServerDialog into structured component architecture - Split monolithic dialog into dedicated section components (Auth, BasicInfo, Connection, Transport, Trust) - Extract form logic into useMCPServerForm custom hook - Add utility modules for JSON import and URL handling - Introduce reusable SecretInput component in @librechat/client - Remove deprecated MCPAuth component * style(MCP): update button styles for improved layout and adjust empty state background color * refactor(Radio): enhance component mounting logic and background style updates * refactor(translation): remove unused keys and streamline localization strings
2025-12-28 18:20:15 +01:00
const updateServerInitState = useCallback(
(serverName: string, updates: Partial<MCPServerInitState>) => {
setServerInitStates((prev) => {
const currentState = getServerInitState(prev, serverName);
return {
...prev,
[serverName]: { ...currentState, ...updates },
};
});
},
[setServerInitStates],
);
const cleanupServerState = useCallback(
(serverName: string) => {
🔌 refactor: MCP UI with Improved Accessibility and Reusable Components (#11118) * feat: enhance MCP server selection UI with new components and improved accessibility * fix(i18n): add missing com_ui_mcp_servers translation key The MCP server menu aria-label was referencing a non-existent translation key. Added the missing key for accessibility. * feat(MCP): enhance MCP components with improved accessibility and focus management * fix(i18n): remove outdated MCP server translation keys * fix(MCPServerList): improve color contrast by updating text color for no MCP servers message * refactor(MCP): Server status components and improve user action handling Updated MCPServerStatusIcon to use a unified icon system for better clarity Introduced new MCPCardActions component for standardized action buttons on server cards Created MCPServerCard component to encapsulate server display logic and actions Enhanced MCPServerList to render MCPServerCard components, improving code organization Added MCPStatusBadge for consistent status representation in dialogs Updated utility functions for status color and text retrieval to align with new design Improved localization keys for better clarity and consistency in user messages * style(MCP): update button and card background styles for improved UI consistency * feat(MCP): implement global server initialization state management using Jotai * refactor(MCP): modularize MCPServerDialog into structured component architecture - Split monolithic dialog into dedicated section components (Auth, BasicInfo, Connection, Transport, Trust) - Extract form logic into useMCPServerForm custom hook - Add utility modules for JSON import and URL handling - Introduce reusable SecretInput component in @librechat/client - Remove deprecated MCPAuth component * style(MCP): update button styles for improved layout and adjust empty state background color * refactor(Radio): enhance component mounting logic and background style updates * refactor(translation): remove unused keys and streamline localization strings
2025-12-28 18:20:15 +01:00
// Clear local poll interval
const pollInterval = pollIntervalsRef.current[serverName];
if (pollInterval) {
clearTimeout(pollInterval);
pollIntervalsRef.current[serverName] = null;
}
🔌 refactor: MCP UI with Improved Accessibility and Reusable Components (#11118) * feat: enhance MCP server selection UI with new components and improved accessibility * fix(i18n): add missing com_ui_mcp_servers translation key The MCP server menu aria-label was referencing a non-existent translation key. Added the missing key for accessibility. * feat(MCP): enhance MCP components with improved accessibility and focus management * fix(i18n): remove outdated MCP server translation keys * fix(MCPServerList): improve color contrast by updating text color for no MCP servers message * refactor(MCP): Server status components and improve user action handling Updated MCPServerStatusIcon to use a unified icon system for better clarity Introduced new MCPCardActions component for standardized action buttons on server cards Created MCPServerCard component to encapsulate server display logic and actions Enhanced MCPServerList to render MCPServerCard components, improving code organization Added MCPStatusBadge for consistent status representation in dialogs Updated utility functions for status color and text retrieval to align with new design Improved localization keys for better clarity and consistency in user messages * style(MCP): update button and card background styles for improved UI consistency * feat(MCP): implement global server initialization state management using Jotai * refactor(MCP): modularize MCPServerDialog into structured component architecture - Split monolithic dialog into dedicated section components (Auth, BasicInfo, Connection, Transport, Trust) - Extract form logic into useMCPServerForm custom hook - Add utility modules for JSON import and URL handling - Introduce reusable SecretInput component in @librechat/client - Remove deprecated MCPAuth component * style(MCP): update button styles for improved layout and adjust empty state background color * refactor(Radio): enhance component mounting logic and background style updates * refactor(translation): remove unused keys and streamline localization strings
2025-12-28 18:20:15 +01:00
// Reset global init state
updateServerInitState(serverName, {
isInitializing: false,
oauthUrl: null,
oauthStartTime: null,
isCancellable: false,
});
},
🔌 refactor: MCP UI with Improved Accessibility and Reusable Components (#11118) * feat: enhance MCP server selection UI with new components and improved accessibility * fix(i18n): add missing com_ui_mcp_servers translation key The MCP server menu aria-label was referencing a non-existent translation key. Added the missing key for accessibility. * feat(MCP): enhance MCP components with improved accessibility and focus management * fix(i18n): remove outdated MCP server translation keys * fix(MCPServerList): improve color contrast by updating text color for no MCP servers message * refactor(MCP): Server status components and improve user action handling Updated MCPServerStatusIcon to use a unified icon system for better clarity Introduced new MCPCardActions component for standardized action buttons on server cards Created MCPServerCard component to encapsulate server display logic and actions Enhanced MCPServerList to render MCPServerCard components, improving code organization Added MCPStatusBadge for consistent status representation in dialogs Updated utility functions for status color and text retrieval to align with new design Improved localization keys for better clarity and consistency in user messages * style(MCP): update button and card background styles for improved UI consistency * feat(MCP): implement global server initialization state management using Jotai * refactor(MCP): modularize MCPServerDialog into structured component architecture - Split monolithic dialog into dedicated section components (Auth, BasicInfo, Connection, Transport, Trust) - Extract form logic into useMCPServerForm custom hook - Add utility modules for JSON import and URL handling - Introduce reusable SecretInput component in @librechat/client - Remove deprecated MCPAuth component * style(MCP): update button styles for improved layout and adjust empty state background color * refactor(Radio): enhance component mounting logic and background style updates * refactor(translation): remove unused keys and streamline localization strings
2025-12-28 18:20:15 +01:00
[updateServerInitState],
);
const startServerPolling = useCallback(
(serverName: string) => {
⏳ refactor: MCP OAuth Polling with Gradual Backoff and Timeout Handling (#9752) * refactor: Implement gradual backoff polling for oauth connection status with timeout handling * refactor: Enhance OAuth polling with gradual backoff and timeout handling; update reconnection tracking * refactor: reconnection timeout behavior in OAuthReconnectionManager and OAuthReconnectionTracker - Implement tests to verify reconnection timeout handling, including tracking of reconnection states and cleanup of timed-out entries. - Enhance existing methods in OAuthReconnectionManager and OAuthReconnectionTracker to support timeout checks and cleanup logic. - Ensure proper handling of multiple servers with different timeout periods and edge cases for active states. * chore: remove comment * refactor: Enforce strict 3-minute OAuth timeout with updated polling intervals and improved timeout handling * refactor: Remove unused polling logic and prevent duplicate polling for servers in MCP server manager * refactor: Update localization key for no memories message in MemoryViewer * refactor: Improve MCP tool initialization by handling server failures - Introduced a mechanism to track failed MCP servers, preventing retries for unavailable servers. - Added logging for failed tool creation attempts to enhance debugging and monitoring. * refactor: Update reconnection timeout to enforce a strict 3-minute limit * ci: Update reconnection timeout tests to reflect a strict 3-minute limit * ci: Update reconnection timeout tests to enforce a strict 3-minute limit * chore: Remove unused MCP connection timeout message
2025-09-21 22:58:19 -04:00
// Prevent duplicate polling for the same server
🔌 refactor: MCP UI with Improved Accessibility and Reusable Components (#11118) * feat: enhance MCP server selection UI with new components and improved accessibility * fix(i18n): add missing com_ui_mcp_servers translation key The MCP server menu aria-label was referencing a non-existent translation key. Added the missing key for accessibility. * feat(MCP): enhance MCP components with improved accessibility and focus management * fix(i18n): remove outdated MCP server translation keys * fix(MCPServerList): improve color contrast by updating text color for no MCP servers message * refactor(MCP): Server status components and improve user action handling Updated MCPServerStatusIcon to use a unified icon system for better clarity Introduced new MCPCardActions component for standardized action buttons on server cards Created MCPServerCard component to encapsulate server display logic and actions Enhanced MCPServerList to render MCPServerCard components, improving code organization Added MCPStatusBadge for consistent status representation in dialogs Updated utility functions for status color and text retrieval to align with new design Improved localization keys for better clarity and consistency in user messages * style(MCP): update button and card background styles for improved UI consistency * feat(MCP): implement global server initialization state management using Jotai * refactor(MCP): modularize MCPServerDialog into structured component architecture - Split monolithic dialog into dedicated section components (Auth, BasicInfo, Connection, Transport, Trust) - Extract form logic into useMCPServerForm custom hook - Add utility modules for JSON import and URL handling - Introduce reusable SecretInput component in @librechat/client - Remove deprecated MCPAuth component * style(MCP): update button styles for improved layout and adjust empty state background color * refactor(Radio): enhance component mounting logic and background style updates * refactor(translation): remove unused keys and streamline localization strings
2025-12-28 18:20:15 +01:00
if (pollIntervalsRef.current[serverName]) {
⏳ refactor: MCP OAuth Polling with Gradual Backoff and Timeout Handling (#9752) * refactor: Implement gradual backoff polling for oauth connection status with timeout handling * refactor: Enhance OAuth polling with gradual backoff and timeout handling; update reconnection tracking * refactor: reconnection timeout behavior in OAuthReconnectionManager and OAuthReconnectionTracker - Implement tests to verify reconnection timeout handling, including tracking of reconnection states and cleanup of timed-out entries. - Enhance existing methods in OAuthReconnectionManager and OAuthReconnectionTracker to support timeout checks and cleanup logic. - Ensure proper handling of multiple servers with different timeout periods and edge cases for active states. * chore: remove comment * refactor: Enforce strict 3-minute OAuth timeout with updated polling intervals and improved timeout handling * refactor: Remove unused polling logic and prevent duplicate polling for servers in MCP server manager * refactor: Update localization key for no memories message in MemoryViewer * refactor: Improve MCP tool initialization by handling server failures - Introduced a mechanism to track failed MCP servers, preventing retries for unavailable servers. - Added logging for failed tool creation attempts to enhance debugging and monitoring. * refactor: Update reconnection timeout to enforce a strict 3-minute limit * ci: Update reconnection timeout tests to reflect a strict 3-minute limit * ci: Update reconnection timeout tests to enforce a strict 3-minute limit * chore: Remove unused MCP connection timeout message
2025-09-21 22:58:19 -04:00
console.debug(`[MCP Manager] Polling already active for ${serverName}, skipping duplicate`);
return;
}
let pollAttempts = 0;
let timeoutId: NodeJS.Timeout | null = null;
/** OAuth typically completes in 5 seconds to 3 minutes
* We enforce a strict 3-minute timeout with gradual backoff
*/
const getPollInterval = (attempt: number): number => {
if (attempt < 12) return 5000; // First minute: every 5s (12 polls)
if (attempt < 22) return 6000; // Second minute: every 6s (10 polls)
return 7500; // Final minute: every 7.5s (8 polls)
};
const maxAttempts = 30; // Exactly 3 minutes (180 seconds) total
const OAUTH_TIMEOUT_MS = 180000; // 3 minutes in milliseconds
const pollOnce = async () => {
try {
⏳ refactor: MCP OAuth Polling with Gradual Backoff and Timeout Handling (#9752) * refactor: Implement gradual backoff polling for oauth connection status with timeout handling * refactor: Enhance OAuth polling with gradual backoff and timeout handling; update reconnection tracking * refactor: reconnection timeout behavior in OAuthReconnectionManager and OAuthReconnectionTracker - Implement tests to verify reconnection timeout handling, including tracking of reconnection states and cleanup of timed-out entries. - Enhance existing methods in OAuthReconnectionManager and OAuthReconnectionTracker to support timeout checks and cleanup logic. - Ensure proper handling of multiple servers with different timeout periods and edge cases for active states. * chore: remove comment * refactor: Enforce strict 3-minute OAuth timeout with updated polling intervals and improved timeout handling * refactor: Remove unused polling logic and prevent duplicate polling for servers in MCP server manager * refactor: Update localization key for no memories message in MemoryViewer * refactor: Improve MCP tool initialization by handling server failures - Introduced a mechanism to track failed MCP servers, preventing retries for unavailable servers. - Added logging for failed tool creation attempts to enhance debugging and monitoring. * refactor: Update reconnection timeout to enforce a strict 3-minute limit * ci: Update reconnection timeout tests to reflect a strict 3-minute limit * ci: Update reconnection timeout tests to enforce a strict 3-minute limit * chore: Remove unused MCP connection timeout message
2025-09-21 22:58:19 -04:00
pollAttempts++;
🔌 refactor: MCP UI with Improved Accessibility and Reusable Components (#11118) * feat: enhance MCP server selection UI with new components and improved accessibility * fix(i18n): add missing com_ui_mcp_servers translation key The MCP server menu aria-label was referencing a non-existent translation key. Added the missing key for accessibility. * feat(MCP): enhance MCP components with improved accessibility and focus management * fix(i18n): remove outdated MCP server translation keys * fix(MCPServerList): improve color contrast by updating text color for no MCP servers message * refactor(MCP): Server status components and improve user action handling Updated MCPServerStatusIcon to use a unified icon system for better clarity Introduced new MCPCardActions component for standardized action buttons on server cards Created MCPServerCard component to encapsulate server display logic and actions Enhanced MCPServerList to render MCPServerCard components, improving code organization Added MCPStatusBadge for consistent status representation in dialogs Updated utility functions for status color and text retrieval to align with new design Improved localization keys for better clarity and consistency in user messages * style(MCP): update button and card background styles for improved UI consistency * feat(MCP): implement global server initialization state management using Jotai * refactor(MCP): modularize MCPServerDialog into structured component architecture - Split monolithic dialog into dedicated section components (Auth, BasicInfo, Connection, Transport, Trust) - Extract form logic into useMCPServerForm custom hook - Add utility modules for JSON import and URL handling - Introduce reusable SecretInput component in @librechat/client - Remove deprecated MCPAuth component * style(MCP): update button styles for improved layout and adjust empty state background color * refactor(Radio): enhance component mounting logic and background style updates * refactor(translation): remove unused keys and streamline localization strings
2025-12-28 18:20:15 +01:00
const state = getServerInitState(serverInitStates, serverName);
⏳ refactor: MCP OAuth Polling with Gradual Backoff and Timeout Handling (#9752) * refactor: Implement gradual backoff polling for oauth connection status with timeout handling * refactor: Enhance OAuth polling with gradual backoff and timeout handling; update reconnection tracking * refactor: reconnection timeout behavior in OAuthReconnectionManager and OAuthReconnectionTracker - Implement tests to verify reconnection timeout handling, including tracking of reconnection states and cleanup of timed-out entries. - Enhance existing methods in OAuthReconnectionManager and OAuthReconnectionTracker to support timeout checks and cleanup logic. - Ensure proper handling of multiple servers with different timeout periods and edge cases for active states. * chore: remove comment * refactor: Enforce strict 3-minute OAuth timeout with updated polling intervals and improved timeout handling * refactor: Remove unused polling logic and prevent duplicate polling for servers in MCP server manager * refactor: Update localization key for no memories message in MemoryViewer * refactor: Improve MCP tool initialization by handling server failures - Introduced a mechanism to track failed MCP servers, preventing retries for unavailable servers. - Added logging for failed tool creation attempts to enhance debugging and monitoring. * refactor: Update reconnection timeout to enforce a strict 3-minute limit * ci: Update reconnection timeout tests to reflect a strict 3-minute limit * ci: Update reconnection timeout tests to enforce a strict 3-minute limit * chore: Remove unused MCP connection timeout message
2025-09-21 22:58:19 -04:00
/** Stop polling after 3 minutes or max attempts */
const elapsedTime = state?.oauthStartTime
? Date.now() - state.oauthStartTime
: pollAttempts * 5000; // Rough estimate if no start time
if (pollAttempts > maxAttempts || elapsedTime > OAUTH_TIMEOUT_MS) {
console.warn(
`[MCP Manager] OAuth timeout for ${serverName} after ${(elapsedTime / 1000).toFixed(0)}s (attempt ${pollAttempts})`,
);
showToast({
message: localize('com_ui_mcp_oauth_timeout', { 0: serverName }),
status: 'error',
});
if (timeoutId) {
clearTimeout(timeoutId);
}
cleanupServerState(serverName);
return;
}
await queryClient.refetchQueries([QueryKeys.mcpConnectionStatus]);
const freshConnectionData = queryClient.getQueryData([
QueryKeys.mcpConnectionStatus,
]) as any;
const freshConnectionStatus = freshConnectionData?.connectionStatus || {};
const serverStatus = freshConnectionStatus[serverName];
if (serverStatus?.connectionState === 'connected') {
⏳ refactor: MCP OAuth Polling with Gradual Backoff and Timeout Handling (#9752) * refactor: Implement gradual backoff polling for oauth connection status with timeout handling * refactor: Enhance OAuth polling with gradual backoff and timeout handling; update reconnection tracking * refactor: reconnection timeout behavior in OAuthReconnectionManager and OAuthReconnectionTracker - Implement tests to verify reconnection timeout handling, including tracking of reconnection states and cleanup of timed-out entries. - Enhance existing methods in OAuthReconnectionManager and OAuthReconnectionTracker to support timeout checks and cleanup logic. - Ensure proper handling of multiple servers with different timeout periods and edge cases for active states. * chore: remove comment * refactor: Enforce strict 3-minute OAuth timeout with updated polling intervals and improved timeout handling * refactor: Remove unused polling logic and prevent duplicate polling for servers in MCP server manager * refactor: Update localization key for no memories message in MemoryViewer * refactor: Improve MCP tool initialization by handling server failures - Introduced a mechanism to track failed MCP servers, preventing retries for unavailable servers. - Added logging for failed tool creation attempts to enhance debugging and monitoring. * refactor: Update reconnection timeout to enforce a strict 3-minute limit * ci: Update reconnection timeout tests to reflect a strict 3-minute limit * ci: Update reconnection timeout tests to enforce a strict 3-minute limit * chore: Remove unused MCP connection timeout message
2025-09-21 22:58:19 -04:00
if (timeoutId) {
clearTimeout(timeoutId);
}
showToast({
message: localize('com_ui_mcp_authenticated_success', { 0: serverName }),
status: 'success',
});
const currentValues = mcpValuesRef.current ?? [];
if (!currentValues.includes(serverName)) {
setMCPValues([...currentValues, serverName]);
}
await queryClient.invalidateQueries([QueryKeys.mcpTools]);
// This delay is to ensure UI has updated with new connection status before cleanup
// Otherwise servers will show as disconnected for a second after OAuth flow completes
setTimeout(() => {
cleanupServerState(serverName);
}, 1000);
return;
}
⏳ refactor: MCP OAuth Polling with Gradual Backoff and Timeout Handling (#9752) * refactor: Implement gradual backoff polling for oauth connection status with timeout handling * refactor: Enhance OAuth polling with gradual backoff and timeout handling; update reconnection tracking * refactor: reconnection timeout behavior in OAuthReconnectionManager and OAuthReconnectionTracker - Implement tests to verify reconnection timeout handling, including tracking of reconnection states and cleanup of timed-out entries. - Enhance existing methods in OAuthReconnectionManager and OAuthReconnectionTracker to support timeout checks and cleanup logic. - Ensure proper handling of multiple servers with different timeout periods and edge cases for active states. * chore: remove comment * refactor: Enforce strict 3-minute OAuth timeout with updated polling intervals and improved timeout handling * refactor: Remove unused polling logic and prevent duplicate polling for servers in MCP server manager * refactor: Update localization key for no memories message in MemoryViewer * refactor: Improve MCP tool initialization by handling server failures - Introduced a mechanism to track failed MCP servers, preventing retries for unavailable servers. - Added logging for failed tool creation attempts to enhance debugging and monitoring. * refactor: Update reconnection timeout to enforce a strict 3-minute limit * ci: Update reconnection timeout tests to reflect a strict 3-minute limit * ci: Update reconnection timeout tests to enforce a strict 3-minute limit * chore: Remove unused MCP connection timeout message
2025-09-21 22:58:19 -04:00
// Check for OAuth timeout (should align with maxAttempts)
if (state?.oauthStartTime && Date.now() - state.oauthStartTime > OAUTH_TIMEOUT_MS) {
showToast({
message: localize('com_ui_mcp_oauth_timeout', { 0: serverName }),
status: 'error',
});
⏳ refactor: MCP OAuth Polling with Gradual Backoff and Timeout Handling (#9752) * refactor: Implement gradual backoff polling for oauth connection status with timeout handling * refactor: Enhance OAuth polling with gradual backoff and timeout handling; update reconnection tracking * refactor: reconnection timeout behavior in OAuthReconnectionManager and OAuthReconnectionTracker - Implement tests to verify reconnection timeout handling, including tracking of reconnection states and cleanup of timed-out entries. - Enhance existing methods in OAuthReconnectionManager and OAuthReconnectionTracker to support timeout checks and cleanup logic. - Ensure proper handling of multiple servers with different timeout periods and edge cases for active states. * chore: remove comment * refactor: Enforce strict 3-minute OAuth timeout with updated polling intervals and improved timeout handling * refactor: Remove unused polling logic and prevent duplicate polling for servers in MCP server manager * refactor: Update localization key for no memories message in MemoryViewer * refactor: Improve MCP tool initialization by handling server failures - Introduced a mechanism to track failed MCP servers, preventing retries for unavailable servers. - Added logging for failed tool creation attempts to enhance debugging and monitoring. * refactor: Update reconnection timeout to enforce a strict 3-minute limit * ci: Update reconnection timeout tests to reflect a strict 3-minute limit * ci: Update reconnection timeout tests to enforce a strict 3-minute limit * chore: Remove unused MCP connection timeout message
2025-09-21 22:58:19 -04:00
if (timeoutId) {
clearTimeout(timeoutId);
}
cleanupServerState(serverName);
return;
}
if (serverStatus?.connectionState === 'error') {
showToast({
message: localize('com_ui_mcp_init_failed'),
status: 'error',
});
⏳ refactor: MCP OAuth Polling with Gradual Backoff and Timeout Handling (#9752) * refactor: Implement gradual backoff polling for oauth connection status with timeout handling * refactor: Enhance OAuth polling with gradual backoff and timeout handling; update reconnection tracking * refactor: reconnection timeout behavior in OAuthReconnectionManager and OAuthReconnectionTracker - Implement tests to verify reconnection timeout handling, including tracking of reconnection states and cleanup of timed-out entries. - Enhance existing methods in OAuthReconnectionManager and OAuthReconnectionTracker to support timeout checks and cleanup logic. - Ensure proper handling of multiple servers with different timeout periods and edge cases for active states. * chore: remove comment * refactor: Enforce strict 3-minute OAuth timeout with updated polling intervals and improved timeout handling * refactor: Remove unused polling logic and prevent duplicate polling for servers in MCP server manager * refactor: Update localization key for no memories message in MemoryViewer * refactor: Improve MCP tool initialization by handling server failures - Introduced a mechanism to track failed MCP servers, preventing retries for unavailable servers. - Added logging for failed tool creation attempts to enhance debugging and monitoring. * refactor: Update reconnection timeout to enforce a strict 3-minute limit * ci: Update reconnection timeout tests to reflect a strict 3-minute limit * ci: Update reconnection timeout tests to enforce a strict 3-minute limit * chore: Remove unused MCP connection timeout message
2025-09-21 22:58:19 -04:00
if (timeoutId) {
clearTimeout(timeoutId);
}
cleanupServerState(serverName);
return;
}
⏳ refactor: MCP OAuth Polling with Gradual Backoff and Timeout Handling (#9752) * refactor: Implement gradual backoff polling for oauth connection status with timeout handling * refactor: Enhance OAuth polling with gradual backoff and timeout handling; update reconnection tracking * refactor: reconnection timeout behavior in OAuthReconnectionManager and OAuthReconnectionTracker - Implement tests to verify reconnection timeout handling, including tracking of reconnection states and cleanup of timed-out entries. - Enhance existing methods in OAuthReconnectionManager and OAuthReconnectionTracker to support timeout checks and cleanup logic. - Ensure proper handling of multiple servers with different timeout periods and edge cases for active states. * chore: remove comment * refactor: Enforce strict 3-minute OAuth timeout with updated polling intervals and improved timeout handling * refactor: Remove unused polling logic and prevent duplicate polling for servers in MCP server manager * refactor: Update localization key for no memories message in MemoryViewer * refactor: Improve MCP tool initialization by handling server failures - Introduced a mechanism to track failed MCP servers, preventing retries for unavailable servers. - Added logging for failed tool creation attempts to enhance debugging and monitoring. * refactor: Update reconnection timeout to enforce a strict 3-minute limit * ci: Update reconnection timeout tests to reflect a strict 3-minute limit * ci: Update reconnection timeout tests to enforce a strict 3-minute limit * chore: Remove unused MCP connection timeout message
2025-09-21 22:58:19 -04:00
// Schedule next poll with smart intervals based on OAuth timing
const nextInterval = getPollInterval(pollAttempts);
// Log progress periodically
if (pollAttempts % 5 === 0 || pollAttempts <= 2) {
console.debug(
`[MCP Manager] Polling ${serverName} attempt ${pollAttempts}/${maxAttempts}, next in ${nextInterval / 1000}s`,
);
}
timeoutId = setTimeout(pollOnce, nextInterval);
🔌 refactor: MCP UI with Improved Accessibility and Reusable Components (#11118) * feat: enhance MCP server selection UI with new components and improved accessibility * fix(i18n): add missing com_ui_mcp_servers translation key The MCP server menu aria-label was referencing a non-existent translation key. Added the missing key for accessibility. * feat(MCP): enhance MCP components with improved accessibility and focus management * fix(i18n): remove outdated MCP server translation keys * fix(MCPServerList): improve color contrast by updating text color for no MCP servers message * refactor(MCP): Server status components and improve user action handling Updated MCPServerStatusIcon to use a unified icon system for better clarity Introduced new MCPCardActions component for standardized action buttons on server cards Created MCPServerCard component to encapsulate server display logic and actions Enhanced MCPServerList to render MCPServerCard components, improving code organization Added MCPStatusBadge for consistent status representation in dialogs Updated utility functions for status color and text retrieval to align with new design Improved localization keys for better clarity and consistency in user messages * style(MCP): update button and card background styles for improved UI consistency * feat(MCP): implement global server initialization state management using Jotai * refactor(MCP): modularize MCPServerDialog into structured component architecture - Split monolithic dialog into dedicated section components (Auth, BasicInfo, Connection, Transport, Trust) - Extract form logic into useMCPServerForm custom hook - Add utility modules for JSON import and URL handling - Introduce reusable SecretInput component in @librechat/client - Remove deprecated MCPAuth component * style(MCP): update button styles for improved layout and adjust empty state background color * refactor(Radio): enhance component mounting logic and background style updates * refactor(translation): remove unused keys and streamline localization strings
2025-12-28 18:20:15 +01:00
pollIntervalsRef.current[serverName] = timeoutId;
} catch (error) {
console.error(`[MCP Manager] Error polling server ${serverName}:`, error);
⏳ refactor: MCP OAuth Polling with Gradual Backoff and Timeout Handling (#9752) * refactor: Implement gradual backoff polling for oauth connection status with timeout handling * refactor: Enhance OAuth polling with gradual backoff and timeout handling; update reconnection tracking * refactor: reconnection timeout behavior in OAuthReconnectionManager and OAuthReconnectionTracker - Implement tests to verify reconnection timeout handling, including tracking of reconnection states and cleanup of timed-out entries. - Enhance existing methods in OAuthReconnectionManager and OAuthReconnectionTracker to support timeout checks and cleanup logic. - Ensure proper handling of multiple servers with different timeout periods and edge cases for active states. * chore: remove comment * refactor: Enforce strict 3-minute OAuth timeout with updated polling intervals and improved timeout handling * refactor: Remove unused polling logic and prevent duplicate polling for servers in MCP server manager * refactor: Update localization key for no memories message in MemoryViewer * refactor: Improve MCP tool initialization by handling server failures - Introduced a mechanism to track failed MCP servers, preventing retries for unavailable servers. - Added logging for failed tool creation attempts to enhance debugging and monitoring. * refactor: Update reconnection timeout to enforce a strict 3-minute limit * ci: Update reconnection timeout tests to reflect a strict 3-minute limit * ci: Update reconnection timeout tests to enforce a strict 3-minute limit * chore: Remove unused MCP connection timeout message
2025-09-21 22:58:19 -04:00
if (timeoutId) {
clearTimeout(timeoutId);
}
cleanupServerState(serverName);
return;
}
⏳ refactor: MCP OAuth Polling with Gradual Backoff and Timeout Handling (#9752) * refactor: Implement gradual backoff polling for oauth connection status with timeout handling * refactor: Enhance OAuth polling with gradual backoff and timeout handling; update reconnection tracking * refactor: reconnection timeout behavior in OAuthReconnectionManager and OAuthReconnectionTracker - Implement tests to verify reconnection timeout handling, including tracking of reconnection states and cleanup of timed-out entries. - Enhance existing methods in OAuthReconnectionManager and OAuthReconnectionTracker to support timeout checks and cleanup logic. - Ensure proper handling of multiple servers with different timeout periods and edge cases for active states. * chore: remove comment * refactor: Enforce strict 3-minute OAuth timeout with updated polling intervals and improved timeout handling * refactor: Remove unused polling logic and prevent duplicate polling for servers in MCP server manager * refactor: Update localization key for no memories message in MemoryViewer * refactor: Improve MCP tool initialization by handling server failures - Introduced a mechanism to track failed MCP servers, preventing retries for unavailable servers. - Added logging for failed tool creation attempts to enhance debugging and monitoring. * refactor: Update reconnection timeout to enforce a strict 3-minute limit * ci: Update reconnection timeout tests to reflect a strict 3-minute limit * ci: Update reconnection timeout tests to enforce a strict 3-minute limit * chore: Remove unused MCP connection timeout message
2025-09-21 22:58:19 -04:00
};
⏳ refactor: MCP OAuth Polling with Gradual Backoff and Timeout Handling (#9752) * refactor: Implement gradual backoff polling for oauth connection status with timeout handling * refactor: Enhance OAuth polling with gradual backoff and timeout handling; update reconnection tracking * refactor: reconnection timeout behavior in OAuthReconnectionManager and OAuthReconnectionTracker - Implement tests to verify reconnection timeout handling, including tracking of reconnection states and cleanup of timed-out entries. - Enhance existing methods in OAuthReconnectionManager and OAuthReconnectionTracker to support timeout checks and cleanup logic. - Ensure proper handling of multiple servers with different timeout periods and edge cases for active states. * chore: remove comment * refactor: Enforce strict 3-minute OAuth timeout with updated polling intervals and improved timeout handling * refactor: Remove unused polling logic and prevent duplicate polling for servers in MCP server manager * refactor: Update localization key for no memories message in MemoryViewer * refactor: Improve MCP tool initialization by handling server failures - Introduced a mechanism to track failed MCP servers, preventing retries for unavailable servers. - Added logging for failed tool creation attempts to enhance debugging and monitoring. * refactor: Update reconnection timeout to enforce a strict 3-minute limit * ci: Update reconnection timeout tests to reflect a strict 3-minute limit * ci: Update reconnection timeout tests to enforce a strict 3-minute limit * chore: Remove unused MCP connection timeout message
2025-09-21 22:58:19 -04:00
// Start the first poll
timeoutId = setTimeout(pollOnce, getPollInterval(0));
🔌 refactor: MCP UI with Improved Accessibility and Reusable Components (#11118) * feat: enhance MCP server selection UI with new components and improved accessibility * fix(i18n): add missing com_ui_mcp_servers translation key The MCP server menu aria-label was referencing a non-existent translation key. Added the missing key for accessibility. * feat(MCP): enhance MCP components with improved accessibility and focus management * fix(i18n): remove outdated MCP server translation keys * fix(MCPServerList): improve color contrast by updating text color for no MCP servers message * refactor(MCP): Server status components and improve user action handling Updated MCPServerStatusIcon to use a unified icon system for better clarity Introduced new MCPCardActions component for standardized action buttons on server cards Created MCPServerCard component to encapsulate server display logic and actions Enhanced MCPServerList to render MCPServerCard components, improving code organization Added MCPStatusBadge for consistent status representation in dialogs Updated utility functions for status color and text retrieval to align with new design Improved localization keys for better clarity and consistency in user messages * style(MCP): update button and card background styles for improved UI consistency * feat(MCP): implement global server initialization state management using Jotai * refactor(MCP): modularize MCPServerDialog into structured component architecture - Split monolithic dialog into dedicated section components (Auth, BasicInfo, Connection, Transport, Trust) - Extract form logic into useMCPServerForm custom hook - Add utility modules for JSON import and URL handling - Introduce reusable SecretInput component in @librechat/client - Remove deprecated MCPAuth component * style(MCP): update button styles for improved layout and adjust empty state background color * refactor(Radio): enhance component mounting logic and background style updates * refactor(translation): remove unused keys and streamline localization strings
2025-12-28 18:20:15 +01:00
pollIntervalsRef.current[serverName] = timeoutId;
},
🔌 refactor: MCP UI with Improved Accessibility and Reusable Components (#11118) * feat: enhance MCP server selection UI with new components and improved accessibility * fix(i18n): add missing com_ui_mcp_servers translation key The MCP server menu aria-label was referencing a non-existent translation key. Added the missing key for accessibility. * feat(MCP): enhance MCP components with improved accessibility and focus management * fix(i18n): remove outdated MCP server translation keys * fix(MCPServerList): improve color contrast by updating text color for no MCP servers message * refactor(MCP): Server status components and improve user action handling Updated MCPServerStatusIcon to use a unified icon system for better clarity Introduced new MCPCardActions component for standardized action buttons on server cards Created MCPServerCard component to encapsulate server display logic and actions Enhanced MCPServerList to render MCPServerCard components, improving code organization Added MCPStatusBadge for consistent status representation in dialogs Updated utility functions for status color and text retrieval to align with new design Improved localization keys for better clarity and consistency in user messages * style(MCP): update button and card background styles for improved UI consistency * feat(MCP): implement global server initialization state management using Jotai * refactor(MCP): modularize MCPServerDialog into structured component architecture - Split monolithic dialog into dedicated section components (Auth, BasicInfo, Connection, Transport, Trust) - Extract form logic into useMCPServerForm custom hook - Add utility modules for JSON import and URL handling - Introduce reusable SecretInput component in @librechat/client - Remove deprecated MCPAuth component * style(MCP): update button styles for improved layout and adjust empty state background color * refactor(Radio): enhance component mounting logic and background style updates * refactor(translation): remove unused keys and streamline localization strings
2025-12-28 18:20:15 +01:00
[queryClient, serverInitStates, showToast, localize, setMCPValues, cleanupServerState],
);
const initializeServer = useCallback(
async (serverName: string, autoOpenOAuth: boolean = true) => {
🔌 refactor: MCP UI with Improved Accessibility and Reusable Components (#11118) * feat: enhance MCP server selection UI with new components and improved accessibility * fix(i18n): add missing com_ui_mcp_servers translation key The MCP server menu aria-label was referencing a non-existent translation key. Added the missing key for accessibility. * feat(MCP): enhance MCP components with improved accessibility and focus management * fix(i18n): remove outdated MCP server translation keys * fix(MCPServerList): improve color contrast by updating text color for no MCP servers message * refactor(MCP): Server status components and improve user action handling Updated MCPServerStatusIcon to use a unified icon system for better clarity Introduced new MCPCardActions component for standardized action buttons on server cards Created MCPServerCard component to encapsulate server display logic and actions Enhanced MCPServerList to render MCPServerCard components, improving code organization Added MCPStatusBadge for consistent status representation in dialogs Updated utility functions for status color and text retrieval to align with new design Improved localization keys for better clarity and consistency in user messages * style(MCP): update button and card background styles for improved UI consistency * feat(MCP): implement global server initialization state management using Jotai * refactor(MCP): modularize MCPServerDialog into structured component architecture - Split monolithic dialog into dedicated section components (Auth, BasicInfo, Connection, Transport, Trust) - Extract form logic into useMCPServerForm custom hook - Add utility modules for JSON import and URL handling - Introduce reusable SecretInput component in @librechat/client - Remove deprecated MCPAuth component * style(MCP): update button styles for improved layout and adjust empty state background color * refactor(Radio): enhance component mounting logic and background style updates * refactor(translation): remove unused keys and streamline localization strings
2025-12-28 18:20:15 +01:00
updateServerInitState(serverName, { isInitializing: true });
try {
const response = await reinitializeMutation.mutateAsync(serverName);
✂️ refactor: MCP UI Separation for Agents (#9237) * refactor: MCP UI Separation for Agents (Dustin WIP) feat: separate MCPs into their own lists away from tools + actions and add the status indicator functionality from chat to their dropdown ui fix: spotify mcp was not persisting on agent creation feat: show disconnected saved servers and their tools in agent mcp list in created agents fix: select-all regression fixed (caused by deleting tools we were drawing from for rendering list) fix: dont show all mcps, only those installed in agent in list feat: separate ToolSelectDialog for MCPServerTools fix: uninitialized mcp servers not showing as added in toolselectdialog refactor: reduce looping in AgentPanelContext for categorizing groups and mcps refactor: split ToolSelectDialog and MCPToolSelectDialog functionality (still needs customization for custom user vars) chore: address ESLint comments chore: address ESLint comments feat: one-click initialization on MCP servers in agent builder fix: stop propagation triggering reinit on caret click refactor: split uninitialized MCPs component from initialized MCPs feat: new mcp tool select dialog ui with custom user vars feat: show initialization state for CUV configurable MCPs too chore: remove unused localization string fix: deselecting all tools caused a re-render fix: remove subtools so removal from MCPToolSelectDialog works more consistently feat: added servers have all tools enabled by default feat: mcp server list now alphabetical to prevent annoying ui behavior of servers jumping around depending on tool selection fix: filter out placeholder group mcp tools from any actual tool calls / definitions feat: indicator now takes you to config dialog for uninitialized servers feat: show previously configured mcp servers that are now missing from the yaml feat: select all enabled by default on first add to mcp server list chore: address ESLint comments * refactor: MCP UI Separation for Agents (Danny WIP) chore: remove use of `{serverName}_mcp_{serverName}` chore: import order WIP: separate component concerns refactor: streamline agent mcp tools refactor: unify MCP server handling and improve tool visibility logic, remove unnecessary normalization or sorting, remove nesting button, make variable names clear refactor: rename mcpServerIds to mcpServerNames for clarity and consistency across components refactor: remove groupedMCPTools and toolToServerMap, streamline MCP server handling in context and components to effectively utilize mcpServersMap refactor: optimize tool selection logic by replacing array includes with Set for improved performance chore: add error logging for failed auth URL parsing in ToolCall component refactor: enhance MCP tool handling by improving server name management and updating UI elements for better clarity * refactor: decouple connection status from useMCPServerManager with useMCPConnectionStatus * fix: improve MCP tool validation logic to handle unconfigured servers * chore: enhance log message clarity for MCP server disconnection in updateUserPluginsController * refactor: simplify connection status extraction in useMCPConnectionStatus hook * refactor: improve initializing UX * chore: replace string literal with ResourceType constant in useResourcePermissions * refactor: cleanup code, remove redundancies, rename variables for clarity * chore: add back filtering and sorting for mcp tools dialog * refactor: initializeServer to return response and early return * refactor: enhance server initialization logic and improve UI for OAuth interaction * chore: clarify warning message for unconfigured MCP server in handleTools * refactor: prevent CustomUserVarsSection from submitting tools dialog form * fix: nested button of button issue in UninitializedMCPTool * feat: add functionality to revoke custom user variables in MCPToolSelectDialog --------- Co-authored-by: Danny Avila <danny@librechat.ai>
2025-08-29 19:57:01 -07:00
if (!response.success) {
showToast({
message: localize('com_ui_mcp_init_failed', { 0: serverName }),
status: 'error',
});
cleanupServerState(serverName);
return response;
}
✂️ refactor: MCP UI Separation for Agents (#9237) * refactor: MCP UI Separation for Agents (Dustin WIP) feat: separate MCPs into their own lists away from tools + actions and add the status indicator functionality from chat to their dropdown ui fix: spotify mcp was not persisting on agent creation feat: show disconnected saved servers and their tools in agent mcp list in created agents fix: select-all regression fixed (caused by deleting tools we were drawing from for rendering list) fix: dont show all mcps, only those installed in agent in list feat: separate ToolSelectDialog for MCPServerTools fix: uninitialized mcp servers not showing as added in toolselectdialog refactor: reduce looping in AgentPanelContext for categorizing groups and mcps refactor: split ToolSelectDialog and MCPToolSelectDialog functionality (still needs customization for custom user vars) chore: address ESLint comments chore: address ESLint comments feat: one-click initialization on MCP servers in agent builder fix: stop propagation triggering reinit on caret click refactor: split uninitialized MCPs component from initialized MCPs feat: new mcp tool select dialog ui with custom user vars feat: show initialization state for CUV configurable MCPs too chore: remove unused localization string fix: deselecting all tools caused a re-render fix: remove subtools so removal from MCPToolSelectDialog works more consistently feat: added servers have all tools enabled by default feat: mcp server list now alphabetical to prevent annoying ui behavior of servers jumping around depending on tool selection fix: filter out placeholder group mcp tools from any actual tool calls / definitions feat: indicator now takes you to config dialog for uninitialized servers feat: show previously configured mcp servers that are now missing from the yaml feat: select all enabled by default on first add to mcp server list chore: address ESLint comments * refactor: MCP UI Separation for Agents (Danny WIP) chore: remove use of `{serverName}_mcp_{serverName}` chore: import order WIP: separate component concerns refactor: streamline agent mcp tools refactor: unify MCP server handling and improve tool visibility logic, remove unnecessary normalization or sorting, remove nesting button, make variable names clear refactor: rename mcpServerIds to mcpServerNames for clarity and consistency across components refactor: remove groupedMCPTools and toolToServerMap, streamline MCP server handling in context and components to effectively utilize mcpServersMap refactor: optimize tool selection logic by replacing array includes with Set for improved performance chore: add error logging for failed auth URL parsing in ToolCall component refactor: enhance MCP tool handling by improving server name management and updating UI elements for better clarity * refactor: decouple connection status from useMCPServerManager with useMCPConnectionStatus * fix: improve MCP tool validation logic to handle unconfigured servers * chore: enhance log message clarity for MCP server disconnection in updateUserPluginsController * refactor: simplify connection status extraction in useMCPConnectionStatus hook * refactor: improve initializing UX * chore: replace string literal with ResourceType constant in useResourcePermissions * refactor: cleanup code, remove redundancies, rename variables for clarity * chore: add back filtering and sorting for mcp tools dialog * refactor: initializeServer to return response and early return * refactor: enhance server initialization logic and improve UI for OAuth interaction * chore: clarify warning message for unconfigured MCP server in handleTools * refactor: prevent CustomUserVarsSection from submitting tools dialog form * fix: nested button of button issue in UninitializedMCPTool * feat: add functionality to revoke custom user variables in MCPToolSelectDialog --------- Co-authored-by: Danny Avila <danny@librechat.ai>
2025-08-29 19:57:01 -07:00
if (response.oauthRequired && response.oauthUrl) {
🔌 refactor: MCP UI with Improved Accessibility and Reusable Components (#11118) * feat: enhance MCP server selection UI with new components and improved accessibility * fix(i18n): add missing com_ui_mcp_servers translation key The MCP server menu aria-label was referencing a non-existent translation key. Added the missing key for accessibility. * feat(MCP): enhance MCP components with improved accessibility and focus management * fix(i18n): remove outdated MCP server translation keys * fix(MCPServerList): improve color contrast by updating text color for no MCP servers message * refactor(MCP): Server status components and improve user action handling Updated MCPServerStatusIcon to use a unified icon system for better clarity Introduced new MCPCardActions component for standardized action buttons on server cards Created MCPServerCard component to encapsulate server display logic and actions Enhanced MCPServerList to render MCPServerCard components, improving code organization Added MCPStatusBadge for consistent status representation in dialogs Updated utility functions for status color and text retrieval to align with new design Improved localization keys for better clarity and consistency in user messages * style(MCP): update button and card background styles for improved UI consistency * feat(MCP): implement global server initialization state management using Jotai * refactor(MCP): modularize MCPServerDialog into structured component architecture - Split monolithic dialog into dedicated section components (Auth, BasicInfo, Connection, Transport, Trust) - Extract form logic into useMCPServerForm custom hook - Add utility modules for JSON import and URL handling - Introduce reusable SecretInput component in @librechat/client - Remove deprecated MCPAuth component * style(MCP): update button styles for improved layout and adjust empty state background color * refactor(Radio): enhance component mounting logic and background style updates * refactor(translation): remove unused keys and streamline localization strings
2025-12-28 18:20:15 +01:00
updateServerInitState(serverName, {
✂️ refactor: MCP UI Separation for Agents (#9237) * refactor: MCP UI Separation for Agents (Dustin WIP) feat: separate MCPs into their own lists away from tools + actions and add the status indicator functionality from chat to their dropdown ui fix: spotify mcp was not persisting on agent creation feat: show disconnected saved servers and their tools in agent mcp list in created agents fix: select-all regression fixed (caused by deleting tools we were drawing from for rendering list) fix: dont show all mcps, only those installed in agent in list feat: separate ToolSelectDialog for MCPServerTools fix: uninitialized mcp servers not showing as added in toolselectdialog refactor: reduce looping in AgentPanelContext for categorizing groups and mcps refactor: split ToolSelectDialog and MCPToolSelectDialog functionality (still needs customization for custom user vars) chore: address ESLint comments chore: address ESLint comments feat: one-click initialization on MCP servers in agent builder fix: stop propagation triggering reinit on caret click refactor: split uninitialized MCPs component from initialized MCPs feat: new mcp tool select dialog ui with custom user vars feat: show initialization state for CUV configurable MCPs too chore: remove unused localization string fix: deselecting all tools caused a re-render fix: remove subtools so removal from MCPToolSelectDialog works more consistently feat: added servers have all tools enabled by default feat: mcp server list now alphabetical to prevent annoying ui behavior of servers jumping around depending on tool selection fix: filter out placeholder group mcp tools from any actual tool calls / definitions feat: indicator now takes you to config dialog for uninitialized servers feat: show previously configured mcp servers that are now missing from the yaml feat: select all enabled by default on first add to mcp server list chore: address ESLint comments * refactor: MCP UI Separation for Agents (Danny WIP) chore: remove use of `{serverName}_mcp_{serverName}` chore: import order WIP: separate component concerns refactor: streamline agent mcp tools refactor: unify MCP server handling and improve tool visibility logic, remove unnecessary normalization or sorting, remove nesting button, make variable names clear refactor: rename mcpServerIds to mcpServerNames for clarity and consistency across components refactor: remove groupedMCPTools and toolToServerMap, streamline MCP server handling in context and components to effectively utilize mcpServersMap refactor: optimize tool selection logic by replacing array includes with Set for improved performance chore: add error logging for failed auth URL parsing in ToolCall component refactor: enhance MCP tool handling by improving server name management and updating UI elements for better clarity * refactor: decouple connection status from useMCPServerManager with useMCPConnectionStatus * fix: improve MCP tool validation logic to handle unconfigured servers * chore: enhance log message clarity for MCP server disconnection in updateUserPluginsController * refactor: simplify connection status extraction in useMCPConnectionStatus hook * refactor: improve initializing UX * chore: replace string literal with ResourceType constant in useResourcePermissions * refactor: cleanup code, remove redundancies, rename variables for clarity * chore: add back filtering and sorting for mcp tools dialog * refactor: initializeServer to return response and early return * refactor: enhance server initialization logic and improve UI for OAuth interaction * chore: clarify warning message for unconfigured MCP server in handleTools * refactor: prevent CustomUserVarsSection from submitting tools dialog form * fix: nested button of button issue in UninitializedMCPTool * feat: add functionality to revoke custom user variables in MCPToolSelectDialog --------- Co-authored-by: Danny Avila <danny@librechat.ai>
2025-08-29 19:57:01 -07:00
oauthUrl: response.oauthUrl,
oauthStartTime: Date.now(),
isCancellable: true,
isInitializing: true,
});
✂️ refactor: MCP UI Separation for Agents (#9237) * refactor: MCP UI Separation for Agents (Dustin WIP) feat: separate MCPs into their own lists away from tools + actions and add the status indicator functionality from chat to their dropdown ui fix: spotify mcp was not persisting on agent creation feat: show disconnected saved servers and their tools in agent mcp list in created agents fix: select-all regression fixed (caused by deleting tools we were drawing from for rendering list) fix: dont show all mcps, only those installed in agent in list feat: separate ToolSelectDialog for MCPServerTools fix: uninitialized mcp servers not showing as added in toolselectdialog refactor: reduce looping in AgentPanelContext for categorizing groups and mcps refactor: split ToolSelectDialog and MCPToolSelectDialog functionality (still needs customization for custom user vars) chore: address ESLint comments chore: address ESLint comments feat: one-click initialization on MCP servers in agent builder fix: stop propagation triggering reinit on caret click refactor: split uninitialized MCPs component from initialized MCPs feat: new mcp tool select dialog ui with custom user vars feat: show initialization state for CUV configurable MCPs too chore: remove unused localization string fix: deselecting all tools caused a re-render fix: remove subtools so removal from MCPToolSelectDialog works more consistently feat: added servers have all tools enabled by default feat: mcp server list now alphabetical to prevent annoying ui behavior of servers jumping around depending on tool selection fix: filter out placeholder group mcp tools from any actual tool calls / definitions feat: indicator now takes you to config dialog for uninitialized servers feat: show previously configured mcp servers that are now missing from the yaml feat: select all enabled by default on first add to mcp server list chore: address ESLint comments * refactor: MCP UI Separation for Agents (Danny WIP) chore: remove use of `{serverName}_mcp_{serverName}` chore: import order WIP: separate component concerns refactor: streamline agent mcp tools refactor: unify MCP server handling and improve tool visibility logic, remove unnecessary normalization or sorting, remove nesting button, make variable names clear refactor: rename mcpServerIds to mcpServerNames for clarity and consistency across components refactor: remove groupedMCPTools and toolToServerMap, streamline MCP server handling in context and components to effectively utilize mcpServersMap refactor: optimize tool selection logic by replacing array includes with Set for improved performance chore: add error logging for failed auth URL parsing in ToolCall component refactor: enhance MCP tool handling by improving server name management and updating UI elements for better clarity * refactor: decouple connection status from useMCPServerManager with useMCPConnectionStatus * fix: improve MCP tool validation logic to handle unconfigured servers * chore: enhance log message clarity for MCP server disconnection in updateUserPluginsController * refactor: simplify connection status extraction in useMCPConnectionStatus hook * refactor: improve initializing UX * chore: replace string literal with ResourceType constant in useResourcePermissions * refactor: cleanup code, remove redundancies, rename variables for clarity * chore: add back filtering and sorting for mcp tools dialog * refactor: initializeServer to return response and early return * refactor: enhance server initialization logic and improve UI for OAuth interaction * chore: clarify warning message for unconfigured MCP server in handleTools * refactor: prevent CustomUserVarsSection from submitting tools dialog form * fix: nested button of button issue in UninitializedMCPTool * feat: add functionality to revoke custom user variables in MCPToolSelectDialog --------- Co-authored-by: Danny Avila <danny@librechat.ai>
2025-08-29 19:57:01 -07:00
if (autoOpenOAuth) {
window.open(response.oauthUrl, '_blank', 'noopener,noreferrer');
}
✂️ refactor: MCP UI Separation for Agents (#9237) * refactor: MCP UI Separation for Agents (Dustin WIP) feat: separate MCPs into their own lists away from tools + actions and add the status indicator functionality from chat to their dropdown ui fix: spotify mcp was not persisting on agent creation feat: show disconnected saved servers and their tools in agent mcp list in created agents fix: select-all regression fixed (caused by deleting tools we were drawing from for rendering list) fix: dont show all mcps, only those installed in agent in list feat: separate ToolSelectDialog for MCPServerTools fix: uninitialized mcp servers not showing as added in toolselectdialog refactor: reduce looping in AgentPanelContext for categorizing groups and mcps refactor: split ToolSelectDialog and MCPToolSelectDialog functionality (still needs customization for custom user vars) chore: address ESLint comments chore: address ESLint comments feat: one-click initialization on MCP servers in agent builder fix: stop propagation triggering reinit on caret click refactor: split uninitialized MCPs component from initialized MCPs feat: new mcp tool select dialog ui with custom user vars feat: show initialization state for CUV configurable MCPs too chore: remove unused localization string fix: deselecting all tools caused a re-render fix: remove subtools so removal from MCPToolSelectDialog works more consistently feat: added servers have all tools enabled by default feat: mcp server list now alphabetical to prevent annoying ui behavior of servers jumping around depending on tool selection fix: filter out placeholder group mcp tools from any actual tool calls / definitions feat: indicator now takes you to config dialog for uninitialized servers feat: show previously configured mcp servers that are now missing from the yaml feat: select all enabled by default on first add to mcp server list chore: address ESLint comments * refactor: MCP UI Separation for Agents (Danny WIP) chore: remove use of `{serverName}_mcp_{serverName}` chore: import order WIP: separate component concerns refactor: streamline agent mcp tools refactor: unify MCP server handling and improve tool visibility logic, remove unnecessary normalization or sorting, remove nesting button, make variable names clear refactor: rename mcpServerIds to mcpServerNames for clarity and consistency across components refactor: remove groupedMCPTools and toolToServerMap, streamline MCP server handling in context and components to effectively utilize mcpServersMap refactor: optimize tool selection logic by replacing array includes with Set for improved performance chore: add error logging for failed auth URL parsing in ToolCall component refactor: enhance MCP tool handling by improving server name management and updating UI elements for better clarity * refactor: decouple connection status from useMCPServerManager with useMCPConnectionStatus * fix: improve MCP tool validation logic to handle unconfigured servers * chore: enhance log message clarity for MCP server disconnection in updateUserPluginsController * refactor: simplify connection status extraction in useMCPConnectionStatus hook * refactor: improve initializing UX * chore: replace string literal with ResourceType constant in useResourcePermissions * refactor: cleanup code, remove redundancies, rename variables for clarity * chore: add back filtering and sorting for mcp tools dialog * refactor: initializeServer to return response and early return * refactor: enhance server initialization logic and improve UI for OAuth interaction * chore: clarify warning message for unconfigured MCP server in handleTools * refactor: prevent CustomUserVarsSection from submitting tools dialog form * fix: nested button of button issue in UninitializedMCPTool * feat: add functionality to revoke custom user variables in MCPToolSelectDialog --------- Co-authored-by: Danny Avila <danny@librechat.ai>
2025-08-29 19:57:01 -07:00
startServerPolling(serverName);
} else {
await Promise.all([
queryClient.invalidateQueries([QueryKeys.mcpServers]),
queryClient.invalidateQueries([QueryKeys.mcpTools]),
queryClient.invalidateQueries([QueryKeys.mcpAuthValues]),
queryClient.invalidateQueries([QueryKeys.mcpConnectionStatus]),
]);
✂️ refactor: MCP UI Separation for Agents (#9237) * refactor: MCP UI Separation for Agents (Dustin WIP) feat: separate MCPs into their own lists away from tools + actions and add the status indicator functionality from chat to their dropdown ui fix: spotify mcp was not persisting on agent creation feat: show disconnected saved servers and their tools in agent mcp list in created agents fix: select-all regression fixed (caused by deleting tools we were drawing from for rendering list) fix: dont show all mcps, only those installed in agent in list feat: separate ToolSelectDialog for MCPServerTools fix: uninitialized mcp servers not showing as added in toolselectdialog refactor: reduce looping in AgentPanelContext for categorizing groups and mcps refactor: split ToolSelectDialog and MCPToolSelectDialog functionality (still needs customization for custom user vars) chore: address ESLint comments chore: address ESLint comments feat: one-click initialization on MCP servers in agent builder fix: stop propagation triggering reinit on caret click refactor: split uninitialized MCPs component from initialized MCPs feat: new mcp tool select dialog ui with custom user vars feat: show initialization state for CUV configurable MCPs too chore: remove unused localization string fix: deselecting all tools caused a re-render fix: remove subtools so removal from MCPToolSelectDialog works more consistently feat: added servers have all tools enabled by default feat: mcp server list now alphabetical to prevent annoying ui behavior of servers jumping around depending on tool selection fix: filter out placeholder group mcp tools from any actual tool calls / definitions feat: indicator now takes you to config dialog for uninitialized servers feat: show previously configured mcp servers that are now missing from the yaml feat: select all enabled by default on first add to mcp server list chore: address ESLint comments * refactor: MCP UI Separation for Agents (Danny WIP) chore: remove use of `{serverName}_mcp_{serverName}` chore: import order WIP: separate component concerns refactor: streamline agent mcp tools refactor: unify MCP server handling and improve tool visibility logic, remove unnecessary normalization or sorting, remove nesting button, make variable names clear refactor: rename mcpServerIds to mcpServerNames for clarity and consistency across components refactor: remove groupedMCPTools and toolToServerMap, streamline MCP server handling in context and components to effectively utilize mcpServersMap refactor: optimize tool selection logic by replacing array includes with Set for improved performance chore: add error logging for failed auth URL parsing in ToolCall component refactor: enhance MCP tool handling by improving server name management and updating UI elements for better clarity * refactor: decouple connection status from useMCPServerManager with useMCPConnectionStatus * fix: improve MCP tool validation logic to handle unconfigured servers * chore: enhance log message clarity for MCP server disconnection in updateUserPluginsController * refactor: simplify connection status extraction in useMCPConnectionStatus hook * refactor: improve initializing UX * chore: replace string literal with ResourceType constant in useResourcePermissions * refactor: cleanup code, remove redundancies, rename variables for clarity * chore: add back filtering and sorting for mcp tools dialog * refactor: initializeServer to return response and early return * refactor: enhance server initialization logic and improve UI for OAuth interaction * chore: clarify warning message for unconfigured MCP server in handleTools * refactor: prevent CustomUserVarsSection from submitting tools dialog form * fix: nested button of button issue in UninitializedMCPTool * feat: add functionality to revoke custom user variables in MCPToolSelectDialog --------- Co-authored-by: Danny Avila <danny@librechat.ai>
2025-08-29 19:57:01 -07:00
showToast({
✂️ refactor: MCP UI Separation for Agents (#9237) * refactor: MCP UI Separation for Agents (Dustin WIP) feat: separate MCPs into their own lists away from tools + actions and add the status indicator functionality from chat to their dropdown ui fix: spotify mcp was not persisting on agent creation feat: show disconnected saved servers and their tools in agent mcp list in created agents fix: select-all regression fixed (caused by deleting tools we were drawing from for rendering list) fix: dont show all mcps, only those installed in agent in list feat: separate ToolSelectDialog for MCPServerTools fix: uninitialized mcp servers not showing as added in toolselectdialog refactor: reduce looping in AgentPanelContext for categorizing groups and mcps refactor: split ToolSelectDialog and MCPToolSelectDialog functionality (still needs customization for custom user vars) chore: address ESLint comments chore: address ESLint comments feat: one-click initialization on MCP servers in agent builder fix: stop propagation triggering reinit on caret click refactor: split uninitialized MCPs component from initialized MCPs feat: new mcp tool select dialog ui with custom user vars feat: show initialization state for CUV configurable MCPs too chore: remove unused localization string fix: deselecting all tools caused a re-render fix: remove subtools so removal from MCPToolSelectDialog works more consistently feat: added servers have all tools enabled by default feat: mcp server list now alphabetical to prevent annoying ui behavior of servers jumping around depending on tool selection fix: filter out placeholder group mcp tools from any actual tool calls / definitions feat: indicator now takes you to config dialog for uninitialized servers feat: show previously configured mcp servers that are now missing from the yaml feat: select all enabled by default on first add to mcp server list chore: address ESLint comments * refactor: MCP UI Separation for Agents (Danny WIP) chore: remove use of `{serverName}_mcp_{serverName}` chore: import order WIP: separate component concerns refactor: streamline agent mcp tools refactor: unify MCP server handling and improve tool visibility logic, remove unnecessary normalization or sorting, remove nesting button, make variable names clear refactor: rename mcpServerIds to mcpServerNames for clarity and consistency across components refactor: remove groupedMCPTools and toolToServerMap, streamline MCP server handling in context and components to effectively utilize mcpServersMap refactor: optimize tool selection logic by replacing array includes with Set for improved performance chore: add error logging for failed auth URL parsing in ToolCall component refactor: enhance MCP tool handling by improving server name management and updating UI elements for better clarity * refactor: decouple connection status from useMCPServerManager with useMCPConnectionStatus * fix: improve MCP tool validation logic to handle unconfigured servers * chore: enhance log message clarity for MCP server disconnection in updateUserPluginsController * refactor: simplify connection status extraction in useMCPConnectionStatus hook * refactor: improve initializing UX * chore: replace string literal with ResourceType constant in useResourcePermissions * refactor: cleanup code, remove redundancies, rename variables for clarity * chore: add back filtering and sorting for mcp tools dialog * refactor: initializeServer to return response and early return * refactor: enhance server initialization logic and improve UI for OAuth interaction * chore: clarify warning message for unconfigured MCP server in handleTools * refactor: prevent CustomUserVarsSection from submitting tools dialog form * fix: nested button of button issue in UninitializedMCPTool * feat: add functionality to revoke custom user variables in MCPToolSelectDialog --------- Co-authored-by: Danny Avila <danny@librechat.ai>
2025-08-29 19:57:01 -07:00
message: localize('com_ui_mcp_initialized_success', { 0: serverName }),
status: 'success',
});
✂️ refactor: MCP UI Separation for Agents (#9237) * refactor: MCP UI Separation for Agents (Dustin WIP) feat: separate MCPs into their own lists away from tools + actions and add the status indicator functionality from chat to their dropdown ui fix: spotify mcp was not persisting on agent creation feat: show disconnected saved servers and their tools in agent mcp list in created agents fix: select-all regression fixed (caused by deleting tools we were drawing from for rendering list) fix: dont show all mcps, only those installed in agent in list feat: separate ToolSelectDialog for MCPServerTools fix: uninitialized mcp servers not showing as added in toolselectdialog refactor: reduce looping in AgentPanelContext for categorizing groups and mcps refactor: split ToolSelectDialog and MCPToolSelectDialog functionality (still needs customization for custom user vars) chore: address ESLint comments chore: address ESLint comments feat: one-click initialization on MCP servers in agent builder fix: stop propagation triggering reinit on caret click refactor: split uninitialized MCPs component from initialized MCPs feat: new mcp tool select dialog ui with custom user vars feat: show initialization state for CUV configurable MCPs too chore: remove unused localization string fix: deselecting all tools caused a re-render fix: remove subtools so removal from MCPToolSelectDialog works more consistently feat: added servers have all tools enabled by default feat: mcp server list now alphabetical to prevent annoying ui behavior of servers jumping around depending on tool selection fix: filter out placeholder group mcp tools from any actual tool calls / definitions feat: indicator now takes you to config dialog for uninitialized servers feat: show previously configured mcp servers that are now missing from the yaml feat: select all enabled by default on first add to mcp server list chore: address ESLint comments * refactor: MCP UI Separation for Agents (Danny WIP) chore: remove use of `{serverName}_mcp_{serverName}` chore: import order WIP: separate component concerns refactor: streamline agent mcp tools refactor: unify MCP server handling and improve tool visibility logic, remove unnecessary normalization or sorting, remove nesting button, make variable names clear refactor: rename mcpServerIds to mcpServerNames for clarity and consistency across components refactor: remove groupedMCPTools and toolToServerMap, streamline MCP server handling in context and components to effectively utilize mcpServersMap refactor: optimize tool selection logic by replacing array includes with Set for improved performance chore: add error logging for failed auth URL parsing in ToolCall component refactor: enhance MCP tool handling by improving server name management and updating UI elements for better clarity * refactor: decouple connection status from useMCPServerManager with useMCPConnectionStatus * fix: improve MCP tool validation logic to handle unconfigured servers * chore: enhance log message clarity for MCP server disconnection in updateUserPluginsController * refactor: simplify connection status extraction in useMCPConnectionStatus hook * refactor: improve initializing UX * chore: replace string literal with ResourceType constant in useResourcePermissions * refactor: cleanup code, remove redundancies, rename variables for clarity * chore: add back filtering and sorting for mcp tools dialog * refactor: initializeServer to return response and early return * refactor: enhance server initialization logic and improve UI for OAuth interaction * chore: clarify warning message for unconfigured MCP server in handleTools * refactor: prevent CustomUserVarsSection from submitting tools dialog form * fix: nested button of button issue in UninitializedMCPTool * feat: add functionality to revoke custom user variables in MCPToolSelectDialog --------- Co-authored-by: Danny Avila <danny@librechat.ai>
2025-08-29 19:57:01 -07:00
const currentValues = mcpValues ?? [];
if (!currentValues.includes(serverName)) {
setMCPValues([...currentValues, serverName]);
}
cleanupServerState(serverName);
}
✂️ refactor: MCP UI Separation for Agents (#9237) * refactor: MCP UI Separation for Agents (Dustin WIP) feat: separate MCPs into their own lists away from tools + actions and add the status indicator functionality from chat to their dropdown ui fix: spotify mcp was not persisting on agent creation feat: show disconnected saved servers and their tools in agent mcp list in created agents fix: select-all regression fixed (caused by deleting tools we were drawing from for rendering list) fix: dont show all mcps, only those installed in agent in list feat: separate ToolSelectDialog for MCPServerTools fix: uninitialized mcp servers not showing as added in toolselectdialog refactor: reduce looping in AgentPanelContext for categorizing groups and mcps refactor: split ToolSelectDialog and MCPToolSelectDialog functionality (still needs customization for custom user vars) chore: address ESLint comments chore: address ESLint comments feat: one-click initialization on MCP servers in agent builder fix: stop propagation triggering reinit on caret click refactor: split uninitialized MCPs component from initialized MCPs feat: new mcp tool select dialog ui with custom user vars feat: show initialization state for CUV configurable MCPs too chore: remove unused localization string fix: deselecting all tools caused a re-render fix: remove subtools so removal from MCPToolSelectDialog works more consistently feat: added servers have all tools enabled by default feat: mcp server list now alphabetical to prevent annoying ui behavior of servers jumping around depending on tool selection fix: filter out placeholder group mcp tools from any actual tool calls / definitions feat: indicator now takes you to config dialog for uninitialized servers feat: show previously configured mcp servers that are now missing from the yaml feat: select all enabled by default on first add to mcp server list chore: address ESLint comments * refactor: MCP UI Separation for Agents (Danny WIP) chore: remove use of `{serverName}_mcp_{serverName}` chore: import order WIP: separate component concerns refactor: streamline agent mcp tools refactor: unify MCP server handling and improve tool visibility logic, remove unnecessary normalization or sorting, remove nesting button, make variable names clear refactor: rename mcpServerIds to mcpServerNames for clarity and consistency across components refactor: remove groupedMCPTools and toolToServerMap, streamline MCP server handling in context and components to effectively utilize mcpServersMap refactor: optimize tool selection logic by replacing array includes with Set for improved performance chore: add error logging for failed auth URL parsing in ToolCall component refactor: enhance MCP tool handling by improving server name management and updating UI elements for better clarity * refactor: decouple connection status from useMCPServerManager with useMCPConnectionStatus * fix: improve MCP tool validation logic to handle unconfigured servers * chore: enhance log message clarity for MCP server disconnection in updateUserPluginsController * refactor: simplify connection status extraction in useMCPConnectionStatus hook * refactor: improve initializing UX * chore: replace string literal with ResourceType constant in useResourcePermissions * refactor: cleanup code, remove redundancies, rename variables for clarity * chore: add back filtering and sorting for mcp tools dialog * refactor: initializeServer to return response and early return * refactor: enhance server initialization logic and improve UI for OAuth interaction * chore: clarify warning message for unconfigured MCP server in handleTools * refactor: prevent CustomUserVarsSection from submitting tools dialog form * fix: nested button of button issue in UninitializedMCPTool * feat: add functionality to revoke custom user variables in MCPToolSelectDialog --------- Co-authored-by: Danny Avila <danny@librechat.ai>
2025-08-29 19:57:01 -07:00
return response;
} catch (error) {
console.error(`[MCP Manager] Failed to initialize ${serverName}:`, error);
showToast({
message: localize('com_ui_mcp_init_failed', { 0: serverName }),
status: 'error',
});
cleanupServerState(serverName);
}
},
[
🔌 refactor: MCP UI with Improved Accessibility and Reusable Components (#11118) * feat: enhance MCP server selection UI with new components and improved accessibility * fix(i18n): add missing com_ui_mcp_servers translation key The MCP server menu aria-label was referencing a non-existent translation key. Added the missing key for accessibility. * feat(MCP): enhance MCP components with improved accessibility and focus management * fix(i18n): remove outdated MCP server translation keys * fix(MCPServerList): improve color contrast by updating text color for no MCP servers message * refactor(MCP): Server status components and improve user action handling Updated MCPServerStatusIcon to use a unified icon system for better clarity Introduced new MCPCardActions component for standardized action buttons on server cards Created MCPServerCard component to encapsulate server display logic and actions Enhanced MCPServerList to render MCPServerCard components, improving code organization Added MCPStatusBadge for consistent status representation in dialogs Updated utility functions for status color and text retrieval to align with new design Improved localization keys for better clarity and consistency in user messages * style(MCP): update button and card background styles for improved UI consistency * feat(MCP): implement global server initialization state management using Jotai * refactor(MCP): modularize MCPServerDialog into structured component architecture - Split monolithic dialog into dedicated section components (Auth, BasicInfo, Connection, Transport, Trust) - Extract form logic into useMCPServerForm custom hook - Add utility modules for JSON import and URL handling - Introduce reusable SecretInput component in @librechat/client - Remove deprecated MCPAuth component * style(MCP): update button styles for improved layout and adjust empty state background color * refactor(Radio): enhance component mounting logic and background style updates * refactor(translation): remove unused keys and streamline localization strings
2025-12-28 18:20:15 +01:00
updateServerInitState,
reinitializeMutation,
startServerPolling,
queryClient,
showToast,
localize,
mcpValues,
cleanupServerState,
setMCPValues,
],
);
const cancelOAuthFlow = useCallback(
(serverName: string) => {
cancelOAuthMutation.mutate(serverName, {
onSuccess: () => {
cleanupServerState(serverName);
🏗️ 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>
2025-12-04 21:37:23 +01:00
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 }),
status: 'warning',
});
},
onError: (error) => {
console.error(`[MCP Manager] Failed to cancel OAuth for ${serverName}:`, error);
showToast({
message: localize('com_ui_mcp_init_failed', { 0: serverName }),
status: 'error',
});
},
});
},
[queryClient, cleanupServerState, showToast, localize, cancelOAuthMutation],
);
const isInitializing = useCallback(
(serverName: string) => {
🔌 refactor: MCP UI with Improved Accessibility and Reusable Components (#11118) * feat: enhance MCP server selection UI with new components and improved accessibility * fix(i18n): add missing com_ui_mcp_servers translation key The MCP server menu aria-label was referencing a non-existent translation key. Added the missing key for accessibility. * feat(MCP): enhance MCP components with improved accessibility and focus management * fix(i18n): remove outdated MCP server translation keys * fix(MCPServerList): improve color contrast by updating text color for no MCP servers message * refactor(MCP): Server status components and improve user action handling Updated MCPServerStatusIcon to use a unified icon system for better clarity Introduced new MCPCardActions component for standardized action buttons on server cards Created MCPServerCard component to encapsulate server display logic and actions Enhanced MCPServerList to render MCPServerCard components, improving code organization Added MCPStatusBadge for consistent status representation in dialogs Updated utility functions for status color and text retrieval to align with new design Improved localization keys for better clarity and consistency in user messages * style(MCP): update button and card background styles for improved UI consistency * feat(MCP): implement global server initialization state management using Jotai * refactor(MCP): modularize MCPServerDialog into structured component architecture - Split monolithic dialog into dedicated section components (Auth, BasicInfo, Connection, Transport, Trust) - Extract form logic into useMCPServerForm custom hook - Add utility modules for JSON import and URL handling - Introduce reusable SecretInput component in @librechat/client - Remove deprecated MCPAuth component * style(MCP): update button styles for improved layout and adjust empty state background color * refactor(Radio): enhance component mounting logic and background style updates * refactor(translation): remove unused keys and streamline localization strings
2025-12-28 18:20:15 +01:00
return getServerInitState(serverInitStates, serverName).isInitializing;
},
🔌 refactor: MCP UI with Improved Accessibility and Reusable Components (#11118) * feat: enhance MCP server selection UI with new components and improved accessibility * fix(i18n): add missing com_ui_mcp_servers translation key The MCP server menu aria-label was referencing a non-existent translation key. Added the missing key for accessibility. * feat(MCP): enhance MCP components with improved accessibility and focus management * fix(i18n): remove outdated MCP server translation keys * fix(MCPServerList): improve color contrast by updating text color for no MCP servers message * refactor(MCP): Server status components and improve user action handling Updated MCPServerStatusIcon to use a unified icon system for better clarity Introduced new MCPCardActions component for standardized action buttons on server cards Created MCPServerCard component to encapsulate server display logic and actions Enhanced MCPServerList to render MCPServerCard components, improving code organization Added MCPStatusBadge for consistent status representation in dialogs Updated utility functions for status color and text retrieval to align with new design Improved localization keys for better clarity and consistency in user messages * style(MCP): update button and card background styles for improved UI consistency * feat(MCP): implement global server initialization state management using Jotai * refactor(MCP): modularize MCPServerDialog into structured component architecture - Split monolithic dialog into dedicated section components (Auth, BasicInfo, Connection, Transport, Trust) - Extract form logic into useMCPServerForm custom hook - Add utility modules for JSON import and URL handling - Introduce reusable SecretInput component in @librechat/client - Remove deprecated MCPAuth component * style(MCP): update button styles for improved layout and adjust empty state background color * refactor(Radio): enhance component mounting logic and background style updates * refactor(translation): remove unused keys and streamline localization strings
2025-12-28 18:20:15 +01:00
[serverInitStates],
);
const isCancellable = useCallback(
(serverName: string) => {
🔌 refactor: MCP UI with Improved Accessibility and Reusable Components (#11118) * feat: enhance MCP server selection UI with new components and improved accessibility * fix(i18n): add missing com_ui_mcp_servers translation key The MCP server menu aria-label was referencing a non-existent translation key. Added the missing key for accessibility. * feat(MCP): enhance MCP components with improved accessibility and focus management * fix(i18n): remove outdated MCP server translation keys * fix(MCPServerList): improve color contrast by updating text color for no MCP servers message * refactor(MCP): Server status components and improve user action handling Updated MCPServerStatusIcon to use a unified icon system for better clarity Introduced new MCPCardActions component for standardized action buttons on server cards Created MCPServerCard component to encapsulate server display logic and actions Enhanced MCPServerList to render MCPServerCard components, improving code organization Added MCPStatusBadge for consistent status representation in dialogs Updated utility functions for status color and text retrieval to align with new design Improved localization keys for better clarity and consistency in user messages * style(MCP): update button and card background styles for improved UI consistency * feat(MCP): implement global server initialization state management using Jotai * refactor(MCP): modularize MCPServerDialog into structured component architecture - Split monolithic dialog into dedicated section components (Auth, BasicInfo, Connection, Transport, Trust) - Extract form logic into useMCPServerForm custom hook - Add utility modules for JSON import and URL handling - Introduce reusable SecretInput component in @librechat/client - Remove deprecated MCPAuth component * style(MCP): update button styles for improved layout and adjust empty state background color * refactor(Radio): enhance component mounting logic and background style updates * refactor(translation): remove unused keys and streamline localization strings
2025-12-28 18:20:15 +01:00
return getServerInitState(serverInitStates, serverName).isCancellable;
},
🔌 refactor: MCP UI with Improved Accessibility and Reusable Components (#11118) * feat: enhance MCP server selection UI with new components and improved accessibility * fix(i18n): add missing com_ui_mcp_servers translation key The MCP server menu aria-label was referencing a non-existent translation key. Added the missing key for accessibility. * feat(MCP): enhance MCP components with improved accessibility and focus management * fix(i18n): remove outdated MCP server translation keys * fix(MCPServerList): improve color contrast by updating text color for no MCP servers message * refactor(MCP): Server status components and improve user action handling Updated MCPServerStatusIcon to use a unified icon system for better clarity Introduced new MCPCardActions component for standardized action buttons on server cards Created MCPServerCard component to encapsulate server display logic and actions Enhanced MCPServerList to render MCPServerCard components, improving code organization Added MCPStatusBadge for consistent status representation in dialogs Updated utility functions for status color and text retrieval to align with new design Improved localization keys for better clarity and consistency in user messages * style(MCP): update button and card background styles for improved UI consistency * feat(MCP): implement global server initialization state management using Jotai * refactor(MCP): modularize MCPServerDialog into structured component architecture - Split monolithic dialog into dedicated section components (Auth, BasicInfo, Connection, Transport, Trust) - Extract form logic into useMCPServerForm custom hook - Add utility modules for JSON import and URL handling - Introduce reusable SecretInput component in @librechat/client - Remove deprecated MCPAuth component * style(MCP): update button styles for improved layout and adjust empty state background color * refactor(Radio): enhance component mounting logic and background style updates * refactor(translation): remove unused keys and streamline localization strings
2025-12-28 18:20:15 +01:00
[serverInitStates],
);
const getOAuthUrl = useCallback(
(serverName: string) => {
🔌 refactor: MCP UI with Improved Accessibility and Reusable Components (#11118) * feat: enhance MCP server selection UI with new components and improved accessibility * fix(i18n): add missing com_ui_mcp_servers translation key The MCP server menu aria-label was referencing a non-existent translation key. Added the missing key for accessibility. * feat(MCP): enhance MCP components with improved accessibility and focus management * fix(i18n): remove outdated MCP server translation keys * fix(MCPServerList): improve color contrast by updating text color for no MCP servers message * refactor(MCP): Server status components and improve user action handling Updated MCPServerStatusIcon to use a unified icon system for better clarity Introduced new MCPCardActions component for standardized action buttons on server cards Created MCPServerCard component to encapsulate server display logic and actions Enhanced MCPServerList to render MCPServerCard components, improving code organization Added MCPStatusBadge for consistent status representation in dialogs Updated utility functions for status color and text retrieval to align with new design Improved localization keys for better clarity and consistency in user messages * style(MCP): update button and card background styles for improved UI consistency * feat(MCP): implement global server initialization state management using Jotai * refactor(MCP): modularize MCPServerDialog into structured component architecture - Split monolithic dialog into dedicated section components (Auth, BasicInfo, Connection, Transport, Trust) - Extract form logic into useMCPServerForm custom hook - Add utility modules for JSON import and URL handling - Introduce reusable SecretInput component in @librechat/client - Remove deprecated MCPAuth component * style(MCP): update button styles for improved layout and adjust empty state background color * refactor(Radio): enhance component mounting logic and background style updates * refactor(translation): remove unused keys and streamline localization strings
2025-12-28 18:20:15 +01:00
return getServerInitState(serverInitStates, serverName).oauthUrl;
},
🔌 refactor: MCP UI with Improved Accessibility and Reusable Components (#11118) * feat: enhance MCP server selection UI with new components and improved accessibility * fix(i18n): add missing com_ui_mcp_servers translation key The MCP server menu aria-label was referencing a non-existent translation key. Added the missing key for accessibility. * feat(MCP): enhance MCP components with improved accessibility and focus management * fix(i18n): remove outdated MCP server translation keys * fix(MCPServerList): improve color contrast by updating text color for no MCP servers message * refactor(MCP): Server status components and improve user action handling Updated MCPServerStatusIcon to use a unified icon system for better clarity Introduced new MCPCardActions component for standardized action buttons on server cards Created MCPServerCard component to encapsulate server display logic and actions Enhanced MCPServerList to render MCPServerCard components, improving code organization Added MCPStatusBadge for consistent status representation in dialogs Updated utility functions for status color and text retrieval to align with new design Improved localization keys for better clarity and consistency in user messages * style(MCP): update button and card background styles for improved UI consistency * feat(MCP): implement global server initialization state management using Jotai * refactor(MCP): modularize MCPServerDialog into structured component architecture - Split monolithic dialog into dedicated section components (Auth, BasicInfo, Connection, Transport, Trust) - Extract form logic into useMCPServerForm custom hook - Add utility modules for JSON import and URL handling - Introduce reusable SecretInput component in @librechat/client - Remove deprecated MCPAuth component * style(MCP): update button styles for improved layout and adjust empty state background color * refactor(Radio): enhance component mounting logic and background style updates * refactor(translation): remove unused keys and streamline localization strings
2025-12-28 18:20:15 +01:00
[serverInitStates],
);
const placeholderText = useMemo(
() => startupConfig?.interface?.mcpServers?.placeholder || localize('com_ui_mcp_servers'),
[startupConfig?.interface?.mcpServers?.placeholder, localize],
);
const batchToggleServers = useCallback(
(serverNames: string[]) => {
const connectedServers: string[] = [];
const disconnectedServers: string[] = [];
serverNames.forEach((serverName) => {
if (isInitializing(serverName)) {
return;
}
✂️ refactor: MCP UI Separation for Agents (#9237) * refactor: MCP UI Separation for Agents (Dustin WIP) feat: separate MCPs into their own lists away from tools + actions and add the status indicator functionality from chat to their dropdown ui fix: spotify mcp was not persisting on agent creation feat: show disconnected saved servers and their tools in agent mcp list in created agents fix: select-all regression fixed (caused by deleting tools we were drawing from for rendering list) fix: dont show all mcps, only those installed in agent in list feat: separate ToolSelectDialog for MCPServerTools fix: uninitialized mcp servers not showing as added in toolselectdialog refactor: reduce looping in AgentPanelContext for categorizing groups and mcps refactor: split ToolSelectDialog and MCPToolSelectDialog functionality (still needs customization for custom user vars) chore: address ESLint comments chore: address ESLint comments feat: one-click initialization on MCP servers in agent builder fix: stop propagation triggering reinit on caret click refactor: split uninitialized MCPs component from initialized MCPs feat: new mcp tool select dialog ui with custom user vars feat: show initialization state for CUV configurable MCPs too chore: remove unused localization string fix: deselecting all tools caused a re-render fix: remove subtools so removal from MCPToolSelectDialog works more consistently feat: added servers have all tools enabled by default feat: mcp server list now alphabetical to prevent annoying ui behavior of servers jumping around depending on tool selection fix: filter out placeholder group mcp tools from any actual tool calls / definitions feat: indicator now takes you to config dialog for uninitialized servers feat: show previously configured mcp servers that are now missing from the yaml feat: select all enabled by default on first add to mcp server list chore: address ESLint comments * refactor: MCP UI Separation for Agents (Danny WIP) chore: remove use of `{serverName}_mcp_{serverName}` chore: import order WIP: separate component concerns refactor: streamline agent mcp tools refactor: unify MCP server handling and improve tool visibility logic, remove unnecessary normalization or sorting, remove nesting button, make variable names clear refactor: rename mcpServerIds to mcpServerNames for clarity and consistency across components refactor: remove groupedMCPTools and toolToServerMap, streamline MCP server handling in context and components to effectively utilize mcpServersMap refactor: optimize tool selection logic by replacing array includes with Set for improved performance chore: add error logging for failed auth URL parsing in ToolCall component refactor: enhance MCP tool handling by improving server name management and updating UI elements for better clarity * refactor: decouple connection status from useMCPServerManager with useMCPConnectionStatus * fix: improve MCP tool validation logic to handle unconfigured servers * chore: enhance log message clarity for MCP server disconnection in updateUserPluginsController * refactor: simplify connection status extraction in useMCPConnectionStatus hook * refactor: improve initializing UX * chore: replace string literal with ResourceType constant in useResourcePermissions * refactor: cleanup code, remove redundancies, rename variables for clarity * chore: add back filtering and sorting for mcp tools dialog * refactor: initializeServer to return response and early return * refactor: enhance server initialization logic and improve UI for OAuth interaction * chore: clarify warning message for unconfigured MCP server in handleTools * refactor: prevent CustomUserVarsSection from submitting tools dialog form * fix: nested button of button issue in UninitializedMCPTool * feat: add functionality to revoke custom user variables in MCPToolSelectDialog --------- Co-authored-by: Danny Avila <danny@librechat.ai>
2025-08-29 19:57:01 -07:00
const serverStatus = connectionStatus?.[serverName];
if (serverStatus?.connectionState === 'connected') {
connectedServers.push(serverName);
} else {
disconnectedServers.push(serverName);
}
});
setMCPValues(connectedServers);
disconnectedServers.forEach((serverName) => {
initializeServer(serverName);
});
},
[connectionStatus, setMCPValues, initializeServer, isInitializing],
);
const toggleServerSelection = useCallback(
(serverName: string) => {
if (isInitializing(serverName)) {
return;
}
const currentValues = mcpValues ?? [];
const isCurrentlySelected = currentValues.includes(serverName);
if (isCurrentlySelected) {
const filteredValues = currentValues.filter((name) => name !== serverName);
setMCPValues(filteredValues);
} else {
✂️ refactor: MCP UI Separation for Agents (#9237) * refactor: MCP UI Separation for Agents (Dustin WIP) feat: separate MCPs into their own lists away from tools + actions and add the status indicator functionality from chat to their dropdown ui fix: spotify mcp was not persisting on agent creation feat: show disconnected saved servers and their tools in agent mcp list in created agents fix: select-all regression fixed (caused by deleting tools we were drawing from for rendering list) fix: dont show all mcps, only those installed in agent in list feat: separate ToolSelectDialog for MCPServerTools fix: uninitialized mcp servers not showing as added in toolselectdialog refactor: reduce looping in AgentPanelContext for categorizing groups and mcps refactor: split ToolSelectDialog and MCPToolSelectDialog functionality (still needs customization for custom user vars) chore: address ESLint comments chore: address ESLint comments feat: one-click initialization on MCP servers in agent builder fix: stop propagation triggering reinit on caret click refactor: split uninitialized MCPs component from initialized MCPs feat: new mcp tool select dialog ui with custom user vars feat: show initialization state for CUV configurable MCPs too chore: remove unused localization string fix: deselecting all tools caused a re-render fix: remove subtools so removal from MCPToolSelectDialog works more consistently feat: added servers have all tools enabled by default feat: mcp server list now alphabetical to prevent annoying ui behavior of servers jumping around depending on tool selection fix: filter out placeholder group mcp tools from any actual tool calls / definitions feat: indicator now takes you to config dialog for uninitialized servers feat: show previously configured mcp servers that are now missing from the yaml feat: select all enabled by default on first add to mcp server list chore: address ESLint comments * refactor: MCP UI Separation for Agents (Danny WIP) chore: remove use of `{serverName}_mcp_{serverName}` chore: import order WIP: separate component concerns refactor: streamline agent mcp tools refactor: unify MCP server handling and improve tool visibility logic, remove unnecessary normalization or sorting, remove nesting button, make variable names clear refactor: rename mcpServerIds to mcpServerNames for clarity and consistency across components refactor: remove groupedMCPTools and toolToServerMap, streamline MCP server handling in context and components to effectively utilize mcpServersMap refactor: optimize tool selection logic by replacing array includes with Set for improved performance chore: add error logging for failed auth URL parsing in ToolCall component refactor: enhance MCP tool handling by improving server name management and updating UI elements for better clarity * refactor: decouple connection status from useMCPServerManager with useMCPConnectionStatus * fix: improve MCP tool validation logic to handle unconfigured servers * chore: enhance log message clarity for MCP server disconnection in updateUserPluginsController * refactor: simplify connection status extraction in useMCPConnectionStatus hook * refactor: improve initializing UX * chore: replace string literal with ResourceType constant in useResourcePermissions * refactor: cleanup code, remove redundancies, rename variables for clarity * chore: add back filtering and sorting for mcp tools dialog * refactor: initializeServer to return response and early return * refactor: enhance server initialization logic and improve UI for OAuth interaction * chore: clarify warning message for unconfigured MCP server in handleTools * refactor: prevent CustomUserVarsSection from submitting tools dialog form * fix: nested button of button issue in UninitializedMCPTool * feat: add functionality to revoke custom user variables in MCPToolSelectDialog --------- Co-authored-by: Danny Avila <danny@librechat.ai>
2025-08-29 19:57:01 -07:00
const serverStatus = connectionStatus?.[serverName];
if (serverStatus?.connectionState === 'connected') {
setMCPValues([...currentValues, serverName]);
} else {
initializeServer(serverName);
}
}
},
[mcpValues, setMCPValues, connectionStatus, initializeServer, isInitializing],
);
const handleConfigSave = useCallback(
(targetName: string, authData: Record<string, string>) => {
if (selectedToolForConfig && selectedToolForConfig.name === 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) {
const payload: TUpdateUserPlugins = {
pluginKey: `${Constants.mcp_prefix}${targetName}`,
action: 'uninstall',
auth: {},
};
updateUserPluginsMutation.mutate(payload);
const currentValues = mcpValues ?? [];
const filteredValues = currentValues.filter((name) => name !== targetName);
setMCPValues(filteredValues);
}
},
[selectedToolForConfig, updateUserPluginsMutation, mcpValues, setMCPValues],
);
📦 chore: Bump MCP SDK: Fix Types and MCP OAuth due to Update (#10811) * chore: Bump @modelcontextprotocol/sdk to version 1.24.3 * refactor: Update resource handling in MCP parsers and types - Simplified resource text checks in `parseAsString` and `formatToolContent` functions to ensure proper existence checks. - Removed unnecessary resource name and description handling to streamline output. - Updated type definitions in `index.ts` to align with the new structure from `@modelcontextprotocol/sdk`, enhancing type safety and clarity. - Added `logo_uri` and `tos_uri` properties to `MCPOAuthHandler` for improved OAuth metadata support. * refactor: Update custom endpoint configurations and type definitions - Removed unused type imports and streamlined the custom parameters handling in `loadCustomEndpointsConfig`. - Adjusted the `TCustomEndpointsConfig` type to utilize `TConfig` instead of `TEndpoint`, enhancing type accuracy. - Made the endpoint schema optional in the configuration to improve flexibility. * fix: Implement token cleanup and error handling for invalid OAuth tokens - Added `cleanupInvalidTokens` method to remove invalid OAuth tokens from storage when detected. - Introduced `isInvalidTokenError` method to identify errors indicating revoked or expired tokens. - Integrated token cleanup logic into the connection attempt process to ensure fresh OAuth flow on invalid token detection. * feat: Add revoke OAuth functionality in Server Initialization - Introduced a new button to revoke OAuth for servers, enhancing user control over OAuth permissions. - Updated the `useMCPServerManager` hook to include a standalone `revokeOAuthForServer` function for managing OAuth revocation. - Adjusted the UI to conditionally render the revoke button based on server requirements. * fix: error handling for authentication in MCPConnection - Updated the error handling logic in MCPConnection to better identify various authentication error indicators, including 401 status, invalid tokens, and unauthorized messages. - Removed the deprecated cleanupInvalidTokens method and integrated its logic into the connection attempt process for improved clarity and efficiency. - Adjusted the MCPConnectionFactory to streamline the connection attempt process and handle OAuth errors more effectively. * refactor: Update button rendering in ServerInitializationSection - Removed the existing button for server initialization and replaced it with a new button implementation, maintaining the same functionality. - Ensured consistent rendering of the button within the component's layout. * chore: update resource type usage in parsers.test.ts
2025-12-04 19:52:32 -05:00
/** Standalone revoke function for OAuth servers - doesn't require selectedToolForConfig */
const revokeOAuthForServer = useCallback(
(serverName: string) => {
const payload: TUpdateUserPlugins = {
pluginKey: `${Constants.mcp_prefix}${serverName}`,
action: 'uninstall',
auth: {},
};
updateUserPluginsMutation.mutate(payload);
},
[updateUserPluginsMutation],
);
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);
if (!open && previousFocusRef.current) {
setTimeout(() => {
if (previousFocusRef.current && typeof previousFocusRef.current.focus === 'function') {
previousFocusRef.current.focus();
}
previousFocusRef.current = null;
}, 0);
}
}, []);
const getServerStatusIconProps = useCallback(
(serverName: string) => {
const mcpData = queryClient.getQueryData<MCPServersResponse | undefined>([
QueryKeys.mcpTools,
]);
const serverData = mcpData?.servers?.[serverName];
✂️ refactor: MCP UI Separation for Agents (#9237) * refactor: MCP UI Separation for Agents (Dustin WIP) feat: separate MCPs into their own lists away from tools + actions and add the status indicator functionality from chat to their dropdown ui fix: spotify mcp was not persisting on agent creation feat: show disconnected saved servers and their tools in agent mcp list in created agents fix: select-all regression fixed (caused by deleting tools we were drawing from for rendering list) fix: dont show all mcps, only those installed in agent in list feat: separate ToolSelectDialog for MCPServerTools fix: uninitialized mcp servers not showing as added in toolselectdialog refactor: reduce looping in AgentPanelContext for categorizing groups and mcps refactor: split ToolSelectDialog and MCPToolSelectDialog functionality (still needs customization for custom user vars) chore: address ESLint comments chore: address ESLint comments feat: one-click initialization on MCP servers in agent builder fix: stop propagation triggering reinit on caret click refactor: split uninitialized MCPs component from initialized MCPs feat: new mcp tool select dialog ui with custom user vars feat: show initialization state for CUV configurable MCPs too chore: remove unused localization string fix: deselecting all tools caused a re-render fix: remove subtools so removal from MCPToolSelectDialog works more consistently feat: added servers have all tools enabled by default feat: mcp server list now alphabetical to prevent annoying ui behavior of servers jumping around depending on tool selection fix: filter out placeholder group mcp tools from any actual tool calls / definitions feat: indicator now takes you to config dialog for uninitialized servers feat: show previously configured mcp servers that are now missing from the yaml feat: select all enabled by default on first add to mcp server list chore: address ESLint comments * refactor: MCP UI Separation for Agents (Danny WIP) chore: remove use of `{serverName}_mcp_{serverName}` chore: import order WIP: separate component concerns refactor: streamline agent mcp tools refactor: unify MCP server handling and improve tool visibility logic, remove unnecessary normalization or sorting, remove nesting button, make variable names clear refactor: rename mcpServerIds to mcpServerNames for clarity and consistency across components refactor: remove groupedMCPTools and toolToServerMap, streamline MCP server handling in context and components to effectively utilize mcpServersMap refactor: optimize tool selection logic by replacing array includes with Set for improved performance chore: add error logging for failed auth URL parsing in ToolCall component refactor: enhance MCP tool handling by improving server name management and updating UI elements for better clarity * refactor: decouple connection status from useMCPServerManager with useMCPConnectionStatus * fix: improve MCP tool validation logic to handle unconfigured servers * chore: enhance log message clarity for MCP server disconnection in updateUserPluginsController * refactor: simplify connection status extraction in useMCPConnectionStatus hook * refactor: improve initializing UX * chore: replace string literal with ResourceType constant in useResourcePermissions * refactor: cleanup code, remove redundancies, rename variables for clarity * chore: add back filtering and sorting for mcp tools dialog * refactor: initializeServer to return response and early return * refactor: enhance server initialization logic and improve UI for OAuth interaction * chore: clarify warning message for unconfigured MCP server in handleTools * refactor: prevent CustomUserVarsSection from submitting tools dialog form * fix: nested button of button issue in UninitializedMCPTool * feat: add functionality to revoke custom user variables in MCPToolSelectDialog --------- Co-authored-by: Danny Avila <danny@librechat.ai>
2025-08-29 19:57:01 -07:00
const serverStatus = connectionStatus?.[serverName];
const serverConfig = loadedServers?.[serverName];
const handleConfigClick = (e: React.MouseEvent) => {
e.stopPropagation();
e.preventDefault();
previousFocusRef.current = document.activeElement as HTMLElement;
/** Minimal TPlugin object for the config dialog */
const configTool: TPlugin = {
name: serverName,
pluginKey: `${Constants.mcp_prefix}${serverName}`,
authConfig:
serverData?.authConfig ||
(serverConfig?.customUserVars
? Object.entries(serverConfig.customUserVars).map(([key, config]) => ({
authField: key,
label: config.title,
description: config.description,
}))
: []),
authenticated: serverData?.authenticated ?? false,
};
setSelectedToolForConfig(configTool);
setIsConfigModalOpen(true);
};
const handleCancelClick = (e: React.MouseEvent) => {
e.stopPropagation();
e.preventDefault();
cancelOAuthFlow(serverName);
};
const hasCustomUserVars =
serverConfig?.customUserVars && Object.keys(serverConfig.customUserVars).length > 0;
return {
serverName,
serverStatus,
tool: serverData
? ({
name: serverName,
pluginKey: `${Constants.mcp_prefix}${serverName}`,
icon: serverData.icon,
authenticated: serverData.authenticated,
} as TPlugin)
: undefined,
onConfigClick: handleConfigClick,
isInitializing: isInitializing(serverName),
canCancel: isCancellable(serverName),
onCancel: handleCancelClick,
hasCustomUserVars,
};
},
[queryClient, isCancellable, isInitializing, cancelOAuthFlow, connectionStatus, loadedServers],
);
const getConfigDialogProps = useCallback(() => {
if (!selectedToolForConfig) return null;
const fieldsSchema: Record<string, ConfigFieldDetail> = {};
if (selectedToolForConfig?.authConfig) {
selectedToolForConfig.authConfig.forEach((field) => {
fieldsSchema[field.authField] = {
title: field.label || field.authField,
description: field.description,
};
});
}
const initialValues: Record<string, string> = {};
if (selectedToolForConfig?.authConfig) {
selectedToolForConfig.authConfig.forEach((field) => {
initialValues[field.authField] = '';
});
}
return {
serverName: selectedToolForConfig.name,
✂️ refactor: MCP UI Separation for Agents (#9237) * refactor: MCP UI Separation for Agents (Dustin WIP) feat: separate MCPs into their own lists away from tools + actions and add the status indicator functionality from chat to their dropdown ui fix: spotify mcp was not persisting on agent creation feat: show disconnected saved servers and their tools in agent mcp list in created agents fix: select-all regression fixed (caused by deleting tools we were drawing from for rendering list) fix: dont show all mcps, only those installed in agent in list feat: separate ToolSelectDialog for MCPServerTools fix: uninitialized mcp servers not showing as added in toolselectdialog refactor: reduce looping in AgentPanelContext for categorizing groups and mcps refactor: split ToolSelectDialog and MCPToolSelectDialog functionality (still needs customization for custom user vars) chore: address ESLint comments chore: address ESLint comments feat: one-click initialization on MCP servers in agent builder fix: stop propagation triggering reinit on caret click refactor: split uninitialized MCPs component from initialized MCPs feat: new mcp tool select dialog ui with custom user vars feat: show initialization state for CUV configurable MCPs too chore: remove unused localization string fix: deselecting all tools caused a re-render fix: remove subtools so removal from MCPToolSelectDialog works more consistently feat: added servers have all tools enabled by default feat: mcp server list now alphabetical to prevent annoying ui behavior of servers jumping around depending on tool selection fix: filter out placeholder group mcp tools from any actual tool calls / definitions feat: indicator now takes you to config dialog for uninitialized servers feat: show previously configured mcp servers that are now missing from the yaml feat: select all enabled by default on first add to mcp server list chore: address ESLint comments * refactor: MCP UI Separation for Agents (Danny WIP) chore: remove use of `{serverName}_mcp_{serverName}` chore: import order WIP: separate component concerns refactor: streamline agent mcp tools refactor: unify MCP server handling and improve tool visibility logic, remove unnecessary normalization or sorting, remove nesting button, make variable names clear refactor: rename mcpServerIds to mcpServerNames for clarity and consistency across components refactor: remove groupedMCPTools and toolToServerMap, streamline MCP server handling in context and components to effectively utilize mcpServersMap refactor: optimize tool selection logic by replacing array includes with Set for improved performance chore: add error logging for failed auth URL parsing in ToolCall component refactor: enhance MCP tool handling by improving server name management and updating UI elements for better clarity * refactor: decouple connection status from useMCPServerManager with useMCPConnectionStatus * fix: improve MCP tool validation logic to handle unconfigured servers * chore: enhance log message clarity for MCP server disconnection in updateUserPluginsController * refactor: simplify connection status extraction in useMCPConnectionStatus hook * refactor: improve initializing UX * chore: replace string literal with ResourceType constant in useResourcePermissions * refactor: cleanup code, remove redundancies, rename variables for clarity * chore: add back filtering and sorting for mcp tools dialog * refactor: initializeServer to return response and early return * refactor: enhance server initialization logic and improve UI for OAuth interaction * chore: clarify warning message for unconfigured MCP server in handleTools * refactor: prevent CustomUserVarsSection from submitting tools dialog form * fix: nested button of button issue in UninitializedMCPTool * feat: add functionality to revoke custom user variables in MCPToolSelectDialog --------- Co-authored-by: Danny Avila <danny@librechat.ai>
2025-08-29 19:57:01 -07:00
serverStatus: connectionStatus?.[selectedToolForConfig.name],
isOpen: isConfigModalOpen,
onOpenChange: handleDialogOpenChange,
fieldsSchema,
initialValues,
onSave: handleSave,
onRevoke: handleRevoke,
isSubmitting: updateUserPluginsMutation.isLoading,
};
}, [
selectedToolForConfig,
connectionStatus,
isConfigModalOpen,
handleDialogOpenChange,
handleSave,
handleRevoke,
updateUserPluginsMutation.isLoading,
]);
return {
availableMCPServers,
🏗️ 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>
2025-12-04 21:37:23 +01:00
/** MCP servers filtered for chat menu selection (chatMenu !== false && !consumeOnly) */
selectableServers,
availableMCPServersMap: loadedServers,
isLoading,
connectionStatus,
initializeServer,
cancelOAuthFlow,
isInitializing,
isCancellable,
getOAuthUrl,
mcpValues,
setMCPValues,
isPinned,
setIsPinned,
placeholderText,
batchToggleServers,
toggleServerSelection,
localize,
isConfigModalOpen,
handleDialogOpenChange,
selectedToolForConfig,
setSelectedToolForConfig,
handleSave,
handleRevoke,
📦 chore: Bump MCP SDK: Fix Types and MCP OAuth due to Update (#10811) * chore: Bump @modelcontextprotocol/sdk to version 1.24.3 * refactor: Update resource handling in MCP parsers and types - Simplified resource text checks in `parseAsString` and `formatToolContent` functions to ensure proper existence checks. - Removed unnecessary resource name and description handling to streamline output. - Updated type definitions in `index.ts` to align with the new structure from `@modelcontextprotocol/sdk`, enhancing type safety and clarity. - Added `logo_uri` and `tos_uri` properties to `MCPOAuthHandler` for improved OAuth metadata support. * refactor: Update custom endpoint configurations and type definitions - Removed unused type imports and streamlined the custom parameters handling in `loadCustomEndpointsConfig`. - Adjusted the `TCustomEndpointsConfig` type to utilize `TConfig` instead of `TEndpoint`, enhancing type accuracy. - Made the endpoint schema optional in the configuration to improve flexibility. * fix: Implement token cleanup and error handling for invalid OAuth tokens - Added `cleanupInvalidTokens` method to remove invalid OAuth tokens from storage when detected. - Introduced `isInvalidTokenError` method to identify errors indicating revoked or expired tokens. - Integrated token cleanup logic into the connection attempt process to ensure fresh OAuth flow on invalid token detection. * feat: Add revoke OAuth functionality in Server Initialization - Introduced a new button to revoke OAuth for servers, enhancing user control over OAuth permissions. - Updated the `useMCPServerManager` hook to include a standalone `revokeOAuthForServer` function for managing OAuth revocation. - Adjusted the UI to conditionally render the revoke button based on server requirements. * fix: error handling for authentication in MCPConnection - Updated the error handling logic in MCPConnection to better identify various authentication error indicators, including 401 status, invalid tokens, and unauthorized messages. - Removed the deprecated cleanupInvalidTokens method and integrated its logic into the connection attempt process for improved clarity and efficiency. - Adjusted the MCPConnectionFactory to streamline the connection attempt process and handle OAuth errors more effectively. * refactor: Update button rendering in ServerInitializationSection - Removed the existing button for server initialization and replaced it with a new button implementation, maintaining the same functionality. - Ensured consistent rendering of the button within the component's layout. * chore: update resource type usage in parsers.test.ts
2025-12-04 19:52:32 -05:00
revokeOAuthForServer,
getServerStatusIconProps,
getConfigDialogProps,
🏗️ 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>
2025-12-04 21:37:23 +01:00
checkEffectivePermission,
};
}