import React, { useState } from 'react' import { client } from '@/ui/api/client' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { Server, Loader2, MoreVertical, Plus, Trash2, ShieldCheck, CheckCircle2, AlertCircle, Clock, Key, Wrench, } from 'lucide-react' import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card' import { Button } from '@/ui/components/ui/button' import { Badge } from '@/ui/components/ui/badge' import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger, } from '@/ui/components/ui/dropdown-menu' import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from '@/ui/components/ui/alert-dialog' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/ui/components/ui/select' import { McpServerInfo, McpServerPermission } from '@shumai/dtos' import { m } from '@/ui/paraglide/messages.js' import { usePermissions } from '@/ui/hooks/use-permissions' import { toast } from 'sonner' import { McpServerFormDialog } from './McpServerFormDialog' interface McpConfigCardProps { teamId: string } export const McpConfigCard: React.FC = ({ teamId }) => { const queryClient = useQueryClient() const { canAdmin } = usePermissions() const [isAddFormOpen, setIsAddFormOpen] = useState(false) const [editingServer, setEditingServer] = useState(null) const [deletingServer, setDeletingServer] = useState(null) const [authenticatingServerId, setAuthenticatingServerId] = useState(null) // Fetch MCP Servers const { data, isLoading } = useQuery({ queryKey: ['teams', teamId, 'mcp', 'servers'], queryFn: async () => { const res = await client.api.teams[':teamId'].mcp.servers.$get({ param: { teamId } }) if (!res.ok) throw new Error(m.failed_load_settings()) return await res.json() }, }) // Delete Server Mutation const deleteMutation = useMutation({ mutationFn: async (id: string) => { const res = await client.api.mcp.servers[':id'].$delete({ param: { id } }) if (!res.ok) throw new Error(m.failed_to_delete()) }, onSuccess: () => { toast.success(m.delete()) queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'mcp', 'servers'] }) setDeletingServer(null) }, onError: (err: Error) => { toast.error(err.message) }, }) // Update Permission Mutation const updatePermissionMutation = useMutation({ mutationFn: async ({ id, permission }: { id: string; permission: McpServerPermission }) => { const res = await client.api.mcp.servers[':id'].permission.$patch({ param: { id }, json: { permission }, }) if (!res.ok) throw new Error(m.failed_to_update_permission()) }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'mcp', 'servers'] }) }, onError: (err: Error) => { toast.error(err.message) }, }) // Enable/Disable Mutation // (Removed: enable/disable now happens per-agent via AgentMcpServer assignment.) // Disconnect Auth Mutation const disconnectAuthMutation = useMutation({ mutationFn: async (id: string) => { const res = await client.api.mcp.servers[':id'].auth.$delete({ param: { id } }) if (!res.ok) throw new Error('Failed to disconnect auth') }, onSuccess: () => { toast.success(m.mcp_disconnect_auth()) queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'mcp', 'servers'] }) }, onError: (err: Error) => { toast.error(err.message) }, }) // Start Auth Flow (OAuth Popup / Bearer) const handleStartAuth = async (serverId: string) => { setAuthenticatingServerId(serverId) try { const res = await client.api.mcp.servers[':id'].auth.start.$post({ param: { id: serverId }, }) if (!res.ok) { const err = (await res.json().catch(() => ({}))) as { error?: string } throw new Error(err.error || m.mcp_auth_failed()) } const data = (await res.json()) as { authorizationUrl?: string; status?: string } if (data.status === 'authenticated') { toast.success(m.mcp_auth_success()) queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'mcp', 'servers'] }) setAuthenticatingServerId(null) return } if (data.authorizationUrl) { // Open OAuth popup window const width = 600 const height = 700 const left = window.screenX + (window.outerWidth - width) / 2 const top = window.screenY + (window.outerHeight - height) / 2 const popup = window.open( data.authorizationUrl, 'mcp_oauth_popup', `width=${width},height=${height},left=${left},top=${top},scrollbars=yes`, ) const handleMessage = (event: MessageEvent) => { if (event.data?.type === 'mcp-oauth-callback') { window.removeEventListener('message', handleMessage) setAuthenticatingServerId(null) if (event.data.ok) { toast.success(m.mcp_auth_success()) queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'mcp', 'servers'] }) } else { toast.error(event.data.message || m.mcp_auth_failed()) } } } window.addEventListener('message', handleMessage) // Monitor popup closure const checkClosed = setInterval(() => { if (!popup || popup.closed) { clearInterval(checkClosed) window.removeEventListener('message', handleMessage) setAuthenticatingServerId(null) queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'mcp', 'servers'] }) } }, 1000) } } catch (err) { toast.error(err instanceof Error ? err.message : m.mcp_auth_failed()) setAuthenticatingServerId(null) } } const servers = data?.servers || [] const renderStatusBadge = (server: McpServerInfo) => { switch (server.status) { case 'connected': return ( {m.mcp_status_connected()} ) case 'needs_auth': return ( {m.mcp_status_needs_auth()} ) case 'failed': return ( {m.mcp_status_failed()} ) default: return ( {m.mcp_status_not_connected()} ) } } return (
{m.mcp_servers()} {m.mcp_servers_description()}
{canAdmin && ( )}
{isLoading ? (
) : servers.length === 0 ? (

{m.no_mcp_servers_installed()}

{m.add_mcp_server_to_get_started()}

{canAdmin && ( )}
) : (
{servers.map((server) => { const isAuthenticating = authenticatingServerId === server.id const needsAuth = server.status === 'needs_auth' || (!server.hasCredential && server.authType !== 'none') return (
canAdmin && setEditingServer(server)} className={`p-4 bg-card rounded-xl border border-border flex flex-col justify-between hover:shadow-md transition-all group ${ canAdmin ? 'cursor-pointer' : '' }`} > {/* Row 1: name + three-dot */}

{server.name} {server.transport}

{canAdmin && ( e.stopPropagation()}> {server.status !== 'connected' && (server.authType !== 'none' || server.hasCredential) ? ( { e.stopPropagation() handleStartAuth(server.id) }} > {m.mcp_connect_auth()} ) : null} {server.hasCredential && ( { e.stopPropagation() disconnectAuthMutation.mutate(server.id) }} className="text-amber-600" > {m.mcp_disconnect_auth()} )} {((server.status !== 'connected' && (server.authType !== 'none' || server.hasCredential)) || server.hasCredential) && } { e.stopPropagation() setDeletingServer(server) }} className="text-red-600" > {m.delete()} )}
{/* Row 2: description + url + lastError */}

{server.description || m.no_description_provided()}

{server.url}

{server.lastError && (

{server.lastError}

)}
{/* Row 3: status + updated (left), permission + connect (right) */}
{renderStatusBadge(server)} {m.mcp_tools_count({ count: server.toolCount })} {m.updated_date()} {new Date(server.updatedAt).toLocaleDateString()}
e.stopPropagation()} > {canAdmin ? ( ) : ( {server.permission === 'reviewer' ? m.permission_all_users() : server.permission === 'editor' ? m.permission_owner_and_editor() : m.permission_owner_only()} )} {/* Connect button — right end of the row */} {needsAuth && canAdmin && ( )}
) })}
)}
{/* Form Dialog for Add / Edit */} { setIsAddFormOpen(false) setEditingServer(null) }} teamId={teamId} server={editingServer} /> {/* Delete Confirmation Alert */} !open && setDeletingServer(null)} > {m.delete_mcp_server()} {m.delete_mcp_server_confirmation({ name: deletingServer?.name || '' })} {m.cancel()} deletingServer && deleteMutation.mutate(deletingServer.id)} className="bg-red-600 hover:bg-red-700 text-white" > {deleteMutation.isPending && } {m.delete()}
) }