🏗️ feat: Dynamic MCP Server Infrastructure with Access Control (#10787)

* Feature: Dynamic MCP Server with Full UI Management

* 🚦 feat: Add MCP Connection Status icons to MCPBuilder panel (#10805)

* feature: Add MCP server connection status icons to MCPBuilder panel

* refactor: Simplify MCPConfigDialog rendering in MCPBuilderPanel

---------

Co-authored-by: Atef Bellaaj <slalom.bellaaj@external.daimlertruck.com>
Co-authored-by: Danny Avila <danny@librechat.ai>

* fix: address code review feedback for MCP server management

- Fix OAuth secret preservation to avoid mutating input parameter
  by creating a merged config copy in ServerConfigsDB.update()

- Improve error handling in getResourcePermissionsMap to propagate
  critical errors instead of silently returning empty Map

- Extract duplicated MCP server filter logic by exposing selectableServers
  from useMCPServerManager hook and using it in MCPSelect component

* test: Update PermissionService tests to throw errors on invalid resource types

- Changed the test for handling invalid resource types to ensure it throws an error instead of returning an empty permissions map.
- Updated the expectation to check for the specific error message when an invalid resource type is provided.

* feat: Implement retry logic for MCP server creation to handle race conditions

- Enhanced the createMCPServer method to include retry logic with exponential backoff for handling duplicate key errors during concurrent server creation.
- Updated tests to verify that all concurrent requests succeed and that unique server names are generated.
- Added a helper function to identify MongoDB duplicate key errors, improving error handling during server creation.

* refactor: StatusIcon to use CircleCheck for connected status

- Replaced the PlugZap icon with CircleCheck in the ConnectedStatusIcon component to better represent the connected state.
- Ensured consistent icon usage across the component for improved visual clarity.

* test: Update AccessControlService tests to throw errors on invalid resource types

- Modified the test for invalid resource types to ensure it throws an error with a specific message instead of returning an empty permissions map.
- This change enhances error handling and improves test coverage for the AccessControlService.

* fix: Update error message for missing server name in MCP server retrieval

- Changed the error message returned when the server name is not provided from 'MCP ID is required' to 'Server name is required' for better clarity and accuracy in the API response.

---------

Co-authored-by: Atef Bellaaj <slalom.bellaaj@external.daimlertruck.com>
Co-authored-by: Danny Avila <danny@librechat.ai>
This commit is contained in:
Atef Bellaaj 2025-12-04 21:37:23 +01:00 committed by Danny Avila
parent 41c0a96d39
commit 99f8bd2ce6
No known key found for this signature in database
GPG key ID: BF31EEB2C5CA0956
103 changed files with 7978 additions and 1003 deletions

View file

@ -66,10 +66,16 @@ export function AgentPanelProvider({ children }: { children: React.ReactNode })
if (mcpData?.servers) {
for (const [serverName, serverData] of Object.entries(mcpData.servers)) {
// Get title and description from config with fallbacks
const serverConfig = availableMCPServersMap?.[serverName];
const displayName = serverConfig?.title || serverName;
const displayDescription =
serverConfig?.description || `${localize('com_ui_tool_collection_prefix')} ${serverName}`;
const metadata = {
name: serverName,
name: displayName,
pluginKey: serverName,
description: `${localize('com_ui_tool_collection_prefix')} ${serverName}`,
description: displayDescription,
icon: serverData.icon || '',
authConfig: serverData.authConfig,
authenticated: serverData.authenticated,
@ -91,6 +97,7 @@ export function AgentPanelProvider({ children }: { children: React.ReactNode })
isConfigured: configuredServers.has(serverName),
isConnected: connectionStatus?.[serverName]?.connectionState === 'connected',
metadata,
consumeOnly: serverConfig?.consumeOnly,
});
}
}
@ -100,11 +107,18 @@ export function AgentPanelProvider({ children }: { children: React.ReactNode })
if (serversMap.has(mcpServerName)) {
continue;
}
// Get title and description from config with fallbacks
const serverConfig = availableMCPServersMap?.[mcpServerName];
const displayName = serverConfig?.title || mcpServerName;
const displayDescription =
serverConfig?.description ||
`${localize('com_ui_tool_collection_prefix')} ${mcpServerName}`;
const metadata = {
icon: '',
name: mcpServerName,
icon: serverConfig?.iconPath || '',
name: displayName,
pluginKey: mcpServerName,
description: `${localize('com_ui_tool_collection_prefix')} ${mcpServerName}`,
description: displayDescription,
} as TPlugin;
serversMap.set(mcpServerName, {
@ -113,11 +127,12 @@ export function AgentPanelProvider({ children }: { children: React.ReactNode })
isConfigured: true,
serverName: mcpServerName,
isConnected: connectionStatus?.[mcpServerName]?.connectionState === 'connected',
consumeOnly: serverConfig?.consumeOnly,
});
}
return serversMap;
}, [mcpData, localize, mcpServerNames, connectionStatus]);
}, [mcpData, localize, mcpServerNames, connectionStatus, availableMCPServersMap]);
const value: AgentPanelContextType = {
mcp,

View file

@ -1,31 +0,0 @@
import React, { createContext, useContext, useMemo } from 'react';
import { Constants } from 'librechat-data-provider';
import { useChatContext } from './ChatContext';
interface MCPPanelContextValue {
conversationId: string;
}
const MCPPanelContext = createContext<MCPPanelContextValue | undefined>(undefined);
export function MCPPanelProvider({ children }: { children: React.ReactNode }) {
const { conversation } = useChatContext();
/** Context value only created when conversationId changes */
const contextValue = useMemo<MCPPanelContextValue>(
() => ({
conversationId: conversation?.conversationId ?? Constants.NEW_CONVO,
}),
[conversation?.conversationId],
);
return <MCPPanelContext.Provider value={contextValue}>{children}</MCPPanelContext.Provider>;
}
export function useMCPPanelContext() {
const context = useContext(MCPPanelContext);
if (!context) {
throw new Error('useMCPPanelContext must be used within MCPPanelProvider');
}
return context;
}

View file

@ -24,7 +24,6 @@ export * from './SearchContext';
export * from './BadgeRowContext';
export * from './SidePanelContext';
export * from './DragDropContext';
export * from './MCPPanelContext';
export * from './ArtifactsContext';
export * from './PromptGroupsContext';
export * from './MessagesViewContext';

View file

@ -1,26 +0,0 @@
import {
AuthorizationTypeEnum,
AuthTypeEnum,
TokenExchangeMethodEnum,
} from 'librechat-data-provider';
import { MCPForm } from '~/common/types';
export const defaultMCPFormValues: MCPForm = {
type: AuthTypeEnum.None,
saved_auth_fields: false,
api_key: '',
authorization_type: AuthorizationTypeEnum.Basic,
custom_auth_header: '',
oauth_client_id: '',
oauth_client_secret: '',
authorization_url: '',
client_url: '',
scope: '',
token_exchange_method: TokenExchangeMethodEnum.DefaultPost,
name: '',
description: '',
url: '',
tools: [],
icon: '',
trust: false,
};

View file

@ -153,7 +153,6 @@ export enum Panel {
actions = 'actions',
model = 'model',
version = 'version',
mcp = 'mcp',
}
export type FileSetter =
@ -177,15 +176,6 @@ export type ActionAuthForm = {
token_exchange_method: t.TokenExchangeMethodEnum;
};
export type MCPForm = ActionAuthForm & {
name?: string;
description?: string;
url?: string;
tools?: string[];
icon?: string;
trust?: boolean;
};
export type ActionWithNullableMetadata = Omit<t.Action, 'metadata'> & {
metadata: t.ActionMetadata | null;
};
@ -226,6 +216,7 @@ export interface MCPServerInfo {
tools: t.AgentToolType[];
isConfigured: boolean;
isConnected: boolean;
consumeOnly?: boolean;
metadata: t.TPlugin;
}

View file

@ -1,8 +1,10 @@
import React, { memo, useCallback } from 'react';
import { PermissionTypes, Permissions } from 'librechat-data-provider';
import { MultiSelect, MCPIcon } from '@librechat/client';
import MCPServerStatusIcon from '~/components/MCP/MCPServerStatusIcon';
import MCPConfigDialog from '~/components/MCP/MCPConfigDialog';
import { useBadgeRowContext } from '~/Providers';
import { useHasAccess } from '~/hooks';
function MCPSelectContent() {
const { conversationId, mcpServerManager } = useBadgeRowContext();
@ -15,16 +17,21 @@ function MCPSelectContent() {
batchToggleServers,
getConfigDialogProps,
getServerStatusIconProps,
availableMCPServers,
selectableServers,
} = mcpServerManager;
const renderSelectedValues = useCallback(
(values: string[], placeholder?: string) => {
(
values: string[],
placeholder?: string,
items?: (string | { label: string; value: string })[],
) => {
if (values.length === 0) {
return placeholder || localize('com_ui_select_placeholder');
}
if (values.length === 1) {
return values[0];
const selectedItem = items?.find((i) => typeof i !== 'string' && i.value == values[0]);
return selectedItem && typeof selectedItem !== 'string' ? selectedItem.label : values[0];
}
return localize('com_ui_x_selected', { 0: values.length });
},
@ -74,11 +81,13 @@ function MCPSelectContent() {
}
const configDialogProps = getConfigDialogProps();
return (
<>
<MultiSelect
items={availableMCPServers?.map((s) => s.serverName)}
items={selectableServers.map((s) => ({
label: s.config.title || s.serverName,
value: s.serverName,
}))}
selectedValues={mcpValues ?? []}
setSelectedValues={batchToggleServers}
renderSelectedValues={renderSelectedValues}
@ -99,9 +108,13 @@ function MCPSelectContent() {
function MCPSelect() {
const { mcpServerManager } = useBadgeRowContext();
const { availableMCPServers } = mcpServerManager;
const { selectableServers } = mcpServerManager;
const canUseMcp = useHasAccess({
permissionType: PermissionTypes.MCP_SERVERS,
permission: Permissions.USE,
});
if (!availableMCPServers || availableMCPServers.length === 0) {
if (!canUseMcp || !selectableServers || selectableServers.length === 0) {
return null;
}

View file

@ -112,7 +112,7 @@ const MCPSubMenu = React.forwardRef<HTMLDivElement, MCPSubMenuProps>(
>
<div className="flex flex-grow items-center gap-2">
<Ariakit.MenuItemCheck checked={isSelected} />
<span>{s.serverName}</span>
<span>{s.config.title || s.serverName}</span>
</div>
{statusIcon && <div className="ml-2 flex items-center">{statusIcon}</div>}
</Ariakit.MenuItem>

View file

@ -72,6 +72,11 @@ const ToolsDropdown = ({ disabled }: ToolsDropdownProps) => {
permission: Permissions.USE,
});
const canUseMcp = useHasAccess({
permissionType: PermissionTypes.MCP_SERVERS,
permission: Permissions.USE,
});
const showWebSearchSettings = useMemo(() => {
const authTypes = webSearchAuthData?.authTypes ?? [];
if (authTypes.length === 0) return true;
@ -286,8 +291,8 @@ const ToolsDropdown = ({ disabled }: ToolsDropdownProps) => {
});
}
const { configuredServers } = mcpServerManager;
if (configuredServers && configuredServers.length > 0) {
const { availableMCPServers } = mcpServerManager;
if (canUseMcp && availableMCPServers && availableMCPServers.length > 0) {
dropdownItems.push({
hideOnClick: false,
render: (props) => <MCPSubMenu {...props} placeholder={mcpPlaceholder} />,

View file

@ -1,6 +1,6 @@
import React from 'react';
import { Spinner } from '@librechat/client';
import { SettingsIcon, AlertTriangle, KeyRound, PlugZap, X } from 'lucide-react';
import { Spinner, TooltipAnchor } from '@librechat/client';
import { SettingsIcon, AlertTriangle, KeyRound, PlugZap, X, CircleCheck } from 'lucide-react';
import type { MCPServerStatus, TPlugin } from 'librechat-data-provider';
import { useLocalize } from '~/hooks';
@ -85,7 +85,13 @@ export default function MCPServerStatusIcon({
/>
);
}
return null; // No config button for connected servers without customUserVars
return (
<ConnectedStatusIcon
serverName={serverName}
requiresOAuth={requiresOAuth}
onConfigClick={onConfigClick}
/>
);
}
return null;
@ -192,3 +198,36 @@ function AuthenticatedStatusIcon({
</button>
);
}
interface ConnectedStatusProps {
serverName: string;
requiresOAuth?: boolean;
onConfigClick: (e: React.MouseEvent) => void;
}
function ConnectedStatusIcon({ serverName, requiresOAuth, onConfigClick }: ConnectedStatusProps) {
if (requiresOAuth) {
return (
<TooltipAnchor
role="button"
onClick={onConfigClick}
className="flex h-6 w-6 items-center justify-center rounded p-1 hover:bg-surface-secondary"
aria-label={localize('com_nav_mcp_configure_server', { 0: serverName })}
description={localize('com_nav_mcp_status_connected')}
side="top"
>
<CircleCheck className="h-4 w-4 text-green-500" />
</TooltipAnchor>
);
}
return (
<TooltipAnchor
className="flex h-6 w-6 items-center justify-center rounded p-1"
description={localize('com_nav_mcp_status_connected')}
side="top"
>
<CircleCheck className="h-4 w-4 text-green-500" />
</TooltipAnchor>
);
}

View file

@ -16,9 +16,13 @@ interface PublicSharingToggleProps {
className?: string;
}
const accessDescriptions: Record<ResourceType, 'com_ui_agent' | 'com_ui_prompt'> = {
const accessDescriptions: Record<
ResourceType,
'com_ui_agent' | 'com_ui_prompt' | 'com_ui_mcp_server'
> = {
[ResourceType.AGENT]: 'com_ui_agent',
[ResourceType.PROMPTGROUP]: 'com_ui_prompt',
[ResourceType.MCPSERVER]: 'com_ui_mcp_server',
};
export default function PublicSharingToggle({

View file

@ -312,6 +312,7 @@ export default function AgentConfig() {
setShowMCPToolDialog={setShowMCPToolDialog}
/>
)}
{/* Agent Tools & Actions */}
<div className="mb-4">
<label className={labelClass}>

View file

@ -5,7 +5,6 @@ import VersionPanel from './Version/VersionPanel';
import { useChatContext } from '~/Providers';
import ActionsPanel from './ActionsPanel';
import AgentPanel from './AgentPanel';
import MCPPanel from './MCPPanel';
export default function AgentPanelSwitch() {
return (
@ -32,8 +31,5 @@ function AgentPanelSwitchWithContext() {
if (activePanel === Panel.version) {
return <VersionPanel />;
}
if (activePanel === Panel.mcp) {
return <MCPPanel />;
}
return <AgentPanel />;
}

View file

@ -1,295 +0,0 @@
import { useState, useEffect } from 'react';
import { useFormContext, Controller } from 'react-hook-form';
import { Label, Checkbox, Spinner, useToastContext } from '@librechat/client';
import type { MCP } from 'librechat-data-provider';
import MCPAuth from '~/components/SidePanel/Builder/MCPAuth';
import MCPIcon from '~/components/SidePanel/Agents/MCPIcon';
import { MCPForm } from '~/common/types';
import { useLocalize } from '~/hooks';
function useUpdateAgentMCP({
onSuccess,
onError,
}: {
onSuccess: (data: [string, MCP]) => void;
onError: (error: Error) => void;
}) {
return {
mutate: async ({
mcp_id,
metadata,
agent_id,
}: {
mcp_id?: string;
metadata: MCP['metadata'];
agent_id: string;
}) => {
try {
// TODO: Implement MCP endpoint
onSuccess(['success', { mcp_id, metadata, agent_id } as MCP]);
} catch (error) {
onError(error as Error);
}
},
isLoading: false,
};
}
interface MCPInputProps {
mcp?: MCP;
agent_id?: string;
setMCP: React.Dispatch<React.SetStateAction<MCP | undefined>>;
}
export default function MCPInput({ mcp, agent_id, setMCP }: MCPInputProps) {
const localize = useLocalize();
const { showToast } = useToastContext();
const {
handleSubmit,
register,
formState: { errors },
control,
} = useFormContext<MCPForm>();
const [isLoading, setIsLoading] = useState(false);
const [showTools, setShowTools] = useState(false);
const [selectedTools, setSelectedTools] = useState<string[]>([]);
// Initialize tools list if editing existing MCP
useEffect(() => {
if (mcp?.mcp_id && mcp.metadata.tools) {
setShowTools(true);
setSelectedTools(mcp.metadata.tools);
}
}, [mcp]);
const updateAgentMCP = useUpdateAgentMCP({
onSuccess(data) {
showToast({
message: localize('com_ui_update_mcp_success'),
status: 'success',
});
setMCP(data[1]);
setShowTools(true);
setSelectedTools(data[1].metadata.tools ?? []);
setIsLoading(false);
},
onError(error) {
showToast({
message: (error as Error).message || localize('com_ui_update_mcp_error'),
status: 'error',
});
setIsLoading(false);
},
});
const saveMCP = handleSubmit(async (data: MCPForm) => {
setIsLoading(true);
try {
const response = await updateAgentMCP.mutate({
agent_id: agent_id ?? '',
mcp_id: mcp?.mcp_id,
metadata: {
...data,
tools: selectedTools,
},
});
setMCP(response[1]);
showToast({
message: localize('com_ui_update_mcp_success'),
status: 'success',
});
} catch {
showToast({
message: localize('com_ui_update_mcp_error'),
status: 'error',
});
} finally {
setIsLoading(false);
}
});
const handleSelectAll = () => {
if (mcp?.metadata.tools) {
setSelectedTools(mcp.metadata.tools);
}
};
const handleDeselectAll = () => {
setSelectedTools([]);
};
const handleToolToggle = (tool: string) => {
setSelectedTools((prev) =>
prev.includes(tool) ? prev.filter((t) => t !== tool) : [...prev, tool],
);
};
const handleToggleAll = () => {
if (selectedTools.length === mcp?.metadata.tools?.length) {
handleDeselectAll();
} else {
handleSelectAll();
}
};
const handleIconChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (file) {
const reader = new FileReader();
reader.onloadend = () => {
const base64String = reader.result as string;
setMCP({
mcp_id: mcp?.mcp_id ?? '',
agent_id: agent_id ?? '',
metadata: {
...mcp?.metadata,
icon: base64String,
},
});
};
reader.readAsDataURL(file);
}
};
return (
<div className="flex flex-col gap-4">
{/* Icon Picker */}
<div className="mb-4">
<MCPIcon icon={mcp?.metadata.icon} onIconChange={handleIconChange} />
</div>
{/* name, description, url */}
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-2">
<Label htmlFor="name">{localize('com_ui_name')}</Label>
<input
id="name"
{...register('name', { required: true })}
className="border-token-border-medium flex h-9 w-full rounded-lg border bg-transparent px-3 py-1.5 text-sm outline-none placeholder:text-text-secondary-alt focus:ring-1 focus:ring-border-light"
placeholder={localize('com_agents_mcp_name_placeholder')}
/>
{errors.name && (
<span className="text-xs text-red-500">{localize('com_ui_field_required')}</span>
)}
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="description">
{localize('com_ui_description')}
<span className="ml-1 text-xs text-text-secondary-alt">
{localize('com_ui_optional')}
</span>
</Label>
<input
id="description"
{...register('description')}
className="border-token-border-medium flex h-9 w-full rounded-lg border bg-transparent px-3 py-1.5 text-sm outline-none placeholder:text-text-secondary-alt focus:ring-1 focus:ring-border-light"
placeholder={localize('com_agents_mcp_description_placeholder')}
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="url">{localize('com_ui_mcp_url')}</Label>
<input
id="url"
{...register('url', {
required: true,
})}
className="border-token-border-medium flex h-9 w-full rounded-lg border bg-transparent px-3 py-1.5 text-sm outline-none placeholder:text-text-secondary-alt focus:ring-1 focus:ring-border-light"
placeholder={'https://mcp.example.com'}
/>
{errors.url && (
<span className="text-xs text-red-500">
{errors.url.type === 'required'
? localize('com_ui_field_required')
: errors.url.message}
</span>
)}
</div>
<MCPAuth />
<div className="my-2 flex items-center gap-2">
<Controller
name="trust"
control={control}
rules={{ required: true }}
render={({ field }) => (
<Checkbox
id="trust-checkbox"
checked={field.value}
onCheckedChange={field.onChange}
aria-labelledby="trust-label"
/>
)}
/>
<Label id="trust-label" htmlFor="trust-checkbox" className="flex flex-col">
{localize('com_ui_trust_app')}
<span className="text-xs text-text-secondary">
{localize('com_agents_mcp_trust_subtext')}
</span>
</Label>
</div>
{errors.trust && (
<span className="text-xs text-red-500">{localize('com_ui_field_required')}</span>
)}
</div>
<div className="flex items-center justify-end">
<button
onClick={saveMCP}
disabled={isLoading}
className="focus:shadow-outline mt-1 flex min-w-[100px] items-center justify-center rounded bg-green-500 px-4 py-2 font-semibold text-white hover:bg-green-400 focus:border-green-500 focus:outline-none focus:ring-0 disabled:bg-green-400"
type="button"
>
{(() => {
if (isLoading) {
return <Spinner className="icon-md" />;
}
return mcp?.mcp_id ? localize('com_ui_update') : localize('com_ui_create');
})()}
</button>
</div>
{showTools && mcp?.metadata.tools && (
<div className="mt-4 flex flex-col gap-4">
<div className="flex items-center justify-between">
<h3 className="text-token-text-primary block font-medium">
{localize('com_ui_available_tools')}
</h3>
<button
onClick={handleToggleAll}
type="button"
className="btn btn-neutral border-token-border-light relative h-8 rounded-full px-4 font-medium"
>
{selectedTools.length === mcp.metadata.tools.length
? localize('com_ui_deselect_all')
: localize('com_ui_select_all')}
</button>
</div>
<div className="flex flex-col gap-2">
{mcp.metadata.tools.map((tool) => (
<label
key={tool}
htmlFor={tool}
className="border-token-border-light hover:bg-token-surface-secondary flex cursor-pointer items-center rounded-lg border p-2"
>
<Checkbox
id={tool}
checked={selectedTools.includes(tool)}
onCheckedChange={() => handleToolToggle(tool)}
className="relative float-left mr-2 inline-flex h-4 w-4 cursor-pointer"
aria-label={tool
.split('_')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ')}
/>
<span className="text-token-text-primary">
{tool
.split('_')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ')}
</span>
</label>
))}
</div>
</div>
)}
</div>
);
}

View file

@ -1,175 +0,0 @@
import { useEffect } from 'react';
import { ChevronLeft } from 'lucide-react';
import { useForm, FormProvider } from 'react-hook-form';
import {
AuthTypeEnum,
AuthorizationTypeEnum,
TokenExchangeMethodEnum,
} from 'librechat-data-provider';
import {
Label,
OGDialog,
TrashIcon,
OGDialogTrigger,
useToastContext,
OGDialogTemplate,
} from '@librechat/client';
import type { MCPForm } from '~/common';
import { useAgentPanelContext } from '~/Providers/AgentPanelContext';
import { defaultMCPFormValues } from '~/common/mcp';
import { Panel, isEphemeralAgent } from '~/common';
import { useLocalize } from '~/hooks';
import MCPInput from './MCPInput';
function useDeleteAgentMCP({
onSuccess,
onError,
}: {
onSuccess: () => void;
onError: (error: Error) => void;
}) {
return {
mutate: async ({ mcp_id, agent_id }: { mcp_id: string; agent_id: string }) => {
try {
console.log('Mock delete MCP:', { mcp_id, agent_id });
onSuccess();
} catch (error) {
onError(error as Error);
}
},
};
}
export default function MCPPanel() {
const localize = useLocalize();
const { showToast } = useToastContext();
const { mcp, setMcp, agent_id, setActivePanel } = useAgentPanelContext();
const deleteAgentMCP = useDeleteAgentMCP({
onSuccess: () => {
showToast({
message: localize('com_ui_delete_mcp_success'),
status: 'success',
});
setActivePanel(Panel.builder);
setMcp(undefined);
},
onError(error) {
showToast({
message: (error as Error).message ?? localize('com_ui_delete_mcp_error'),
status: 'error',
});
},
});
const methods = useForm<MCPForm>({
defaultValues: defaultMCPFormValues,
mode: 'onChange',
});
const { reset } = methods;
useEffect(() => {
if (mcp) {
const formData = {
icon: mcp.metadata.icon ?? '',
name: mcp.metadata.name ?? '',
description: mcp.metadata.description ?? '',
url: mcp.metadata.url ?? '',
tools: mcp.metadata.tools ?? [],
trust: mcp.metadata.trust ?? false,
};
if (mcp.metadata.auth) {
Object.assign(formData, {
type: mcp.metadata.auth.type || AuthTypeEnum.None,
saved_auth_fields: false,
api_key: mcp.metadata.api_key ?? '',
authorization_type: mcp.metadata.auth.authorization_type || AuthorizationTypeEnum.Basic,
oauth_client_id: mcp.metadata.oauth_client_id ?? '',
oauth_client_secret: mcp.metadata.oauth_client_secret ?? '',
authorization_url: mcp.metadata.auth.authorization_url ?? '',
client_url: mcp.metadata.auth.client_url ?? '',
scope: mcp.metadata.auth.scope ?? '',
token_exchange_method:
mcp.metadata.auth.token_exchange_method ?? TokenExchangeMethodEnum.DefaultPost,
});
}
reset(formData);
}
}, [mcp, reset]);
return (
<FormProvider {...methods}>
<form className="h-full grow overflow-hidden">
<div className="h-full overflow-auto px-2 pb-12 text-sm">
<div className="relative flex flex-col items-center px-16 py-6 text-center">
<div className="absolute left-0 top-6">
<button
type="button"
className="btn btn-neutral relative"
onClick={() => {
setActivePanel(Panel.builder);
setMcp(undefined);
}}
>
<div className="flex w-full items-center justify-center gap-2">
<ChevronLeft />
</div>
</button>
</div>
{!!mcp && (
<OGDialog>
<OGDialogTrigger asChild>
<div className="absolute right-0 top-6">
<button
type="button"
disabled={isEphemeralAgent(agent_id) || !mcp.mcp_id}
className="btn btn-neutral border-token-border-light relative h-9 rounded-lg font-medium"
>
<TrashIcon className="text-red-500" />
</button>
</div>
</OGDialogTrigger>
<OGDialogTemplate
showCloseButton={false}
title={localize('com_ui_delete_mcp')}
className="max-w-[450px]"
main={
<Label className="text-left text-sm font-medium">
{localize('com_ui_delete_mcp_confirm')}
</Label>
}
selection={{
selectHandler: () => {
if (isEphemeralAgent(agent_id)) {
return showToast({
message: localize('com_agents_no_agent_id_error'),
status: 'error',
});
}
deleteAgentMCP.mutate({
mcp_id: mcp.mcp_id,
agent_id: agent_id || '',
});
},
selectClasses:
'bg-red-700 dark:bg-red-600 hover:bg-red-800 dark:hover:bg-red-800 transition-color duration-200 text-white',
selectText: localize('com_ui_delete'),
}}
/>
</OGDialog>
)}
<div className="text-xl font-medium">
{mcp ? localize('com_ui_edit_mcp_server') : localize('com_ui_add_mcp_server')}
</div>
<div className="text-xs text-text-secondary">{localize('com_agents_mcp_info')}</div>
</div>
<MCPInput mcp={mcp} agent_id={agent_id} setMCP={setMcp} />
</div>
</form>
</FormProvider>
);
}

View file

@ -1,57 +0,0 @@
import { useCallback } from 'react';
import { useLocalize } from '~/hooks';
import { useToastContext } from '@librechat/client';
import { useAgentPanelContext } from '~/Providers/AgentPanelContext';
import MCP from '~/components/SidePanel/Builder/MCP';
import { Panel, isEphemeralAgent } from '~/common';
export default function MCPSection() {
const localize = useLocalize();
const { showToast } = useToastContext();
const { mcps = [], agent_id, setMcp, setActivePanel } = useAgentPanelContext();
const handleAddMCP = useCallback(() => {
if (isEphemeralAgent(agent_id)) {
showToast({
message: localize('com_agents_mcps_disabled'),
status: 'warning',
});
return;
}
setActivePanel(Panel.mcp);
}, [agent_id, setActivePanel, showToast, localize]);
return (
<div className="mb-4">
<label className="text-token-text-primary mb-2 block font-medium">
{localize('com_ui_mcp_servers')}
</label>
<div className="space-y-2">
{mcps
.filter((mcp) => mcp.agent_id === agent_id)
.map((mcp, i) => (
<MCP
key={i}
mcp={mcp}
onClick={() => {
setMcp(mcp);
setActivePanel(Panel.mcp);
}}
/>
))}
<div className="flex space-x-2">
<button
type="button"
onClick={handleAddMCP}
className="btn btn-neutral border-token-border-light relative h-9 w-full rounded-lg font-medium"
aria-haspopup="dialog"
>
<div className="flex w-full items-center justify-center gap-2">
{localize('com_ui_add_mcp')}
</div>
</button>
</div>
</div>
</div>
);
}

View file

@ -2,8 +2,9 @@ import React from 'react';
import UninitializedMCPTool from './UninitializedMCPTool';
import UnconfiguredMCPTool from './UnconfiguredMCPTool';
import { useAgentPanelContext } from '~/Providers';
import { useLocalize } from '~/hooks';
import { useHasAccess, useLocalize } from '~/hooks';
import MCPTool from './MCPTool';
import { PermissionTypes, Permissions } from 'librechat-data-provider';
export default function MCPTools({
agentId,
@ -16,7 +17,13 @@ export default function MCPTools({
}) {
const localize = useLocalize();
const { mcpServersMap } = useAgentPanelContext();
const hasMcpAccess = useHasAccess({
permissionType: PermissionTypes.MCP_SERVERS,
permission: Permissions.USE,
});
if (!hasMcpAccess) {
return null;
}
return (
<div className="mb-4">
<label className="text-token-text-primary mb-2 block font-medium">

View file

@ -1,213 +0,0 @@
import React, { useState, useCallback } from 'react';
import { ChevronLeft, Trash2 } from 'lucide-react';
import { useQueryClient } from '@tanstack/react-query';
import { Button, useToastContext } from '@librechat/client';
import { Constants, QueryKeys } from 'librechat-data-provider';
import { useUpdateUserPluginsMutation } from 'librechat-data-provider/react-query';
import type { TUpdateUserPlugins } from 'librechat-data-provider';
import ServerInitializationSection from '~/components/MCP/ServerInitializationSection';
import CustomUserVarsSection from '~/components/MCP/CustomUserVarsSection';
import { MCPPanelProvider, useMCPPanelContext } from '~/Providers';
import { useLocalize, useMCPServerManager } from '~/hooks';
import MCPPanelSkeleton from './MCPPanelSkeleton';
function MCPPanelContent() {
const localize = useLocalize();
const queryClient = useQueryClient();
const { showToast } = useToastContext();
const { conversationId } = useMCPPanelContext();
const { availableMCPServers, isLoading, connectionStatus } = useMCPServerManager({
conversationId,
});
const [selectedServerNameForEditing, setSelectedServerNameForEditing] = useState<string | null>(
null,
);
const updateUserPluginsMutation = useUpdateUserPluginsMutation({
onSuccess: async () => {
showToast({ message: localize('com_nav_mcp_vars_updated'), status: 'success' });
await Promise.all([
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',
});
},
});
const handleServerClickToEdit = (serverName: string) => {
setSelectedServerNameForEditing(serverName);
};
const handleGoBackToList = () => {
setSelectedServerNameForEditing(null);
};
const handleConfigSave = useCallback(
(targetName: string, authData: Record<string, string>) => {
console.log(
`[MCP Panel] Saving config for ${targetName}, pluginKey: ${`${Constants.mcp_prefix}${targetName}`}`,
);
const payload: TUpdateUserPlugins = {
pluginKey: `${Constants.mcp_prefix}${targetName}`,
action: 'install',
auth: authData,
};
updateUserPluginsMutation.mutate(payload);
},
[updateUserPluginsMutation],
);
const handleConfigRevoke = useCallback(
(targetName: string) => {
const payload: TUpdateUserPlugins = {
pluginKey: `${Constants.mcp_prefix}${targetName}`,
action: 'uninstall',
auth: {},
};
updateUserPluginsMutation.mutate(payload);
},
[updateUserPluginsMutation],
);
if (isLoading) {
return <MCPPanelSkeleton />;
}
if (availableMCPServers.length === 0) {
return (
<div className="p-4 text-center text-sm text-gray-500">
{localize('com_sidepanel_mcp_no_servers_with_vars')}
</div>
);
}
if (selectedServerNameForEditing) {
// Editing View
const serverBeingEdited = availableMCPServers.find(
(s) => s.serverName === selectedServerNameForEditing,
);
if (!serverBeingEdited) {
// Fallback to list view if server not found
setSelectedServerNameForEditing(null);
return (
<div className="p-4 text-center text-sm text-gray-500">
{localize('com_ui_error')}: {localize('com_ui_mcp_server_not_found')}
</div>
);
}
const serverStatus = connectionStatus?.[selectedServerNameForEditing];
const isConnected = serverStatus?.connectionState === 'connected';
return (
<div className="h-auto max-w-full space-y-4 overflow-x-hidden py-2">
<Button
variant="outline"
onClick={handleGoBackToList}
size="sm"
aria-label={localize('com_ui_back')}
>
<ChevronLeft className="mr-1 h-4 w-4" aria-hidden="true" />
{localize('com_ui_back')}
</Button>
<div className="mb-4">
<CustomUserVarsSection
serverName={selectedServerNameForEditing}
fields={serverBeingEdited.config.customUserVars || {}}
onSave={(authData) => {
if (selectedServerNameForEditing) {
handleConfigSave(selectedServerNameForEditing, authData);
}
}}
onRevoke={() => {
if (selectedServerNameForEditing) {
handleConfigRevoke(selectedServerNameForEditing);
}
}}
isSubmitting={updateUserPluginsMutation.isLoading}
/>
</div>
<ServerInitializationSection
sidePanel={true}
conversationId={conversationId}
serverName={selectedServerNameForEditing}
requiresOAuth={serverStatus?.requiresOAuth || false}
hasCustomUserVars={
serverBeingEdited.config.customUserVars &&
Object.keys(serverBeingEdited.config.customUserVars).length > 0
}
/>
{serverStatus?.requiresOAuth && isConnected && (
<Button
className="w-full"
size="sm"
variant="destructive"
onClick={() => handleConfigRevoke(selectedServerNameForEditing)}
aria-label={localize('com_ui_oauth_revoke')}
>
<Trash2 className="h-4 w-4" aria-hidden="true" />
{localize('com_ui_oauth_revoke')}
</Button>
)}
</div>
);
} else {
// Server List View
return (
<div className="h-auto max-w-full overflow-x-hidden py-2">
<div className="space-y-2">
{availableMCPServers.map((server) => {
const serverStatus = connectionStatus?.[server.serverName];
const isConnected = serverStatus?.connectionState === 'connected';
return (
<div key={server.serverName} className="flex items-center gap-2">
<Button
variant="outline"
className="flex-1 justify-start dark:hover:bg-gray-700"
onClick={() => handleServerClickToEdit(server.serverName)}
aria-label={localize('com_ui_edit_server', { serverName: server.serverName })}
>
<div className="flex items-center gap-2">
<span>{server.serverName}</span>
{serverStatus && (
<span
className={`rounded-xl px-2 py-0.5 text-xs ${
isConnected
? 'bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300'
: 'bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300'
}`}
>
{serverStatus.connectionState}
</span>
)}
</div>
</Button>
</div>
);
})}
</div>
</div>
);
}
}
export default function MCPPanel() {
return (
<MCPPanelProvider>
<MCPPanelContent />
</MCPPanelProvider>
);
}

View file

@ -1,21 +0,0 @@
import React from 'react';
import { Skeleton } from '@librechat/client';
export default function MCPPanelSkeleton() {
return (
<div className="space-y-6 p-2">
{[1, 2].map((serverIdx) => (
<div key={serverIdx} className="space-y-4">
<Skeleton className="h-6 w-1/3 rounded-lg" /> {/* Server Name */}
{[1, 2].map((varIdx) => (
<div key={varIdx} className="space-y-2">
<Skeleton className="h-5 w-1/4 rounded-lg" /> {/* Variable Title */}
<Skeleton className="h-8 w-full rounded-lg" /> {/* Input Field */}
<Skeleton className="h-4 w-2/3 rounded-lg" /> {/* Description */}
</div>
))}
</div>
))}
</div>
);
}

View file

@ -0,0 +1,231 @@
import { useMemo, useEffect, useState } from 'react';
import * as Ariakit from '@ariakit/react';
import { ShieldEllipsis } from 'lucide-react';
import { useForm, Controller } from 'react-hook-form';
import { Permissions, SystemRoles, roleDefaults, PermissionTypes } from 'librechat-data-provider';
import {
Button,
Switch,
OGDialog,
DropdownPopup,
OGDialogTitle,
OGDialogContent,
OGDialogTrigger,
useToastContext,
} from '@librechat/client';
import type { Control, UseFormSetValue, UseFormGetValues } from 'react-hook-form';
import { useUpdateMCPServersPermissionsMutation } from '~/data-provider';
import { useLocalize, useAuthContext } from '~/hooks';
type FormValues = Record<Permissions, boolean>;
type LabelControllerProps = {
label: string;
mcpServersPerm: Permissions;
control: Control<FormValues, unknown, FormValues>;
setValue: UseFormSetValue<FormValues>;
getValues: UseFormGetValues<FormValues>;
};
const LabelController: React.FC<LabelControllerProps> = ({
control,
mcpServersPerm,
label,
getValues,
setValue,
}) => (
<div className="mb-4 flex items-center justify-between gap-2">
<button
className="cursor-pointer select-none"
type="button"
onClick={() =>
setValue(mcpServersPerm, !getValues(mcpServersPerm), {
shouldDirty: true,
})
}
tabIndex={0}
>
{label}
</button>
<Controller
name={mcpServersPerm}
control={control}
render={({ field }) => (
<Switch
{...field}
checked={field.value}
onCheckedChange={field.onChange}
value={field.value?.toString()}
/>
)}
/>
</div>
);
const MCPAdminSettings = () => {
const localize = useLocalize();
const { showToast } = useToastContext();
const { user, roles } = useAuthContext();
const { mutate, isLoading } = useUpdateMCPServersPermissionsMutation({
onSuccess: () => {
showToast({ status: 'success', message: localize('com_ui_saved') });
},
onError: () => {
showToast({ status: 'error', message: localize('com_ui_error_save_admin_settings') });
},
});
const [isRoleMenuOpen, setIsRoleMenuOpen] = useState(false);
const [selectedRole, setSelectedRole] = useState<SystemRoles>(SystemRoles.USER);
const defaultValues = useMemo(() => {
const rolePerms = roles?.[selectedRole]?.permissions;
if (rolePerms) {
return rolePerms[PermissionTypes.MCP_SERVERS];
}
return roleDefaults[selectedRole].permissions[PermissionTypes.MCP_SERVERS];
}, [roles, selectedRole]);
const {
reset,
control,
setValue,
getValues,
handleSubmit,
formState: { isSubmitting },
} = useForm<FormValues>({
mode: 'onChange',
defaultValues,
});
useEffect(() => {
const value = roles?.[selectedRole]?.permissions?.[PermissionTypes.MCP_SERVERS];
if (value) {
reset(value);
} else {
reset(roleDefaults[selectedRole].permissions[PermissionTypes.MCP_SERVERS]);
}
}, [roles, selectedRole, reset]);
if (user?.role !== SystemRoles.ADMIN) {
return null;
}
const labelControllerData = [
{
mcpServersPerm: Permissions.USE,
label: localize('com_ui_mcp_servers_allow_use'),
},
{
mcpServersPerm: Permissions.CREATE,
label: localize('com_ui_mcp_servers_allow_create'),
},
{
mcpServersPerm: Permissions.SHARE,
label: localize('com_ui_mcp_servers_allow_share'),
},
];
const onSubmit = (data: FormValues) => {
mutate({ roleName: selectedRole, updates: data });
};
const roleDropdownItems = [
{
label: SystemRoles.USER,
onClick: () => {
setSelectedRole(SystemRoles.USER);
},
},
{
label: SystemRoles.ADMIN,
onClick: () => {
setSelectedRole(SystemRoles.ADMIN);
},
},
];
return (
<OGDialog>
<OGDialogTrigger asChild>
<Button
size={'sm'}
variant={'outline'}
className="btn btn-neutral border-token-border-light relative h-9 w-full gap-1 rounded-lg font-medium"
>
<ShieldEllipsis className="cursor-pointer" aria-hidden="true" />
{localize('com_ui_admin_settings')}
</Button>
</OGDialogTrigger>
<OGDialogContent className="border-border-light bg-surface-primary text-text-primary lg:w-1/4">
<OGDialogTitle>{`${localize('com_ui_admin_settings')} - ${localize(
'com_ui_mcp_servers',
)}`}</OGDialogTitle>
<div className="p-2">
{/* Role selection dropdown */}
<div className="flex items-center gap-2">
<span className="font-medium">{localize('com_ui_role_select')}:</span>
<DropdownPopup
unmountOnHide={true}
menuId="role-dropdown"
isOpen={isRoleMenuOpen}
setIsOpen={setIsRoleMenuOpen}
trigger={
<Ariakit.MenuButton className="inline-flex w-1/4 items-center justify-center rounded-lg border border-border-light bg-transparent px-2 py-1 text-text-primary transition-all ease-in-out hover:bg-surface-tertiary">
{selectedRole}
</Ariakit.MenuButton>
}
items={roleDropdownItems}
itemClassName="items-center justify-center"
sameWidth={true}
/>
</div>
{/* Permissions form */}
<form onSubmit={handleSubmit(onSubmit)}>
<div className="py-5">
{labelControllerData.map(({ mcpServersPerm, label }) => (
<div key={mcpServersPerm}>
<LabelController
control={control}
mcpServersPerm={mcpServersPerm}
label={label}
getValues={getValues}
setValue={setValue}
/>
{selectedRole === SystemRoles.ADMIN && mcpServersPerm === Permissions.USE && (
<>
<div className="mb-2 max-w-full whitespace-normal break-words text-sm text-red-600">
<span>{localize('com_ui_admin_access_warning')}</span>
{'\n'}
<a
href="https://www.librechat.ai/docs/configuration/librechat_yaml/object_structure/interface"
target="_blank"
rel="noreferrer"
className="text-blue-500 underline"
>
{localize('com_ui_more_info')}
</a>
</div>
</>
)}
</div>
))}
</div>
<div className="flex justify-end">
<button
type="button"
onClick={handleSubmit(onSubmit)}
disabled={isSubmitting || isLoading}
className="btn rounded bg-green-500 font-bold text-white transition-all hover:bg-green-600"
>
{localize('com_ui_save')}
</button>
</div>
</form>
</div>
</OGDialogContent>
</OGDialog>
);
};
export default MCPAdminSettings;

View file

@ -0,0 +1,408 @@
import { useState } from 'react';
import { FormProvider, useForm, useFormContext } from 'react-hook-form';
import * as RadioGroup from '@radix-ui/react-radio-group';
import { Copy, CopyCheck } from 'lucide-react';
import {
OGDialog,
OGDialogTrigger,
OGDialogTemplate,
Button,
useToastContext,
} from '@librechat/client';
import { TranslationKeys, useLocalize, useCopyToClipboard } from '~/hooks';
import { cn } from '~/utils';
enum AuthTypeEnum {
None = 'none',
ServiceHttp = 'service_http',
OAuth = 'oauth',
}
enum AuthorizationTypeEnum {
Basic = 'basic',
Bearer = 'bearer',
Custom = 'custom',
}
// Auth configuration type
export interface AuthConfig {
auth_type?: AuthTypeEnum;
api_key?: string;
api_key_authorization_type?: AuthorizationTypeEnum;
api_key_custom_header?: string;
oauth_client_id?: string;
oauth_client_secret?: string;
oauth_authorization_url?: string;
oauth_token_url?: string;
oauth_scope?: string;
server_id?: string; // For edit mode redirect URI
}
// Export enums for parent components
export { AuthTypeEnum, AuthorizationTypeEnum };
/**
* Returns the appropriate localization key for authentication type
*/
function getAuthLocalizationKey(type: AuthTypeEnum): TranslationKeys {
switch (type) {
case AuthTypeEnum.ServiceHttp:
return 'com_ui_api_key';
case AuthTypeEnum.OAuth:
return 'com_ui_oauth';
default:
return 'com_ui_none';
}
}
/**
* OAuth and API Key authentication dialog for MCP Server Builder
* Self-contained controlled component with its own form state
* Only updates parent on Save, discards changes on Cancel
*/
export default function MCPAuth({
value,
onChange,
}: {
value: AuthConfig;
onChange: (config: AuthConfig) => void;
}) {
const localize = useLocalize();
const [openAuthDialog, setOpenAuthDialog] = useState(false);
// Create local form with current value as default
const methods = useForm<AuthConfig>({
defaultValues: value,
});
const { handleSubmit, watch, reset } = methods;
const authType = watch('auth_type') || AuthTypeEnum.None;
const inputClasses = cn(
'mb-2 h-9 w-full resize-none overflow-y-auto rounded-lg border px-3 py-2 text-sm',
'border-border-medium bg-surface-primary outline-none',
'focus:ring-2 focus:ring-ring',
);
// Reset form when dialog opens with latest value from parent
const handleDialogOpen = (open: boolean) => {
if (open) {
reset(value);
}
setOpenAuthDialog(open);
};
// Save: update parent and close
const handleSave = handleSubmit((formData) => {
onChange(formData);
setOpenAuthDialog(false);
});
return (
<OGDialog open={openAuthDialog} onOpenChange={handleDialogOpen}>
<OGDialogTrigger asChild>
<div className="relative mb-4">
<div className="mb-1.5 flex items-center">
<label className="text-token-text-primary block font-medium">
{localize('com_ui_authentication')}
</label>
</div>
<div className="border-token-border-medium flex rounded-lg border text-sm hover:cursor-pointer">
<div className="h-9 grow px-3 py-2">{localize(getAuthLocalizationKey(authType))}</div>
<div className="bg-token-border-medium w-px"></div>
<button type="button" color="neutral" className="flex items-center gap-2 px-3">
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
className="icon-sm"
>
<path
d="M11.6439 3C10.9352 3 10.2794 3.37508 9.92002 3.98596L9.49644 4.70605C8.96184 5.61487 7.98938 6.17632 6.93501 6.18489L6.09967 6.19168C5.39096 6.19744 4.73823 6.57783 4.38386 7.19161L4.02776 7.80841C3.67339 8.42219 3.67032 9.17767 4.01969 9.7943L4.43151 10.5212C4.95127 11.4386 4.95127 12.5615 4.43151 13.4788L4.01969 14.2057C3.67032 14.8224 3.67339 15.5778 4.02776 16.1916L4.38386 16.8084C4.73823 17.4222 5.39096 17.8026 6.09966 17.8083L6.93502 17.8151C7.98939 17.8237 8.96185 18.3851 9.49645 19.294L9.92002 20.014C10.2794 20.6249 10.9352 21 11.6439 21H12.3561C13.0648 21 13.7206 20.6249 14.08 20.014L14.5035 19.294C15.0381 18.3851 16.0106 17.8237 17.065 17.8151L17.9004 17.8083C18.6091 17.8026 19.2618 17.4222 19.6162 16.8084L19.9723 16.1916C20.3267 15.5778 20.3298 14.8224 19.9804 14.2057L19.5686 13.4788C19.0488 12.5615 19.0488 11.4386 19.5686 10.5212L19.9804 9.7943C20.3298 9.17767 20.3267 8.42219 19.9723 7.80841L19.6162 7.19161C19.2618 6.57783 18.6091 6.19744 17.9004 6.19168L17.065 6.18489C16.0106 6.17632 15.0382 5.61487 14.5036 4.70605L14.08 3.98596C13.7206 3.37508 13.0648 3 12.3561 3H11.6439Z"
stroke="currentColor"
strokeWidth="2"
strokeLinejoin="round"
/>
<circle cx="12" cy="12" r="2.5" stroke="currentColor" strokeWidth="2" />
</svg>
</button>
</div>
</div>
</OGDialogTrigger>
<FormProvider {...methods}>
<OGDialogTemplate
title={localize('com_ui_authentication')}
showCloseButton={false}
className="w-full max-w-md"
main={
<div className="space-y-4">
<div>
<label className="mb-1 block text-sm font-medium">
{localize('com_ui_authentication_type')}
</label>
<RadioGroup.Root
defaultValue={AuthTypeEnum.None}
onValueChange={(value) =>
methods.setValue('auth_type', value as AuthConfig['auth_type'])
}
value={authType}
role="radiogroup"
aria-required="false"
dir="ltr"
className="flex gap-4"
style={{ outline: 'none' }}
>
<div className="flex items-center gap-2">
<label htmlFor="auth-none" className="flex cursor-pointer items-center gap-1">
<RadioGroup.Item
type="button"
role="radio"
value={AuthTypeEnum.None}
id="auth-none"
className={cn(
'mr-1 flex h-5 w-5 items-center justify-center rounded-full border',
'border-border-heavy bg-surface-primary',
)}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-text-primary" />
</RadioGroup.Item>
{localize('com_ui_none')}
</label>
</div>
{/*
TODO Support API keys for auth
<div className="flex items-center gap-2">
<label htmlFor="auth-apikey" className="flex cursor-pointer items-center gap-1">
<RadioGroup.Item
type="button"
role="radio"
value={AuthTypeEnum.ServiceHttp}
id="auth-apikey"
className={cn(
'mr-1 flex h-5 w-5 items-center justify-center rounded-full border',
'border-border-heavy bg-surface-primary',
)}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-text-primary" />
</RadioGroup.Item>
{localize('com_ui_api_key')}
</label>
</div> */}
<div className="flex items-center gap-2">
<label htmlFor="auth-oauth" className="flex cursor-pointer items-center gap-1">
<RadioGroup.Item
type="button"
role="radio"
value={AuthTypeEnum.OAuth}
id="auth-oauth"
className={cn(
'mr-1 flex h-5 w-5 items-center justify-center rounded-full border',
'border-border-heavy bg-surface-primary',
)}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-text-primary" />
</RadioGroup.Item>
{localize('com_ui_oauth')}
</label>
</div>
</RadioGroup.Root>
</div>
{authType === AuthTypeEnum.None && null}
{authType === AuthTypeEnum.ServiceHttp && <ApiKey inputClasses={inputClasses} />}
{authType === AuthTypeEnum.OAuth && <OAuth inputClasses={inputClasses} />}
</div>
}
buttons={
<Button type="button" variant="submit" onClick={handleSave} className="text-white">
{localize('com_ui_save')}
</Button>
}
/>
</FormProvider>
</OGDialog>
);
}
const ApiKey = ({ inputClasses }: { inputClasses: string }) => {
const localize = useLocalize();
const { register, watch, setValue } = useFormContext();
const authorization_type = watch('api_key_authorization_type') || AuthorizationTypeEnum.Basic;
return (
<>
<label className="mb-1 block text-sm font-medium">{localize('com_ui_api_key')}</label>
<input
placeholder="<HIDDEN>"
type="password"
autoComplete="new-password"
className={inputClasses}
{...register('api_key')}
/>
<label className="mb-1 block text-sm font-medium">{localize('com_ui_auth_type')}</label>
<RadioGroup.Root
defaultValue={AuthorizationTypeEnum.Basic}
onValueChange={(value) => setValue('api_key_authorization_type', value)}
value={authorization_type}
role="radiogroup"
aria-required="true"
dir="ltr"
className="mb-2 flex gap-6 overflow-hidden rounded-lg"
style={{ outline: 'none' }}
>
<div className="flex items-center gap-2">
<label htmlFor="auth-basic" className="flex cursor-pointer items-center gap-1">
<RadioGroup.Item
type="button"
role="radio"
value={AuthorizationTypeEnum.Basic}
id="auth-basic"
className={cn(
'mr-1 flex h-5 w-5 items-center justify-center rounded-full border',
'border-border-heavy bg-surface-primary',
)}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-text-primary" />
</RadioGroup.Item>
{localize('com_ui_basic')}
</label>
</div>
<div className="flex items-center gap-2">
<label htmlFor="auth-bearer" className="flex cursor-pointer items-center gap-1">
<RadioGroup.Item
type="button"
role="radio"
value={AuthorizationTypeEnum.Bearer}
id="auth-bearer"
className={cn(
'mr-1 flex h-5 w-5 items-center justify-center rounded-full border',
'border-border-heavy bg-surface-primary',
)}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-text-primary" />
</RadioGroup.Item>
{localize('com_ui_bearer')}
</label>
</div>
<div className="flex items-center gap-2">
<label htmlFor="auth-custom" className="flex cursor-pointer items-center gap-1">
<RadioGroup.Item
type="button"
role="radio"
value={AuthorizationTypeEnum.Custom}
id="auth-custom"
className={cn(
'mr-1 flex h-5 w-5 items-center justify-center rounded-full border',
'border-border-heavy bg-surface-primary',
)}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-text-primary" />
</RadioGroup.Item>
{localize('com_ui_custom')}
</label>
</div>
</RadioGroup.Root>
{authorization_type === AuthorizationTypeEnum.Custom && (
<div className="mt-2">
<label className="mb-1 block text-sm font-medium">
{localize('com_ui_custom_header_name')}
</label>
<input
className={inputClasses}
placeholder="X-Api-Key"
{...register('api_key_custom_header')}
/>
</div>
)}
</>
);
};
const OAuth = ({ inputClasses }: { inputClasses: string }) => {
const localize = useLocalize();
const { showToast } = useToastContext();
const { register, watch } = useFormContext();
const [isCopying, setIsCopying] = useState(false);
// Check if we're in edit mode (server exists with ID)
const serverId = watch('server_id');
const isEditMode = !!serverId;
// Calculate redirect URI for edit mode
const redirectUri = isEditMode
? `${window.location.origin}/api/mcp/${serverId}/oauth/callback`
: '';
const copyLink = useCopyToClipboard({ text: redirectUri });
return (
<>
<label className="mb-1 block text-sm font-medium">{localize('com_ui_client_id')}</label>
<input
placeholder="<HIDDEN>"
type="password"
autoComplete="new-password"
className={inputClasses}
{...register('oauth_client_id')}
/>
<label className="mb-1 block text-sm font-medium">{localize('com_ui_client_secret')}</label>
<input
placeholder="<HIDDEN>"
type="password"
autoComplete="new-password"
className={inputClasses}
{...register('oauth_client_secret')}
/>
<label className="mb-1 block text-sm font-medium">{localize('com_ui_auth_url')}</label>
<input className={inputClasses} {...register('oauth_authorization_url')} />
<label className="mb-1 block text-sm font-medium">{localize('com_ui_token_url')}</label>
<input className={inputClasses} {...register('oauth_token_url')} />
{/* Redirect URI - read-only in edit mode, info message in create mode */}
<label className="mb-1 block text-sm font-medium">{localize('com_ui_redirect_uri')}</label>
{isEditMode ? (
<div className="relative mb-2 flex items-center">
<div className="border-token-border-medium bg-token-surface-primary hover:border-token-border-hover flex h-10 w-full rounded-lg border">
<div className="flex-1 overflow-hidden">
<div className="relative w-full">
<input
type="text"
readOnly
value={redirectUri}
className="w-full border-0 bg-transparent px-3 py-2 pr-12 text-sm text-text-secondary-alt focus:outline-none"
style={{ direction: 'rtl' }}
/>
</div>
</div>
<div className="absolute right-0 flex h-full items-center pr-1">
<Button
size="sm"
variant="ghost"
type="button"
onClick={() => {
if (isCopying) {
return;
}
showToast({ message: localize('com_ui_copied_to_clipboard') });
copyLink(setIsCopying);
}}
className={cn('h-8 rounded-md px-2', isCopying ? 'cursor-default' : '')}
aria-label={localize('com_ui_copy_link')}
>
{isCopying ? <CopyCheck className="size-4" /> : <Copy className="size-4" />}
</Button>
</div>
</div>
</div>
) : (
<div className="mb-2 rounded-lg border border-border-medium bg-surface-secondary p-2">
<p className="text-xs text-text-secondary">{localize('com_ui_redirect_uri_info')}</p>
</div>
)}
<label className="mb-1 block text-sm font-medium">{localize('com_ui_scope')}</label>
<input className={inputClasses} {...register('oauth_scope')} />
</>
);
};

View file

@ -0,0 +1,63 @@
import { useState, useRef } from 'react';
import { Plus } from 'lucide-react';
import { PermissionTypes, Permissions } from 'librechat-data-provider';
import { Button, Spinner, OGDialogTrigger } from '@librechat/client';
import { useLocalize, useMCPServerManager, useHasAccess } from '~/hooks';
import MCPServerList from './MCPServerList';
import MCPServerDialog from './MCPServerDialog';
import MCPConfigDialog from '~/components/MCP/MCPConfigDialog';
import MCPAdminSettings from './MCPAdminSettings';
export default function MCPBuilderPanel() {
const localize = useLocalize();
const { availableMCPServers, isLoading, getServerStatusIconProps, getConfigDialogProps } =
useMCPServerManager();
const hasCreateAccess = useHasAccess({
permissionType: PermissionTypes.MCP_SERVERS,
permission: Permissions.CREATE,
});
const [showDialog, setShowDialog] = useState(false);
const addButtonRef = useRef<HTMLButtonElement | null>(null);
const configDialogProps = getConfigDialogProps();
return (
<div className="flex h-full w-full flex-col overflow-hidden">
<div role="region" aria-label="MCP Builder" className="mt-2 space-y-2">
{/* Admin Settings Button */}
<MCPAdminSettings />
{hasCreateAccess && (
<MCPServerDialog open={showDialog} onOpenChange={setShowDialog} triggerRef={addButtonRef}>
<OGDialogTrigger asChild>
<div className="flex w-full justify-end">
<Button
ref={addButtonRef}
variant="outline"
className="w-full bg-transparent"
onClick={() => setShowDialog(true)}
>
<Plus className="size-4" aria-hidden />
{localize('com_ui_add_mcp')}
</Button>
</div>
</OGDialogTrigger>
</MCPServerDialog>
)}
{/* Server List */}
{isLoading ? (
<div className="flex items-center justify-center p-8">
<Spinner className="h-6 w-6" />
</div>
) : (
<MCPServerList
servers={availableMCPServers}
getServerStatusIconProps={getServerStatusIconProps}
/>
)}
{configDialogProps && <MCPConfigDialog {...configDialogProps} />}
</div>
</div>
);
}

View file

@ -0,0 +1,639 @@
import React, { useState, useEffect, useMemo } from 'react';
import { FormProvider, useForm, Controller } from 'react-hook-form';
import * as RadioGroup from '@radix-ui/react-radio-group';
import type { MCPServerCreateParams } from 'librechat-data-provider';
import {
OGDialog,
OGDialogTemplate,
OGDialogContent,
OGDialogHeader,
OGDialogTitle,
TrashIcon,
Button,
Label,
Checkbox,
Spinner,
useToastContext,
} from '@librechat/client';
import {
useCreateMCPServerMutation,
useUpdateMCPServerMutation,
useDeleteMCPServerMutation,
} from '~/data-provider/MCP';
import MCPAuth, { type AuthConfig, AuthTypeEnum, AuthorizationTypeEnum } from './MCPAuth';
import MCPIcon from '~/components/SidePanel/Agents/MCPIcon';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
import {
SystemRoles,
Permissions,
ResourceType,
PermissionBits,
PermissionTypes,
} from 'librechat-data-provider';
import { GenericGrantAccessDialog } from '~/components/Sharing';
import { useAuthContext, useHasAccess, useResourcePermissions, MCPServerDefinition } from '~/hooks';
// Form data with nested auth structure matching AuthConfig
interface MCPServerFormData {
// Server metadata
title: string;
description?: string;
icon?: string;
// Connection details
url: string;
type: 'streamable-http' | 'sse';
// Nested auth configuration (matches AuthConfig directly)
auth: AuthConfig;
// UI-only validation
trust: boolean;
}
interface MCPServerDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
children: React.ReactNode;
triggerRef?: React.MutableRefObject<HTMLButtonElement | null>;
server?: MCPServerDefinition | null;
}
export default function MCPServerDialog({
open,
onOpenChange,
children,
triggerRef,
server,
}: MCPServerDialogProps) {
const localize = useLocalize();
const { showToast } = useToastContext();
// Mutations
const createMutation = useCreateMCPServerMutation();
const updateMutation = useUpdateMCPServerMutation();
const deleteMutation = useDeleteMCPServerMutation();
// Convert McpServer to form data
const defaultValues = useMemo<MCPServerFormData>(() => {
if (server) {
// Determine auth type from server config
let authType: AuthTypeEnum = AuthTypeEnum.None;
if (server.config.oauth) {
authType = AuthTypeEnum.OAuth;
} else if ('api_key' in server.config) {
authType = AuthTypeEnum.ServiceHttp;
}
return {
title: server.config.title || '',
description: server.config.description || '',
url: 'url' in server.config ? server.config.url : '',
type: (server.config.type as 'streamable-http' | 'sse') || 'streamable-http',
icon: server.config.iconPath || '',
auth: {
auth_type: authType,
api_key: '',
api_key_authorization_type: AuthorizationTypeEnum.Basic,
api_key_custom_header: '',
oauth_client_id: server.config.oauth?.client_id || '',
oauth_client_secret: '', // NEVER pre-fill secrets
oauth_authorization_url: server.config.oauth?.authorization_url || '',
oauth_token_url: server.config.oauth?.token_url || '',
oauth_scope: server.config.oauth?.scope || '',
server_id: server.serverName, // For edit mode redirect URI
},
trust: true, // Pre-check for existing servers
};
}
return {
title: '',
description: '',
url: '',
type: 'streamable-http',
icon: '',
auth: {
auth_type: AuthTypeEnum.None,
api_key: '',
api_key_authorization_type: AuthorizationTypeEnum.Basic,
api_key_custom_header: '',
oauth_client_id: '',
oauth_client_secret: '',
oauth_authorization_url: '',
oauth_token_url: '',
oauth_scope: '',
},
trust: false,
};
}, [server]);
const methods = useForm<MCPServerFormData>({
defaultValues,
});
const {
handleSubmit,
register,
formState: { errors },
control,
watch,
reset,
} = methods;
const iconValue = watch('icon');
const [isSubmitting, setIsSubmitting] = useState(false);
const [showRedirectUriDialog, setShowRedirectUriDialog] = useState(false);
const [createdServerId, setCreatedServerId] = useState<string | null>(null);
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
// Reset form when dialog opens or server changes
useEffect(() => {
if (open) {
reset(defaultValues);
}
// eslint-disable-next-line react-hooks/exhaustive-deps -- defaultValues is derived from server
}, [open, server, reset]);
const handleIconChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (file) {
const reader = new FileReader();
reader.onloadend = () => {
const base64String = reader.result as string;
methods.setValue('icon', base64String);
};
reader.readAsDataURL(file);
}
};
const handleDelete = async () => {
if (!server) {
return;
}
setIsDeleting(true);
try {
await deleteMutation.mutateAsync(server.serverName);
showToast({
message: localize('com_ui_mcp_server_deleted'),
status: 'success',
});
setShowDeleteConfirm(false);
onOpenChange(false);
setTimeout(() => {
triggerRef?.current?.focus();
}, 0);
} catch (error: any) {
let errorMessage = localize('com_ui_error');
if (error && typeof error === 'object' && 'response' in error) {
const axiosError = error as any;
if (axiosError.response?.data?.error) {
errorMessage = axiosError.response.data.error;
}
} else if (error.message) {
errorMessage = error.message;
}
showToast({
message: errorMessage,
status: 'error',
});
} finally {
setIsDeleting(false);
}
};
const onSubmit = handleSubmit(async (formData: MCPServerFormData) => {
setIsSubmitting(true);
try {
// Convert form data to API params - everything goes in config now
const config: any = {
type: formData.type,
url: formData.url,
title: formData.title,
...(formData.description && { description: formData.description }),
...(formData.icon && { iconPath: formData.icon }),
};
// Add OAuth if auth type is oauth and any fields are filled
if (
formData.auth.auth_type === AuthTypeEnum.OAuth &&
(formData.auth.oauth_client_id ||
formData.auth.oauth_client_secret ||
formData.auth.oauth_authorization_url ||
formData.auth.oauth_token_url ||
formData.auth.oauth_scope)
) {
config.oauth = {};
if (formData.auth.oauth_client_id) {
config.oauth.client_id = formData.auth.oauth_client_id;
}
if (formData.auth.oauth_client_secret) {
config.oauth.client_secret = formData.auth.oauth_client_secret;
}
if (formData.auth.oauth_authorization_url) {
config.oauth.authorization_url = formData.auth.oauth_authorization_url;
}
if (formData.auth.oauth_token_url) {
config.oauth.token_url = formData.auth.oauth_token_url;
}
if (formData.auth.oauth_scope) {
config.oauth.scope = formData.auth.oauth_scope;
}
}
const params: MCPServerCreateParams = {
config,
};
// Call mutation based on create vs edit mode
const result = server
? await updateMutation.mutateAsync({ serverName: server.serverName, data: params })
: await createMutation.mutateAsync(params);
showToast({
message: server
? localize('com_ui_mcp_server_updated')
: localize('com_ui_mcp_server_created'),
status: 'success',
});
// Show redirect URI dialog only on creation with OAuth
if (!server && formData.auth.auth_type === AuthTypeEnum.OAuth) {
setCreatedServerId(result.serverName);
setShowRedirectUriDialog(true);
} else {
onOpenChange(false);
}
setTimeout(() => {
triggerRef?.current?.focus();
}, 0);
} catch (error: any) {
let errorMessage = localize('com_ui_error');
if (error && typeof error === 'object' && 'response' in error) {
const axiosError = error as any;
if (axiosError.response?.data?.error) {
errorMessage = axiosError.response.data.error;
}
} else if (error.message) {
errorMessage = error.message;
}
showToast({
message: errorMessage,
status: 'error',
});
} finally {
setIsSubmitting(false);
}
});
const { user } = useAuthContext();
// Check global permission to share MCP servers
const hasAccessToShareMcpServers = useHasAccess({
permissionType: PermissionTypes.MCP_SERVERS,
permission: Permissions.SHARE,
});
// Check user's permissions on this specific MCP server
const { hasPermission, isLoading: permissionsLoading } = useResourcePermissions(
ResourceType.MCPSERVER,
server?.dbId || '',
);
const canShareThisServer = hasPermission(PermissionBits.SHARE);
const shouldShowShareButton =
server && // Only in edit mode
(user?.role === SystemRoles.ADMIN || canShareThisServer) &&
hasAccessToShareMcpServers &&
!permissionsLoading;
const redirectUri = createdServerId
? `${window.location.origin}/api/mcp/${createdServerId}/oauth/callback`
: '';
return (
<>
{/* Delete confirmation dialog */}
<OGDialog
open={showDeleteConfirm}
onOpenChange={(open) => {
setShowDeleteConfirm(open);
}}
>
<OGDialogTemplate
title={localize('com_ui_delete')}
className="max-w-[450px]"
main={
<Label className="text-left text-sm font-medium">
{localize('com_ui_mcp_server_delete_confirm')}
</Label>
}
selection={{
selectHandler: handleDelete,
selectClasses:
'bg-destructive text-white transition-all duration-200 hover:bg-destructive/80',
selectText: isDeleting ? <Spinner /> : localize('com_ui_delete'),
}}
/>
</OGDialog>
{/* Post-creation redirect URI dialog */}
<OGDialog
open={showRedirectUriDialog}
onOpenChange={(open) => {
setShowRedirectUriDialog(open);
if (!open) {
onOpenChange(false);
setCreatedServerId(null);
}
}}
>
<OGDialogContent className="w-full max-w-lg border-none bg-surface-primary text-text-primary">
<OGDialogHeader className="border-b border-border-light sm:p-3">
<OGDialogTitle>{localize('com_ui_mcp_server_created')}</OGDialogTitle>
</OGDialogHeader>
<div className="p-4 sm:p-6 sm:pt-4">
<p className="mb-4 text-sm text-text-primary">
{localize('com_ui_redirect_uri_instructions')}
</p>
<div className="rounded-lg border border-border-medium bg-surface-secondary p-3">
<label className="mb-2 block text-xs font-medium text-text-secondary">
{localize('com_ui_redirect_uri')}
</label>
<div className="flex items-center gap-2">
<input
className="flex-1 rounded border border-border-medium bg-surface-primary px-3 py-2 text-sm"
value={redirectUri}
readOnly
/>
<Button
onClick={() => {
navigator.clipboard.writeText(redirectUri);
showToast({
message: localize('com_ui_copied'),
status: 'success',
});
}}
variant="outline"
className="whitespace-nowrap"
>
{localize('com_ui_copy_link')}
</Button>
</div>
</div>
<div className="mt-6 flex justify-end">
<Button
onClick={() => {
setShowRedirectUriDialog(false);
onOpenChange(false);
setCreatedServerId(null);
}}
variant="submit"
className="text-white"
>
{localize('com_ui_done')}
</Button>
</div>
</div>
</OGDialogContent>
</OGDialog>
{/* Main MCP Server Dialog */}
<OGDialog open={open} onOpenChange={onOpenChange} triggerRef={triggerRef}>
{children}
<OGDialogTemplate
title={server ? localize('com_ui_edit_mcp_server') : localize('com_ui_add_mcp_server')}
description={
server
? localize('com_ui_edit_mcp_server_dialog_description', {
serverName: server.serverName,
})
: undefined
}
className="w-11/12 md:max-w-2xl"
main={
<FormProvider {...methods}>
<div className="max-h-[60vh] space-y-4 overflow-y-auto px-1">
{/* Icon Picker */}
<div>
<MCPIcon icon={iconValue} onIconChange={handleIconChange} />
</div>
{/* Title */}
<div className="space-y-2">
<Label htmlFor="title" className="text-sm font-medium">
{localize('com_ui_name')} <span className="text-red-500">*</span>
</Label>
<input
autoComplete="off"
{...register('title', {
required: true,
pattern: {
value: /^[a-zA-Z0-9 ]+$/,
message: localize('com_ui_mcp_title_invalid'),
},
})}
className="border-token-border-medium flex h-9 w-full rounded-lg border bg-transparent px-3 py-1.5 text-sm outline-none placeholder:text-text-secondary-alt focus:ring-1 focus:ring-border-light"
placeholder={localize('com_agents_mcp_name_placeholder')}
/>
{errors.title && (
<span className="text-xs text-red-500">
{errors.title.type === 'pattern'
? errors.title.message
: localize('com_ui_field_required')}
</span>
)}
</div>
{/* Description */}
<div className="space-y-2">
<Label htmlFor="description" className="text-sm font-medium">
{localize('com_ui_description')}
<span className="ml-1 text-xs text-text-secondary-alt">
{localize('com_ui_optional')}
</span>
</Label>
<input
id="description"
{...register('description')}
className="border-token-border-medium flex h-9 w-full rounded-lg border bg-transparent px-3 py-1.5 text-sm outline-none placeholder:text-text-secondary-alt focus:ring-1 focus:ring-border-light"
placeholder={localize('com_agents_mcp_description_placeholder')}
/>
</div>
{/* URL */}
<div className="space-y-2">
<Label htmlFor="url" className="text-sm font-medium">
{localize('com_ui_mcp_url')} <span className="text-red-500">*</span>
</Label>
<input
id="url"
{...register('url', {
required: true,
})}
className="border-token-border-medium flex h-9 w-full rounded-lg border bg-transparent px-3 py-1.5 text-sm outline-none placeholder:text-text-secondary-alt focus:ring-1 focus:ring-border-light"
placeholder="https://mcp.example.com"
/>
{errors.url && (
<span className="text-xs text-red-500">
{errors.url.type === 'required'
? localize('com_ui_field_required')
: errors.url.message}
</span>
)}
</div>
{/* Server Type */}
<div className="space-y-2">
<Label htmlFor="type" className="text-sm font-medium">
{localize('com_ui_mcp_server_type')}
</Label>
<Controller
name="type"
control={control}
render={({ field }) => (
<RadioGroup.Root
value={field.value}
onValueChange={field.onChange}
className="flex gap-4"
>
<div className="flex items-center gap-2">
<label
htmlFor="type-streamable-http"
className="flex cursor-pointer items-center gap-1"
>
<RadioGroup.Item
type="button"
value="streamable-http"
id="type-streamable-http"
className={cn(
'mr-1 flex h-5 w-5 items-center justify-center rounded-full border',
'border-border-heavy bg-surface-primary',
)}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-text-primary" />
</RadioGroup.Item>
{localize('com_ui_mcp_type_streamable_http')}
</label>
</div>
<div className="flex items-center gap-2">
<label
htmlFor="type-sse"
className="flex cursor-pointer items-center gap-1"
>
<RadioGroup.Item
type="button"
value="sse"
id="type-sse"
className={cn(
'mr-1 flex h-5 w-5 items-center justify-center rounded-full border',
'border-border-heavy bg-surface-primary',
)}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-text-primary" />
</RadioGroup.Item>
{localize('com_ui_mcp_type_sse')}
</label>
</div>
</RadioGroup.Root>
)}
/>
</div>
{/* Authentication */}
<Controller
name="auth"
control={control}
render={({ field }) => <MCPAuth value={field.value} onChange={field.onChange} />}
/>
{/* Trust Checkbox */}
<div className="flex items-center gap-2">
<Controller
name="trust"
control={control}
rules={{ required: true }}
render={({ field }) => (
<Checkbox
id="trust"
checked={field.value}
onCheckedChange={field.onChange}
aria-labelledby="trust-this-mcp-label"
/>
)}
/>
<Label
id="trust-this-mcp-label"
htmlFor="trust"
className="flex cursor-pointer flex-col text-sm font-medium"
>
<span>
{localize('com_ui_trust_app')} <span className="text-red-500">*</span>
</span>
<span className="text-xs font-normal text-text-secondary">
{localize('com_agents_mcp_trust_subtext')}
</span>
</Label>
</div>
{errors.trust && (
<span className="text-xs text-red-500">{localize('com_ui_field_required')}</span>
)}
</div>
</FormProvider>
}
footerClassName="sm:justify-between"
leftButtons={
server ? (
<div className="flex items-center gap-2">
<Button
type="button"
variant="outline"
size="sm"
aria-label="Delete MCP server"
onClick={() => setShowDeleteConfirm(true)}
disabled={isSubmitting || isDeleting}
>
<div className="flex w-full items-center justify-center gap-2 text-red-500">
<TrashIcon />
</div>
</Button>
{shouldShowShareButton && (
<GenericGrantAccessDialog
resourceDbId={server.dbId}
resourceName={server.config.title || ''}
resourceType={ResourceType.MCPSERVER}
/>
)}
</div>
) : null
}
buttons={
<Button
type="button"
variant="submit"
onClick={onSubmit}
disabled={isSubmitting}
className="text-white"
>
{isSubmitting ? (
<Spinner className="size-4" />
) : (
localize(server ? 'com_ui_update' : 'com_ui_create')
)}
</Button>
}
/>
</OGDialog>
</>
);
}

View file

@ -0,0 +1,91 @@
import { useState, useRef } from 'react';
import { GearIcon, MCPIcon, OGDialogTrigger } from '@librechat/client';
import {
PermissionBits,
PermissionTypes,
Permissions,
hasPermissions,
} from 'librechat-data-provider';
import { useLocalize, useHasAccess, MCPServerDefinition } from '~/hooks';
import MCPServerStatusIcon from '~/components/MCP/MCPServerStatusIcon';
import MCPServerDialog from './MCPServerDialog';
interface MCPServerListProps {
servers: MCPServerDefinition[];
getServerStatusIconProps: (
serverName: string,
) => React.ComponentProps<typeof MCPServerStatusIcon>;
}
// Self-contained edit button component (follows MemoryViewer pattern)
const EditMCPServerButton = ({ server }: { server: MCPServerDefinition }) => {
const localize = useLocalize();
const [open, setOpen] = useState(false);
const triggerRef = useRef<HTMLButtonElement>(null);
return (
<MCPServerDialog open={open} onOpenChange={setOpen} triggerRef={triggerRef} server={server}>
<OGDialogTrigger asChild>
<button
ref={triggerRef}
onClick={() => setOpen(true)}
className="flex h-5 w-5 items-center justify-center rounded hover:bg-surface-secondary"
aria-label={localize('com_ui_edit')}
>
<GearIcon className="h-4 w-4" />
</button>
</OGDialogTrigger>
</MCPServerDialog>
);
};
export default function MCPServerList({ servers, getServerStatusIconProps }: MCPServerListProps) {
const canCreateEditMCPs = useHasAccess({
permissionType: PermissionTypes.MCP_SERVERS,
permission: Permissions.CREATE,
});
const localize = useLocalize();
if (servers.length === 0) {
return (
<div className="rounded-lg border border-border-light bg-transparent p-8 text-center shadow-sm">
<p className="text-sm text-text-secondary">{localize('com_ui_no_mcp_servers')}</p>
<p className="mt-1 text-xs text-text-tertiary">{localize('com_ui_add_first_mcp_server')}</p>
</div>
);
}
return (
<div className="space-y-2">
{servers.map((server) => {
const canEditThisServer = hasPermissions(server.effectivePermissions, PermissionBits.EDIT);
const displayName = server.config?.title || server.serverName;
const serverKey = `key_${server.serverName}`;
return (
<div key={serverKey} className="rounded-lg border border-border-light bg-transparent p-3">
<div className="flex items-center gap-3">
{/* Server Icon */}
{server.config?.iconPath ? (
<img src={server.config.iconPath} className="h-5 w-5 rounded" alt={displayName} />
) : (
<MCPIcon className="h-5 w-5" />
)}
{/* Server Info */}
<div className="min-w-0 flex-1">
<h3 className="truncate font-semibold text-text-primary">{displayName}</h3>
</div>
{/* Edit Button - Only for DB servers and when user has CREATE access */}
{canCreateEditMCPs && canEditThisServer && <EditMCPServerButton server={server} />}
{/* Connection Status Icon */}
<MCPServerStatusIcon {...getServerStatusIconProps(server.serverName)} />
</div>
</div>
);
})}
</div>
);
}

View file

@ -0,0 +1,5 @@
export { default } from './MCPBuilderPanel';
export { default as MCPBuilderPanel } from './MCPBuilderPanel';
export { default as MCPServerList } from './MCPServerList';
export { default as MCPServerDialog } from './MCPServerDialog';
export { default as MCPAuth } from './MCPAuth';

View file

@ -207,7 +207,7 @@ function MCPToolSelectDialog({
}, [mcpServerNames]);
const mcpServers = useMemo(() => {
const servers = Array.from(mcpServersMap.values());
const servers = Array.from(mcpServersMap.values()).filter((s) => !s.consumeOnly);
return servers.sort((a, b) => a.serverName.localeCompare(b.serverName));
}, [mcpServersMap]);
@ -340,7 +340,6 @@ function MCPToolSelectDialog({
tool_id: serverInfo.serverName,
metadata: {
...serverInfo.metadata,
description: `${localize('com_ui_tool_collection_prefix')} ${serverInfo.serverName}`,
},
};

View file

@ -1 +1,2 @@
export * from './queries';
export * from './mutations';

View file

@ -0,0 +1,141 @@
import { useMutation, useQueryClient, UseMutationResult } from '@tanstack/react-query';
import { dataService, QueryKeys, ResourceType } from 'librechat-data-provider';
import type * as t from 'librechat-data-provider';
/**
* Hook for creating a new MCP server
*/
export const useCreateMCPServerMutation = (options?: {
onMutate?: (variables: t.MCPServerCreateParams) => void;
onSuccess?: (
data: t.MCPServerDBObjectResponse,
variables: t.MCPServerCreateParams,
context: unknown,
) => void;
onError?: (error: Error, variables: t.MCPServerCreateParams, context: unknown) => void;
}): UseMutationResult<t.MCPServerDBObjectResponse, Error, t.MCPServerCreateParams> => {
const queryClient = useQueryClient();
return useMutation((data: t.MCPServerCreateParams) => dataService.createMCPServer(data), {
onMutate: (variables) => options?.onMutate?.(variables),
onError: (error, variables, context) => options?.onError?.(error, variables, context),
onSuccess: (newServer, variables, context) => {
const listRes = queryClient.getQueryData<t.MCPServersListResponse>([QueryKeys.mcpServers]);
if (listRes) {
queryClient.setQueryData<t.MCPServersListResponse>([QueryKeys.mcpServers], {
...listRes,
[newServer.serverName!]: newServer,
});
}
queryClient.invalidateQueries([QueryKeys.mcpServers]);
queryClient.invalidateQueries([QueryKeys.mcpTools]);
queryClient.invalidateQueries([QueryKeys.mcpAuthValues]);
queryClient.invalidateQueries([QueryKeys.mcpConnectionStatus]);
queryClient.invalidateQueries([
QueryKeys.effectivePermissions,
'all',
ResourceType.MCPSERVER,
]);
return options?.onSuccess?.(newServer, variables, context);
},
});
};
/**
* Hook for updating an existing MCP server
*/
export const useUpdateMCPServerMutation = (options?: {
onMutate?: (variables: { serverName: string; data: t.MCPServerUpdateParams }) => void;
onSuccess?: (
data: t.MCPServerDBObjectResponse,
variables: { serverName: string; data: t.MCPServerUpdateParams },
context: unknown,
) => void;
onError?: (
error: Error,
variables: { serverName: string; data: t.MCPServerUpdateParams },
context: unknown,
) => void;
}): UseMutationResult<
t.MCPServerDBObjectResponse,
Error,
{ serverName: string; data: t.MCPServerUpdateParams }
> => {
const queryClient = useQueryClient();
return useMutation(
({ serverName, data }: { serverName: string; data: t.MCPServerUpdateParams }) =>
dataService.updateMCPServer(serverName, data),
{
onMutate: (variables: { serverName: string; data: t.MCPServerUpdateParams }) =>
options?.onMutate?.(variables),
onError: (
error: Error,
variables: { serverName: string; data: t.MCPServerUpdateParams },
context: unknown,
) => options?.onError?.(error, variables, context),
onSuccess: (
updatedServer: t.MCPServerDBObjectResponse,
variables: { serverName: string; data: t.MCPServerUpdateParams },
context: unknown,
) => {
// Update list cache
const listRes = queryClient.getQueryData<t.MCPServersListResponse>([QueryKeys.mcpServers]);
if (listRes) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { type, ...oldServer } = listRes[variables.serverName!];
listRes[variables.serverName!] = { ...oldServer, ...updatedServer };
queryClient.setQueryData<t.MCPServersListResponse>([QueryKeys.mcpServers], {
...listRes,
});
}
queryClient.setQueryData([QueryKeys.mcpServer, variables.serverName], updatedServer);
queryClient.invalidateQueries([QueryKeys.mcpServers]);
queryClient.invalidateQueries([QueryKeys.mcpTools]);
queryClient.invalidateQueries([QueryKeys.mcpAuthValues]);
queryClient.invalidateQueries([QueryKeys.mcpConnectionStatus]);
return options?.onSuccess?.(updatedServer, variables, context);
},
},
);
};
/**
* Hook for deleting an MCP server
*/
export const useDeleteMCPServerMutation = (options?: {
onMutate?: (variables: string) => void;
onSuccess?: (_data: { success: boolean }, variables: string, context: unknown) => void;
onError?: (error: Error, variables: string, context: unknown) => void;
}): UseMutationResult<{ success: boolean }, Error, string> => {
const queryClient = useQueryClient();
return useMutation((serverName: string) => dataService.deleteMCPServer(serverName), {
onMutate: (variables) => options?.onMutate?.(variables),
onError: (error, variables, context) => options?.onError?.(error, variables, context),
onSuccess: (_data, serverName, context) => {
// Update list cache by removing the deleted server (immutable update)
const listRes = queryClient.getQueryData<t.MCPServersListResponse>([QueryKeys.mcpServers]);
if (listRes) {
const { [serverName]: _removed, ...remaining } = listRes;
queryClient.setQueryData<t.MCPServersListResponse>([QueryKeys.mcpServers], remaining);
}
// Remove from specific server query cache
queryClient.removeQueries([QueryKeys.mcpServer, serverName]);
// Invalidate list query to ensure consistency
queryClient.invalidateQueries([QueryKeys.mcpServers]);
queryClient.invalidateQueries([QueryKeys.mcpTools]);
queryClient.invalidateQueries([QueryKeys.mcpAuthValues]);
queryClient.invalidateQueries([QueryKeys.mcpConnectionStatus]);
return options?.onSuccess?.(_data, serverName, context);
},
});
};

View file

@ -6,6 +6,7 @@ import {
memoryPermissionsSchema,
marketplacePermissionsSchema,
peoplePickerPermissionsSchema,
mcpServersPermissionsSchema,
} from 'librechat-data-provider';
import type {
UseQueryOptions,
@ -171,6 +172,42 @@ export const useUpdatePeoplePickerPermissionsMutation = (
);
};
export const useUpdateMCPServersPermissionsMutation = (
options?: t.UpdateMCPServersPermOptions,
): UseMutationResult<
t.UpdatePermResponse,
t.TError | undefined,
t.UpdateMCPServersPermVars,
unknown
> => {
const queryClient = useQueryClient();
const { onMutate, onSuccess, onError } = options ?? {};
return useMutation(
(variables) => {
mcpServersPermissionsSchema.partial().parse(variables.updates);
return dataService.updateMCPServersPermissions(variables);
},
{
onSuccess: (data, variables, context) => {
queryClient.invalidateQueries([QueryKeys.roles, variables.roleName]);
if (onSuccess) {
onSuccess(data, variables, context);
}
},
onError: (...args) => {
const error = args[0];
if (error != null) {
console.error('Failed to update MCP servers permissions:', error);
}
if (onError) {
onError(...args);
}
},
onMutate,
},
);
};
export const useUpdateMarketplacePermissionsMutation = (
options?: t.UpdateMarketplacePermOptions,
): UseMutationResult<

View file

@ -1,5 +1,5 @@
export * from './useMCPConnectionStatus';
export * from './useMCPSelect';
export * from './useVisibleTools';
export { useMCPServerManager } from './useMCPServerManager';
export * from './useMCPServerManager';
export { useRemoveMCPTool } from './useRemoveMCPTool';

View file

@ -1,11 +1,12 @@
import { useCallback, useState, useMemo, useRef, useEffect } from 'react';
import { useToastContext } from '@librechat/client';
import { useQueryClient } from '@tanstack/react-query';
import { Constants, QueryKeys, MCPOptions } from 'librechat-data-provider';
import { Constants, QueryKeys, MCPOptions, ResourceType } from 'librechat-data-provider';
import {
useCancelMCPOAuthMutation,
useUpdateUserPluginsMutation,
useReinitializeMCPServerMutation,
useGetAllEffectivePermissionsQuery,
} from 'librechat-data-provider/react-query';
import type { TUpdateUserPlugins, TPlugin, MCPServersResponse } from 'librechat-data-provider';
import type { ConfigFieldDetail } from '~/common';
@ -15,9 +16,9 @@ import { useGetStartupConfig, useMCPServersQuery } from '~/data-provider';
export interface MCPServerDefinition {
serverName: string;
config: MCPOptions;
mcp_id?: string;
_id?: string; // MongoDB ObjectId for database servers (used for permissions)
dbId?: string; // MongoDB ObjectId for database servers (used for permissions)
effectivePermissions: number; // Permission bits (VIEW=1, EDIT=2, DELETE=4, SHARE=8)
consumeOnly?: boolean;
}
interface ServerState {
@ -36,35 +37,44 @@ export function useMCPServerManager({ conversationId }: { conversationId?: strin
const { data: loadedServers, isLoading } = useMCPServersQuery();
// Fetch effective permissions for all MCP servers
const { data: permissionsMap } = useGetAllEffectivePermissionsQuery(ResourceType.MCPSERVER);
const [isConfigModalOpen, setIsConfigModalOpen] = useState(false);
const [selectedToolForConfig, setSelectedToolForConfig] = useState<TPlugin | null>(null);
const previousFocusRef = useRef<HTMLElement | null>(null);
const configuredServers = useMemo(() => {
if (!loadedServers) return [];
return Object.keys(loadedServers).filter((name) => loadedServers[name]?.chatMenu !== false);
}, [loadedServers]);
const availableMCPServers: MCPServerDefinition[] = useMemo<MCPServerDefinition[]>(() => {
const definitions: MCPServerDefinition[] = [];
if (loadedServers) {
for (const [serverName, metadata] of Object.entries(loadedServers)) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { _id, mcp_id, effectivePermissions, author, updatedAt, createdAt, ...config } =
metadata;
const { dbId, consumeOnly, ...config } = metadata;
// Get effective permissions from the permissions map using _id
// Fall back to 1 (VIEW) for YAML-based servers without _id
const effectivePermissions = dbId && permissionsMap?.[dbId] ? permissionsMap[dbId] : 1;
definitions.push({
serverName,
mcp_id,
effectivePermissions: effectivePermissions || 1,
dbId,
effectivePermissions,
consumeOnly,
config,
});
}
}
return definitions;
}, [loadedServers]);
}, [loadedServers, permissionsMap]);
// Memoize filtered servers for useMCPSelect to prevent infinite loops
const selectableServers = useMemo(
() => availableMCPServers.filter((s) => s.config.chatMenu !== false && !s.consumeOnly),
[availableMCPServers],
);
const { mcpValues, setMCPValues, isPinned, setIsPinned } = useMCPSelect({
conversationId,
servers: availableMCPServers,
servers: selectableServers,
});
const mcpValuesRef = useRef(mcpValues);
@ -73,6 +83,14 @@ export function useMCPServerManager({ conversationId }: { conversationId?: strin
mcpValuesRef.current = mcpValues;
}, [mcpValues]);
// Check if specific permission bit is set
const checkEffectivePermission = useCallback(
(effectivePermissions: number, permissionBit: number): boolean => {
return (effectivePermissions & permissionBit) !== 0;
},
[],
);
const reinitializeMutation = useReinitializeMCPServerMutation();
const cancelOAuthMutation = useCancelMCPOAuthMutation();
@ -98,8 +116,8 @@ export function useMCPServerManager({ conversationId }: { conversationId?: strin
const [serverStates, setServerStates] = useState<Record<string, ServerState>>(() => {
const initialStates: Record<string, ServerState> = {};
configuredServers.forEach((serverName) => {
initialStates[serverName] = {
availableMCPServers.forEach((server) => {
initialStates[server.serverName] = {
isInitializing: false,
oauthUrl: null,
oauthStartTime: null,
@ -111,7 +129,7 @@ export function useMCPServerManager({ conversationId }: { conversationId?: strin
});
const { connectionStatus } = useMCPConnectionStatus({
enabled: !isLoading && configuredServers.length > 0,
enabled: !isLoading && availableMCPServers.length > 0,
});
const updateServerState = useCallback((serverName: string, updates: Partial<ServerState>) => {
@ -366,7 +384,12 @@ export function useMCPServerManager({ conversationId }: { conversationId?: strin
cancelOAuthMutation.mutate(serverName, {
onSuccess: () => {
cleanupServerState(serverName);
queryClient.invalidateQueries([QueryKeys.mcpConnectionStatus]);
Promise.all([
queryClient.invalidateQueries([QueryKeys.mcpServers]),
queryClient.invalidateQueries([QueryKeys.mcpTools]),
queryClient.invalidateQueries([QueryKeys.mcpAuthValues]),
queryClient.invalidateQueries([QueryKeys.mcpConnectionStatus]),
]);
showToast({
message: localize('com_ui_mcp_oauth_cancelled', { 0: serverName }),
@ -629,6 +652,8 @@ export function useMCPServerManager({ conversationId }: { conversationId?: strin
return {
availableMCPServers,
/** MCP servers filtered for chat menu selection (chatMenu !== false && !consumeOnly) */
selectableServers,
availableMCPServersMap: loadedServers,
isLoading,
connectionStatus,
@ -655,5 +680,6 @@ export function useMCPServerManager({ conversationId }: { conversationId?: strin
handleRevoke,
getServerStatusIconProps,
getConfigDialogProps,
checkEffectivePermission,
};
}

View file

@ -10,6 +10,7 @@ import {
isAssistantsEndpoint,
} from 'librechat-data-provider';
import type { TInterfaceConfig, TEndpointsConfig } from 'librechat-data-provider';
import MCPBuilderPanel from '~/components/SidePanel/MCPBuilder/MCPBuilderPanel';
import type { NavLink } from '~/common';
import AgentPanelSwitch from '~/components/SidePanel/Agents/AgentPanelSwitch';
import BookmarkPanel from '~/components/SidePanel/Bookmarks/BookmarkPanel';
@ -18,7 +19,6 @@ import PanelSwitch from '~/components/SidePanel/Builder/PanelSwitch';
import PromptsAccordion from '~/components/Prompts/PromptsAccordion';
import Parameters from '~/components/SidePanel/Parameters/Panel';
import FilesPanel from '~/components/SidePanel/Files/Panel';
import MCPPanel from '~/components/SidePanel/MCP/MCPPanel';
import { useHasAccess, useMCPServerManager } from '~/hooks';
export default function useSideNavLinks({
@ -60,7 +60,10 @@ export default function useSideNavLinks({
permissionType: PermissionTypes.AGENTS,
permission: Permissions.CREATE,
});
const hasAccessToUseMCPSettings = useHasAccess({
permissionType: PermissionTypes.MCP_SERVERS,
permission: Permissions.USE,
});
const { availableMCPServers } = useMCPServerManager();
const Links = useMemo(() => {
@ -152,21 +155,13 @@ export default function useSideNavLinks({
});
}
if (
availableMCPServers &&
availableMCPServers.some(
(server: any) =>
(server.config.customUserVars && Object.keys(server.config.customUserVars).length > 0) ||
server.config.isOAuth ||
server.config.startup === false,
)
) {
if (hasAccessToUseMCPSettings && availableMCPServers && availableMCPServers.length > 0) {
links.push({
title: 'com_nav_setting_mcp',
label: '',
icon: MCPIcon,
id: 'mcp-settings',
Component: MCPPanel,
id: 'mcp-builder',
Component: MCPBuilderPanel,
});
}
@ -180,19 +175,20 @@ export default function useSideNavLinks({
return links;
}, [
endpointsConfig,
interfaceConfig.parameters,
keyProvided,
endpointType,
endpoint,
endpointsConfig,
keyProvided,
hasAccessToAgents,
hasAccessToCreateAgents,
hasAccessToPrompts,
hasAccessToMemories,
hasAccessToReadMemories,
interfaceConfig.parameters,
endpointType,
hasAccessToBookmarks,
hasAccessToCreateAgents,
hidePanel,
availableMCPServers,
hasAccessToUseMCPSettings,
hidePanel,
]);
return Links;

View file

@ -8,7 +8,7 @@ import { getResourceConfig } from '~/utils';
/**
* Hook to manage resource permission state including current shares, public access, and mutations
* @param resourceType - Type of resource (e.g., ResourceType.AGENT, ResourceType.PROMPTGROUP)
* @param resourceType - Type of resource (e.g., ResourceType.AGENT, ResourceType.PROMPTGROUP, ResourceType.MCPSERVER)
* @param resourceDbId - Database ID of the resource
* @param isModalOpen - Whether the modal is open (for effect dependencies)
* @returns Object with permission state and update mutation

View file

@ -75,10 +75,8 @@
"com_agents_marketplace_subtitle": "Discover and use powerful AI agents to enhance your workflows and productivity",
"com_agents_mcp_description_placeholder": "Explain what it does in a few words",
"com_agents_mcp_icon_size": "Minimum size 128 x 128 px",
"com_agents_mcp_info": "Add MCP servers to your agent to enable it to perform tasks and interact with external services",
"com_agents_mcp_name_placeholder": "Custom Tool",
"com_agents_mcp_trust_subtext": "Custom connectors are not verified by LibreChat",
"com_agents_mcps_disabled": "You need to create an agent before adding MCPs.",
"com_agents_missing_name": "Please type in a name before creating an agent.",
"com_agents_missing_provider_model": "Please select a provider and model before creating an agent.",
"com_agents_name_placeholder": "Optional: The name of the agent",
@ -536,6 +534,7 @@
"com_nav_long_audio_warning": "Longer texts will take longer to process.",
"com_nav_maximize_chat_space": "Maximize chat space",
"com_nav_mcp_configure_server": "Configure {{0}}",
"com_nav_mcp_status_connected": "Connected",
"com_nav_mcp_status_connecting": "{{0}} - Connecting",
"com_nav_mcp_vars_update_error": "Error updating MCP custom user variables",
"com_nav_mcp_vars_updated": "MCP custom user variables updated successfully.",
@ -593,7 +592,6 @@
"com_sidepanel_conversation_tags": "Bookmarks",
"com_sidepanel_hide_panel": "Hide Panel",
"com_sidepanel_manage_files": "Manage Files",
"com_sidepanel_mcp_no_servers_with_vars": "No MCP servers with configurable variables.",
"com_sidepanel_parameters": "Parameters",
"com_sources_agent_file": "Source Document",
"com_sources_agent_files": "Agent Files",
@ -631,6 +629,10 @@
"com_ui_add_web_search_api_keys": "Add Web Search API Keys",
"com_ui_add_mcp": "Add MCP",
"com_ui_add_mcp_server": "Add MCP Server",
"com_ui_no_mcp_servers": "No MCP servers yet",
"com_ui_add_first_mcp_server": "Create your first MCP server to get started",
"com_ui_mcp_server_created": "MCP server created successfully",
"com_ui_mcp_server_updated": "MCP server updated successfully",
"com_ui_add_model_preset": "Add a model or preset for an additional response",
"com_ui_add_multi_conversation": "Add multi-conversation",
"com_ui_add_special_variables": "Add Special Variables",
@ -691,6 +693,9 @@
"com_ui_agents_allow_create": "Allow creating Agents",
"com_ui_agents_allow_share": "Allow sharing Agents",
"com_ui_agents_allow_use": "Allow using Agents",
"com_ui_mcp_servers_allow_create": "Allow users to create MCP servers",
"com_ui_mcp_servers_allow_share": "Allow users to share MCP servers",
"com_ui_mcp_servers_allow_use": "Allow users to use MCP servers",
"com_ui_all": "all",
"com_ui_all_proper": "All",
"com_ui_analyzing": "Analyzing",
@ -725,7 +730,6 @@
"com_ui_authentication": "Authentication",
"com_ui_authentication_type": "Authentication Type",
"com_ui_auto": "Auto",
"com_ui_available_tools": "Available Tools",
"com_ui_avatar": "Avatar",
"com_ui_azure": "Azure",
"com_ui_azure_ad": "Entra ID",
@ -864,10 +868,6 @@
"com_ui_delete_confirm_strong": "This will delete <strong>{{title}}</strong>",
"com_ui_delete_confirm_prompt_version_var": "This will delete the selected version for \"{{0}}.\" If no other versions exist, the prompt will be deleted.",
"com_ui_delete_conversation": "Delete chat?",
"com_ui_delete_mcp": "Delete MCP",
"com_ui_delete_mcp_confirm": "Are you sure you want to delete this MCP server?",
"com_ui_delete_mcp_error": "Failed to delete MCP server",
"com_ui_delete_mcp_success": "MCP server deleted successfully",
"com_ui_delete_memory": "Delete Memory",
"com_ui_delete_not_allowed": "Delete operation is not allowed",
"com_ui_delete_preset": "Delete Preset?",
@ -887,6 +887,7 @@
"com_ui_deselect_all": "Deselect All",
"com_ui_detailed": "Detailed",
"com_ui_disabling": "Disabling...",
"com_ui_done": "Done",
"com_ui_download": "Download",
"com_ui_download_artifact": "Download Artifact",
"com_ui_download_backup": "Download Backup Codes",
@ -904,9 +905,9 @@
"com_ui_edit": "Edit",
"com_ui_edit_editing_image": "Editing image",
"com_ui_edit_mcp_server": "Edit MCP Server",
"com_ui_edit_mcp_server_dialog_description": "Unique Server Identifier: {{serverName}}",
"com_ui_edit_memory": "Edit Memory",
"com_ui_edit_preset_title": "Edit Preset - {{title}}",
"com_ui_edit_server": "Edit {{serverName}}",
"com_ui_edit_prompt_page": "Edit Prompt Page",
"com_ui_editable_message": "Editable Message",
"com_ui_editor_instructions": "Drag the image to reposition • Use zoom slider or buttons to adjust size",
@ -1047,7 +1048,7 @@
"com_ui_mcp_initialized_success": "MCP server '{{0}}' initialized successfully",
"com_ui_mcp_oauth_cancelled": "OAuth login cancelled for {{0}}",
"com_ui_mcp_oauth_timeout": "OAuth login timed out for {{0}}",
"com_ui_mcp_server_not_found": "Server not found.",
"com_ui_mcp_server": "MCP Server",
"com_ui_mcp_servers": "MCP Servers",
"com_ui_mcp_update_var": "Update {{0}}",
"com_ui_mcp_url": "MCP Server URL",
@ -1109,7 +1110,6 @@
"com_ui_oauth_error_missing_code": "Authorization code is missing. Please try again.",
"com_ui_oauth_error_missing_state": "State parameter is missing. Please try again.",
"com_ui_oauth_error_title": "Authentication Failed",
"com_ui_oauth_revoke": "Revoke",
"com_ui_oauth_success_description": "Your authentication was successful. This window will close in",
"com_ui_oauth_success_title": "Authentication Successful",
"com_ui_of": "of",
@ -1154,6 +1154,9 @@
"com_ui_quality": "Quality",
"com_ui_read_aloud": "Read aloud",
"com_ui_redirecting_to_provider": "Redirecting to {{0}}, please wait...",
"com_ui_redirect_uri": "Redirect URI",
"com_ui_redirect_uri_info": "The redirect URI will be provided after the server is created. Configure it in your OAuth provider settings.",
"com_ui_redirect_uri_instructions": "Copy this redirect URI and configure it in your OAuth provider settings.",
"com_ui_reference_saved_memories": "Reference saved memories",
"com_ui_reference_saved_memories_description": "Allow the assistant to reference and use your saved memories when responding",
"com_ui_refresh": "Refresh",
@ -1199,6 +1202,18 @@
"com_ui_role_select": "Role",
"com_ui_role_viewer": "Viewer",
"com_ui_role_viewer_desc": "Can view and use the agent but cannot modify it",
"com_ui_mcp_server_role_viewer": "MCP Server Viewer",
"com_ui_mcp_server_role_viewer_desc": "Can view and use MCP servers",
"com_ui_mcp_server_role_editor": "MCP Server Editor",
"com_ui_mcp_server_role_editor_desc": "Can view, use, and edit MCP servers",
"com_ui_mcp_server_role_owner": "MCP Server Owner",
"com_ui_mcp_server_role_owner_desc": "Full control over MCP servers",
"com_ui_mcp_server_delete_confirm": "Are you sure you want to delete this MCP server?",
"com_ui_mcp_server_deleted": "MCP server deleted successfully",
"com_ui_mcp_title_invalid": "Title can only contain letters, numbers, and spaces",
"com_ui_mcp_server_type": "Server Type",
"com_ui_mcp_type_streamable_http": "Streamable HTTPS",
"com_ui_mcp_type_sse": "SSE",
"com_ui_roleplay": "Roleplay",
"com_ui_rotate": "Rotate",
"com_ui_rotate_90": "Rotate 90 degrees",
@ -1312,8 +1327,6 @@
"com_ui_unpin": "Unpin",
"com_ui_untitled": "Untitled",
"com_ui_update": "Update",
"com_ui_update_mcp_error": "There was an error creating or updating the MCP.",
"com_ui_update_mcp_success": "Successfully created or updated MCP",
"com_ui_upload": "Upload",
"com_ui_upload_agent_avatar": "Successfully updated agent avatar",
"com_ui_upload_agent_avatar_label": "Upload agent avatar image",

View file

@ -36,6 +36,17 @@ export const RESOURCE_CONFIGS: Record<ResourceType, ResourceConfig> = {
`Manage permissions for ${name && name !== '' ? `"${name}"` : 'prompt'}`,
getCopyUrlMessage: () => 'Prompt URL copied',
},
[ResourceType.MCPSERVER]: {
resourceType: ResourceType.MCPSERVER,
defaultViewerRoleId: AccessRoleIds.MCPSERVER_VIEWER,
defaultEditorRoleId: AccessRoleIds.MCPSERVER_EDITOR,
defaultOwnerRoleId: AccessRoleIds.MCPSERVER_OWNER,
getResourceName: (name?: string) => (name && name !== '' ? `"${name}"` : 'MCP server'),
getShareMessage: (name?: string) => (name && name !== '' ? `"${name}"` : 'MCP server'),
getManageMessage: (name?: string) =>
`Manage permissions for ${name && name !== '' ? `"${name}"` : 'MCP server'}`,
getCopyUrlMessage: () => 'MCP Server URL copied',
},
};
export const getResourceConfig = (resourceType: ResourceType): ResourceConfig | undefined => {

View file

@ -35,6 +35,19 @@ export const ROLE_LOCALIZATIONS = {
name: 'com_ui_role_owner' as const,
description: 'com_ui_role_owner_desc' as const,
} as const,
// MCPServer roles
mcpServer_viewer: {
name: 'com_ui_mcp_server_role_viewer' as const,
description: 'com_ui_mcp_server_role_viewer_desc' as const,
} as const,
mcpServer_editor: {
name: 'com_ui_mcp_server_role_editor' as const,
description: 'com_ui_mcp_server_role_editor_desc' as const,
} as const,
mcpServer_owner: {
name: 'com_ui_mcp_server_role_owner' as const,
description: 'com_ui_mcp_server_role_owner_desc' as const,
} as const,
};
/**