import React, { useState, useEffect } from 'react' import { client } from '@/ui/api/client' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from '@/ui/components/ui/dialog' import { Button } from '@/ui/components/ui/button' import { Input } from '@/ui/components/ui/input' import { Label } from '@/ui/components/ui/label' import { ToggleGroup, ToggleGroupItem } from '@/ui/components/ui/toggle-group' import { Badge } from '@/ui/components/ui/badge' import { ScrollArea } from '@/ui/components/ui/scroll-area' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/ui/components/ui/select' import { Loader2, Server, Info, RefreshCw, Wrench, ChevronDown, ChevronRight } from 'lucide-react' import { m } from '@/ui/paraglide/messages.js' import { toast } from 'sonner' import { McpServerInfo, McpTransport, McpServerPermission, McpServerAuthType, McpToolInfo, CreateMcpServerRequest, UpdateMcpServerRequest, } from '@shumai/dtos' interface McpServerFormDialogProps { isOpen: boolean onClose: () => void teamId: string server?: McpServerInfo | null } export const McpServerFormDialog: React.FC = ({ isOpen, onClose, teamId, server, }) => { const queryClient = useQueryClient() const isEditing = !!server const [url, setUrl] = useState('') const [transport, setTransport] = useState('streamable_http') const [permission, setPermission] = useState('reviewer') // Auth config state const [authType, setAuthType] = useState('auto') const [bearerToken, setBearerToken] = useState('') const [clientId, setClientId] = useState('') const [clientSecret, setClientSecret] = useState('') const [scope, setScope] = useState('') const [grantType, setGrantType] = useState<'authorization_code' | 'client_credentials'>( 'authorization_code', ) // Config state const [directTools, setDirectTools] = useState([]) const [excludedTools, setExcludedTools] = useState([]) // Tools inspector state const [expandedTools, setExpandedTools] = useState>({}) const [isInstructionsExpanded, setIsInstructionsExpanded] = useState(false) useEffect(() => { if (server) { setUrl(server.url) setTransport(server.transport || 'streamable_http') setPermission(server.permission || 'reviewer') setAuthType(server.authType || 'auto') setDirectTools(Array.isArray(server.config?.directTools) ? server.config.directTools : []) setExcludedTools(server.config?.excludeTools ?? []) setExpandedTools({}) setIsInstructionsExpanded(false) } else { setUrl('') setTransport('streamable_http') setPermission('reviewer') setAuthType('auto') setBearerToken('') setClientId('') setClientSecret('') setScope('') setGrantType('authorization_code') setDirectTools([]) setExcludedTools([]) setExpandedTools({}) setIsInstructionsExpanded(false) } }, [server, isOpen]) const buildAuthConfig = () => { if (authType === 'none') { return { type: 'none' as const } } if (authType === 'bearer') { return { type: 'bearer' as const, bearerToken: bearerToken || undefined } } if (authType === 'oauth') { return { type: 'oauth' as const, oauth: { grantType, clientId: clientId || undefined, clientSecret: clientSecret || undefined, scope: scope || undefined, }, } } return undefined // 'auto' } // Fetch tools (edit mode only) const { data: toolsData, isLoading: isToolsLoading, refetch: refetchTools, } = useQuery({ queryKey: ['mcp', 'servers', server?.id, 'tools'], queryFn: async () => { if (!server?.id) return { tools: [] as McpToolInfo[] } const res = await client.api.mcp.servers[':id'].tools.$get({ param: { id: server.id }, }) if (!res.ok) throw new Error('Failed to fetch tools') return await res.json() }, enabled: isOpen && isEditing && !!server?.id, }) const refreshMutation = useMutation({ mutationFn: async () => { if (!server?.id) return const res = await client.api.mcp.servers[':id'].refresh.$post({ param: { id: server.id }, }) if (!res.ok) { const err = (await res.json().catch(() => ({}))) as { error?: string } throw new Error(err.error || 'Failed to refresh server') } return await res.json() }, onSuccess: () => { toast.success(m.mcp_refresh_server_success()) // The tool list is refetched and the toggles re-enable; the server cards // re-fetch the updated record (name, description, instructions, status). refetchTools() queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'mcp', 'servers'] }) }, onError: (err: Error) => { toast.error(err.message) }, }) const saveMutation = useMutation({ mutationFn: async () => { const config = { directTools: directTools.length > 0 ? directTools : undefined, excludeTools: excludedTools.length > 0 ? excludedTools : undefined, } if (isEditing && server) { const updatePayload: UpdateMcpServerRequest = { transport, permission, authConfig: buildAuthConfig(), config, } const res = await client.api.mcp.servers[':id'].$patch({ param: { id: server.id }, json: updatePayload, }) if (!res.ok) { const errData = (await res.json().catch(() => ({}))) as { error?: string } throw new Error(errData.error || m.failed_to_update_permission()) } return await res.json() } else { const createPayload: CreateMcpServerRequest = { url: url.trim(), } const res = await client.api.teams[':teamId'].mcp.servers.$post({ param: { teamId }, json: createPayload, }) if (!res.ok) { const errData = (await res.json().catch(() => ({}))) as { error?: string } throw new Error(errData.error || m.an_unknown_error_occurred()) } const created = await res.json() return created } }, onSuccess: () => { toast.success(isEditing ? m.profile_updated() : m.mcp_servers()) queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'mcp', 'servers'] }) onClose() }, onError: (err: Error) => { toast.error(err.message) }, }) const handleSubmit = (e: React.FormEvent) => { e.preventDefault() if (!url.trim()) return saveMutation.mutate() } const tools = toolsData?.tools ?? [] const getToolState = (toolName: string): 'off' | 'on' | 'direct' => { if (excludedTools.includes(toolName)) return 'off' if (directTools.includes(toolName)) return 'direct' return 'on' } const setToolState = (toolName: string, state: 'off' | 'on' | 'direct') => { if (state === 'off') { setExcludedTools((prev) => (prev.includes(toolName) ? prev : [...prev, toolName])) setDirectTools((prev) => prev.filter((n) => n !== toolName)) } else if (state === 'on') { setExcludedTools((prev) => prev.filter((n) => n !== toolName)) setDirectTools((prev) => prev.filter((n) => n !== toolName)) } else if (state === 'direct') { setExcludedTools((prev) => prev.filter((n) => n !== toolName)) setDirectTools((prev) => (prev.includes(toolName) ? prev : [...prev, toolName])) } } const handleBulkSetState = (state: 'off' | 'on' | 'direct') => { const allToolNames = tools.map((t) => t.name) if (state === 'off') { setExcludedTools(allToolNames) setDirectTools([]) } else if (state === 'on') { setExcludedTools([]) setDirectTools([]) } else if (state === 'direct') { setExcludedTools([]) setDirectTools(allToolNames) } } const toggleExpand = (toolName: string) => { setExpandedTools((prev) => ({ ...prev, [toolName]: !prev[toolName] })) } return ( !open && onClose()}> {isEditing && server ? ( /* ------------------------------------------------------------------ * Edit / config mode: fixed header + footer, scrollable content. * Mirrors the skill config dialog layout. * ------------------------------------------------------------------ */ {refreshMutation.isPending && (
{m.mcp_refresh_server()}...
)} {m.edit_mcp_server()} {m.mcp_servers_description()}
{/* Auto-detected identity (read-only) — the endpoint URL is set at creation and immutable here (delete + re-add to change it). */}
{m.mcp_server_name()} {server.name}
{m.mcp_server_url()} {server.url}
{server.description && (
{m.description()} {server.description}
)} {m.mcp_server_auto_detected()}
{server.instructions && (
{m.mcp_server_instructions()}

setIsInstructionsExpanded((prev) => !prev)} className={`text-xs text-muted-foreground whitespace-pre-wrap leading-relaxed cursor-pointer transition-all ${ isInstructionsExpanded ? '' : 'line-clamp-2' }`} title={isInstructionsExpanded ? undefined : 'Click to expand instructions'} > {server.instructions}

)} {/* Transport & Permission */}
{/* Authentication Configuration */}
{authType === 'bearer' && (
setBearerToken(e.target.value)} placeholder="Enter token string" />
)} {authType === 'oauth' && (
setClientId(e.target.value)} placeholder="Optional Client ID" />
setClientSecret(e.target.value)} placeholder="Optional Secret" />
setScope(e.target.value)} placeholder="Optional scope" />
)}
{/* Tools list */}

{m.mcp_tools_desc()}

{tools.length > 0 && (
)}
{isToolsLoading ? (
) : tools.length === 0 ? (
{m.no_tools_found()}
) : ( tools.map((tool) => { const currentState = getToolState(tool.name) const isExpanded = !!expandedTools[tool.name] const schemaObj = tool.inputSchema as { properties?: Record required?: string[] } const hasProperties = schemaObj?.properties && Object.keys(schemaObj.properties).length > 0 return (
hasProperties && toggleExpand(tool.name)} > {hasProperties ? ( isExpanded ? ( ) : ( ) ) : (
)}
{tool.name} {tool.title && ( {tool.title} )}
{tool.description && (

{tool.description}

)}
{ if (val) setToolState(tool.name, val as 'off' | 'on' | 'direct') }} size="sm" variant="outline" disabled={refreshMutation.isPending || isToolsLoading} > {m.mcp_tool_state_disabled()} {m.mcp_tool_state_proxy()} {m.mcp_tool_state_direct()}
{/* Parameters schema expansion */} {isExpanded && hasProperties && (
{m.tool_parameters()}
{Object.entries(schemaObj.properties!).map( ([propName, propDef]) => { const isRequired = schemaObj.required?.includes(propName) return (
{propName} {isRequired && ( * )} {propDef.type || 'any'}
{propDef.description && ( {propDef.description} )}
) }, )}
)}
) }) )}
) : ( /* ------------------------------------------------------------------ * Create mode: compact URL-only dialog. Name/description are * auto-detected from the server after connecting. * ------------------------------------------------------------------ */ {m.add_mcp_server()} {m.mcp_servers_description()}
setUrl(e.target.value)} placeholder="https://mcp.example.com/mcp" type="url" required />

{m.mcp_server_auto_detected()}

)}
) }