mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
Switch MCP management to use OpenCode server API with version requirement >=1.0.137
This commit is contained in:
1 parent
42149c4759
commit
a00db28fa4
8 files changed
+547
-138
No files matched your search
@@ -0,0 +1,127 @@
|
||||
import { API_BASE_URL } from '@/config'
|
||||
|
||||
const API_BASE = API_BASE_URL
|
||||
|
||||
export type McpStatus =
|
||||
| { status: 'connected' }
|
||||
| { status: 'disabled' }
|
||||
| { status: 'failed'; error: string }
|
||||
| { status: 'needs_auth' }
|
||||
| { status: 'needs_client_registration'; error: string }
|
||||
|
||||
export type McpStatusMap = Record<string, McpStatus>
|
||||
|
||||
export interface McpServerConfig {
|
||||
type: 'local' | 'remote'
|
||||
enabled?: boolean
|
||||
command?: string[]
|
||||
url?: string
|
||||
environment?: Record<string, string>
|
||||
headers?: Record<string, string>
|
||||
timeout?: number
|
||||
oauth?: boolean | {
|
||||
clientId?: string
|
||||
clientSecret?: string
|
||||
scope?: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface AddMcpServerRequest {
|
||||
name: string
|
||||
config: McpServerConfig
|
||||
}
|
||||
|
||||
export interface McpAuthStartResponse {
|
||||
authorizationUrl: string
|
||||
}
|
||||
|
||||
export const mcpApi = {
|
||||
async getStatus(): Promise<McpStatusMap> {
|
||||
const response = await fetch(`${API_BASE}/api/opencode/mcp`)
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to get MCP status: ${response.statusText}`)
|
||||
}
|
||||
return response.json()
|
||||
},
|
||||
|
||||
async addServer(name: string, config: McpServerConfig): Promise<McpStatusMap> {
|
||||
const response = await fetch(`${API_BASE}/api/opencode/mcp`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name, config }),
|
||||
})
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: response.statusText }))
|
||||
throw new Error(error.error || `Failed to add MCP server: ${response.statusText}`)
|
||||
}
|
||||
return response.json()
|
||||
},
|
||||
|
||||
async connect(name: string): Promise<boolean> {
|
||||
const response = await fetch(`${API_BASE}/api/opencode/mcp/${encodeURIComponent(name)}/connect`, {
|
||||
method: 'POST',
|
||||
})
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: response.statusText }))
|
||||
throw new Error(error.error || `Failed to connect MCP server: ${response.statusText}`)
|
||||
}
|
||||
return response.json()
|
||||
},
|
||||
|
||||
async disconnect(name: string): Promise<boolean> {
|
||||
const response = await fetch(`${API_BASE}/api/opencode/mcp/${encodeURIComponent(name)}/disconnect`, {
|
||||
method: 'POST',
|
||||
})
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: response.statusText }))
|
||||
throw new Error(error.error || `Failed to disconnect MCP server: ${response.statusText}`)
|
||||
}
|
||||
return response.json()
|
||||
},
|
||||
|
||||
async startAuth(name: string): Promise<McpAuthStartResponse> {
|
||||
const response = await fetch(`${API_BASE}/api/opencode/mcp/${encodeURIComponent(name)}/auth`, {
|
||||
method: 'POST',
|
||||
})
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: response.statusText }))
|
||||
throw new Error(error.error || `Failed to start MCP auth: ${response.statusText}`)
|
||||
}
|
||||
return response.json()
|
||||
},
|
||||
|
||||
async completeAuth(name: string, code: string): Promise<McpStatus> {
|
||||
const response = await fetch(`${API_BASE}/api/opencode/mcp/${encodeURIComponent(name)}/auth/callback`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ code }),
|
||||
})
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: response.statusText }))
|
||||
throw new Error(error.error || `Failed to complete MCP auth: ${response.statusText}`)
|
||||
}
|
||||
return response.json()
|
||||
},
|
||||
|
||||
async authenticate(name: string): Promise<McpStatus> {
|
||||
const response = await fetch(`${API_BASE}/api/opencode/mcp/${encodeURIComponent(name)}/auth/authenticate`, {
|
||||
method: 'POST',
|
||||
})
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: response.statusText }))
|
||||
throw new Error(error.error || `Failed to authenticate MCP server: ${response.statusText}`)
|
||||
}
|
||||
return response.json()
|
||||
},
|
||||
|
||||
async removeAuth(name: string): Promise<{ success: true }> {
|
||||
const response = await fetch(`${API_BASE}/api/opencode/mcp/${encodeURIComponent(name)}/auth`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: response.statusText }))
|
||||
throw new Error(error.error || `Failed to remove MCP auth: ${response.statusText}`)
|
||||
}
|
||||
return response.json()
|
||||
},
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, Di
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { useMcpServers } from '@/hooks/useMcpServers'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
|
||||
@@ -31,15 +32,16 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe
|
||||
const [enabled, setEnabled] = useState(true)
|
||||
|
||||
const queryClient = useQueryClient()
|
||||
const { addServerAsync, isAddingServer } = useMcpServers()
|
||||
|
||||
const addMcpServerMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
const config = await settingsApi.getDefaultOpenCodeConfig()
|
||||
if (!config) throw new Error('No default config found')
|
||||
|
||||
const currentMcp = (config.content?.mcp as Record<string, any>) || {}
|
||||
const currentMcp = (config.content?.mcp as Record<string, unknown>) || {}
|
||||
|
||||
const mcpConfig: any = {
|
||||
const mcpConfig: Record<string, unknown> = {
|
||||
type: serverType,
|
||||
enabled,
|
||||
}
|
||||
@@ -80,8 +82,29 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe
|
||||
}
|
||||
|
||||
await settingsApi.updateOpenCodeConfig(config.name, { content: updatedConfig })
|
||||
|
||||
if (enabled) {
|
||||
await addServerAsync({
|
||||
name: serverId,
|
||||
config: {
|
||||
type: serverType,
|
||||
enabled,
|
||||
command: serverType === 'local' ? command.split(' ').filter(arg => arg.trim()) : undefined,
|
||||
url: serverType === 'remote' ? url.trim() : undefined,
|
||||
environment: serverType === 'local' && Object.keys(environment).length > 0
|
||||
? environment.reduce((acc, env) => {
|
||||
if (env.key.trim() && env.value.trim()) {
|
||||
acc[env.key.trim()] = env.value.trim()
|
||||
}
|
||||
return acc
|
||||
}, {} as Record<string, string>)
|
||||
: undefined,
|
||||
timeout: timeout && parseInt(timeout) ? parseInt(timeout) : undefined,
|
||||
}
|
||||
})
|
||||
}
|
||||
},
|
||||
onSuccess: async () => {
|
||||
onSuccess: async () => {
|
||||
if (onUpdate) {
|
||||
const config = await settingsApi.getDefaultOpenCodeConfig()
|
||||
if (config) {
|
||||
@@ -90,6 +113,7 @@ onSuccess: async () => {
|
||||
} else {
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode-config'] })
|
||||
}
|
||||
queryClient.invalidateQueries({ queryKey: ['mcp-status'] })
|
||||
handleClose()
|
||||
},
|
||||
})
|
||||
@@ -125,6 +149,8 @@ onSuccess: async () => {
|
||||
onOpenChange(false)
|
||||
}
|
||||
|
||||
const isPending = addMcpServerMutation.isPending || isAddingServer
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleClose}>
|
||||
<DialogContent className="w-full max-w-3xl bg-card border-border">
|
||||
@@ -228,7 +254,7 @@ onSuccess: async () => {
|
||||
size="icon"
|
||||
onClick={() => handleRemoveEnvironmentVar(index)}
|
||||
>
|
||||
×
|
||||
x
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
@@ -259,7 +285,7 @@ onSuccess: async () => {
|
||||
checked={enabled}
|
||||
onCheckedChange={setEnabled}
|
||||
/>
|
||||
<Label htmlFor="enabled">Enable server on startup</Label>
|
||||
<Label htmlFor="enabled">Connect immediately after adding</Label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -269,13 +295,13 @@ onSuccess: async () => {
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleAdd}
|
||||
disabled={!serverId || addMcpServerMutation.isPending}
|
||||
disabled={!serverId || isPending}
|
||||
>
|
||||
{addMcpServerMutation.isPending && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||
{isPending && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||
Add MCP Server
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -4,14 +4,16 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Dialog, DialogTrigger } from '@/components/ui/dialog'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Plus, Trash2, Globe, Terminal, Loader2 } from 'lucide-react'
|
||||
import { Plus, Trash2, Globe, Terminal, Loader2, AlertCircle, RefreshCw, Key, XCircle } from 'lucide-react'
|
||||
import { DeleteDialog } from '@/components/ui/delete-dialog'
|
||||
import { AddMcpServerDialog } from './AddMcpServerDialog'
|
||||
import { useMcpServers } from '@/hooks/useMcpServers'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import type { McpStatus } from '@/api/mcp'
|
||||
|
||||
interface McpServerConfig {
|
||||
type: 'local' | 'remote'
|
||||
enabled: boolean
|
||||
enabled?: boolean
|
||||
command?: string[]
|
||||
url?: string
|
||||
environment?: Record<string, string>
|
||||
@@ -27,51 +29,61 @@ interface McpManagerProps {
|
||||
onConfigUpdate?: (configName: string, content: Record<string, unknown>) => Promise<void>
|
||||
}
|
||||
|
||||
function getStatusBadge(status: McpStatus) {
|
||||
switch (status.status) {
|
||||
case 'connected':
|
||||
return <Badge variant="default" className="text-xs bg-green-600">Connected</Badge>
|
||||
case 'disabled':
|
||||
return <Badge variant="secondary" className="text-xs">Disabled</Badge>
|
||||
case 'failed':
|
||||
return (
|
||||
<Badge variant="destructive" className="text-xs flex items-center gap-1">
|
||||
<AlertCircle className="h-3 w-3" />
|
||||
Failed
|
||||
</Badge>
|
||||
)
|
||||
case 'needs_auth':
|
||||
return (
|
||||
<Badge variant="outline" className="text-xs flex items-center gap-1 border-yellow-500 text-yellow-600">
|
||||
<Key className="h-3 w-3" />
|
||||
Auth Required
|
||||
</Badge>
|
||||
)
|
||||
case 'needs_client_registration':
|
||||
return (
|
||||
<Badge variant="outline" className="text-xs flex items-center gap-1 border-orange-500 text-orange-600">
|
||||
<AlertCircle className="h-3 w-3" />
|
||||
Registration Required
|
||||
</Badge>
|
||||
)
|
||||
default:
|
||||
return <Badge variant="outline" className="text-xs">Unknown</Badge>
|
||||
}
|
||||
}
|
||||
|
||||
export function McpManager({ config, onUpdate, onConfigUpdate }: McpManagerProps) {
|
||||
const [isAddDialogOpen, setIsAddDialogOpen] = useState(false)
|
||||
const [deleteConfirmServer, setDeleteConfirmServer] = useState<{ id: string; name: string } | null>(null)
|
||||
const [togglingServerId, setTogglingServerId] = useState<string | null>(null)
|
||||
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const toggleServerMutation = useMutation({
|
||||
mutationFn: async ({ serverId, enabled }: { serverId: string; enabled: boolean }) => {
|
||||
if (!config) return
|
||||
|
||||
setTogglingServerId(serverId)
|
||||
|
||||
const currentMcp = (config.content?.mcp as Record<string, any>) || {}
|
||||
const serverConfig = currentMcp[serverId]
|
||||
|
||||
if (!serverConfig) return
|
||||
|
||||
const updatedConfig = {
|
||||
...config.content,
|
||||
mcp: {
|
||||
...currentMcp,
|
||||
[serverId]: {
|
||||
...serverConfig,
|
||||
enabled,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
await onUpdate(updatedConfig)
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode-config'] })
|
||||
},
|
||||
onSettled: () => {
|
||||
setTogglingServerId(null)
|
||||
},
|
||||
})
|
||||
const {
|
||||
status: mcpStatus,
|
||||
isLoading: isLoadingStatus,
|
||||
refetch: refetchStatus,
|
||||
connect,
|
||||
disconnect,
|
||||
authenticate,
|
||||
isToggling
|
||||
} = useMcpServers()
|
||||
|
||||
const deleteServerMutation = useMutation({
|
||||
mutationFn: async (serverId: string) => {
|
||||
if (!config) return
|
||||
|
||||
const currentMcp = (config.content?.mcp as Record<string, any>) || {}
|
||||
const { [serverId]: _deleted, ...rest } = currentMcp
|
||||
const currentMcp = (config.content?.mcp as Record<string, McpServerConfig>) || {}
|
||||
const { [serverId]: _, ...rest } = currentMcp
|
||||
void _
|
||||
|
||||
const updatedConfig = {
|
||||
...config.content,
|
||||
@@ -82,16 +94,34 @@ export function McpManager({ config, onUpdate, onConfigUpdate }: McpManagerProps
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode-config'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['mcp-status'] })
|
||||
setDeleteConfirmServer(null)
|
||||
},
|
||||
})
|
||||
|
||||
const mcpServers = config?.content?.mcp as Record<string, McpServerConfig> || {}
|
||||
|
||||
const isAnyOperationPending = toggleServerMutation.isPending || deleteServerMutation.isPending || togglingServerId !== null
|
||||
const isAnyOperationPending = deleteServerMutation.isPending || togglingServerId !== null || isToggling
|
||||
|
||||
const handleToggleServer = (serverId: string, enabled: boolean) => {
|
||||
toggleServerMutation.mutate({ serverId, enabled })
|
||||
const handleToggleServer = async (serverId: string) => {
|
||||
const currentStatus = mcpStatus?.[serverId]
|
||||
if (!currentStatus) return
|
||||
|
||||
setTogglingServerId(serverId)
|
||||
try {
|
||||
if (currentStatus.status === 'connected') {
|
||||
await disconnect(serverId)
|
||||
} else if (currentStatus.status === 'disabled') {
|
||||
await connect(serverId)
|
||||
} else if (currentStatus.status === 'needs_auth') {
|
||||
await authenticate(serverId)
|
||||
} else if (currentStatus.status === 'failed') {
|
||||
await connect(serverId)
|
||||
}
|
||||
} finally {
|
||||
setTogglingServerId(null)
|
||||
refetchStatus()
|
||||
}
|
||||
}
|
||||
|
||||
const handleDeleteServer = () => {
|
||||
@@ -125,6 +155,14 @@ export function McpManager({ config, onUpdate, onConfigUpdate }: McpManagerProps
|
||||
return 'MCP server'
|
||||
}
|
||||
|
||||
const getErrorMessage = (serverId: string): string | null => {
|
||||
const status = mcpStatus?.[serverId]
|
||||
if (!status) return null
|
||||
if (status.status === 'failed') return status.error
|
||||
if (status.status === 'needs_client_registration') return status.error
|
||||
return null
|
||||
}
|
||||
|
||||
if (!config) {
|
||||
return (
|
||||
<div className="text-center py-8">
|
||||
@@ -155,19 +193,29 @@ export function McpManager({ config, onUpdate, onConfigUpdate }: McpManagerProps
|
||||
Manage Model Context Protocol servers for {config.name}
|
||||
</p>
|
||||
</div>
|
||||
<Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button className='mr-1 h-6'>
|
||||
<Plus className="h-4 w-4" />
|
||||
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<AddMcpServerDialog
|
||||
open={isAddDialogOpen}
|
||||
onOpenChange={setIsAddDialogOpen}
|
||||
onUpdate={onConfigUpdate}
|
||||
/>
|
||||
</Dialog>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-6"
|
||||
onClick={() => refetchStatus()}
|
||||
disabled={isLoadingStatus}
|
||||
>
|
||||
<RefreshCw className={`h-3 w-3 ${isLoadingStatus ? 'animate-spin' : ''}`} />
|
||||
</Button>
|
||||
<Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button className='mr-1 h-6'>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<AddMcpServerDialog
|
||||
open={isAddDialogOpen}
|
||||
onOpenChange={setIsAddDialogOpen}
|
||||
onUpdate={onConfigUpdate}
|
||||
/>
|
||||
</Dialog>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{Object.keys(mcpServers).length === 0 ? (
|
||||
@@ -178,58 +226,70 @@ export function McpManager({ config, onUpdate, onConfigUpdate }: McpManagerProps
|
||||
</Card>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{Object.entries(mcpServers).map(([serverId, serverConfig]) => (
|
||||
<Card key={serverId}>
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
{serverConfig.type === 'local' ? (
|
||||
<Terminal className="h-4 w-4 text-muted-foreground" />
|
||||
) : (
|
||||
<Globe className="h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
<CardTitle className="text-base">{getServerDisplayName(serverId)}</CardTitle>
|
||||
{Object.entries(mcpServers).map(([serverId, serverConfig]) => {
|
||||
const status = mcpStatus?.[serverId]
|
||||
const isConnected = status?.status === 'connected'
|
||||
const errorMessage = getErrorMessage(serverId)
|
||||
|
||||
return (
|
||||
<Card key={serverId} className={errorMessage ? 'border-red-500/50' : ''}>
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
{serverConfig.type === 'local' ? (
|
||||
<Terminal className="h-4 w-4 text-muted-foreground" />
|
||||
) : (
|
||||
<Globe className="h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
<CardTitle className="text-base">{getServerDisplayName(serverId)}</CardTitle>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{status ? getStatusBadge(status) : (
|
||||
<Badge variant="outline" className="text-xs">Loading...</Badge>
|
||||
)}
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{serverConfig.type}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant={serverConfig.enabled ? 'default' : 'secondary'} className="text-xs">
|
||||
{serverConfig.enabled ? 'Enabled' : 'Disabled'}
|
||||
</Badge>
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{serverConfig.type}
|
||||
</Badge>
|
||||
<Switch
|
||||
checked={isConnected}
|
||||
onCheckedChange={() => handleToggleServer(serverId)}
|
||||
disabled={isAnyOperationPending || togglingServerId === serverId}
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setDeleteConfirmServer({ id: serverId, name: getServerDisplayName(serverId) })}
|
||||
className="text-red-500 hover:text-red-600"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
checked={serverConfig.enabled}
|
||||
onCheckedChange={(enabled) => handleToggleServer(serverId, enabled)}
|
||||
disabled={isAnyOperationPending}
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setDeleteConfirmServer({ id: serverId, name: getServerDisplayName(serverId) })}
|
||||
className="text-red-500 hover:text-red-600"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent className='p-2'>
|
||||
<div className="text-sm text-muted-foreground space-y-1">
|
||||
<p>{getServerDescription(serverConfig)}</p>
|
||||
{serverConfig.timeout && (
|
||||
<p>Timeout: {serverConfig.timeout}ms</p>
|
||||
)}
|
||||
{serverConfig.environment && Object.keys(serverConfig.environment).length > 0 && (
|
||||
<p>Environment variables: {Object.keys(serverConfig.environment).length} configured</p>
|
||||
)}
|
||||
{errorMessage && (
|
||||
<div className="flex items-start gap-2 mt-2 p-2 bg-red-500/10 rounded text-red-600 text-xs">
|
||||
<XCircle className="h-4 w-4 flex-shrink-0 mt-0.5" />
|
||||
<span className="break-words">{errorMessage}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className='p-2'>
|
||||
<div className="text-sm text-muted-foreground space-y-1">
|
||||
<p>{getServerDescription(serverConfig)}</p>
|
||||
{serverConfig.timeout && (
|
||||
<p>Timeout: {serverConfig.timeout}ms</p>
|
||||
)}
|
||||
{serverConfig.environment && Object.keys(serverConfig.environment).length > 0 && (
|
||||
<p>Environment variables: {Object.keys(serverConfig.environment).length} configured</p>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { mcpApi } from '@/api/mcp'
|
||||
import type { McpStatusMap, McpServerConfig, McpStatus } from '@/api/mcp'
|
||||
import { showToast as toast } from '@/lib/toast'
|
||||
|
||||
export function useMcpServers() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const statusQuery = useQuery({
|
||||
queryKey: ['mcp-status'],
|
||||
queryFn: () => mcpApi.getStatus(),
|
||||
refetchInterval: 5000,
|
||||
staleTime: 2000,
|
||||
})
|
||||
|
||||
const addServerMutation = useMutation({
|
||||
mutationFn: ({ name, config }: { name: string; config: McpServerConfig }) =>
|
||||
mcpApi.addServer(name, config),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['mcp-status'] })
|
||||
toast.success('MCP server added successfully')
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error(`Failed to add MCP server: ${error.message}`)
|
||||
},
|
||||
})
|
||||
|
||||
const connectMutation = useMutation({
|
||||
mutationFn: (name: string) => mcpApi.connect(name),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['mcp-status'] })
|
||||
toast.success('MCP server connected')
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error(`Failed to connect MCP server: ${error.message}`)
|
||||
},
|
||||
})
|
||||
|
||||
const disconnectMutation = useMutation({
|
||||
mutationFn: (name: string) => mcpApi.disconnect(name),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['mcp-status'] })
|
||||
toast.success('MCP server disconnected')
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error(`Failed to disconnect MCP server: ${error.message}`)
|
||||
},
|
||||
})
|
||||
|
||||
const startAuthMutation = useMutation({
|
||||
mutationFn: (name: string) => mcpApi.startAuth(name),
|
||||
onError: (error: Error) => {
|
||||
toast.error(`Failed to start authentication: ${error.message}`)
|
||||
},
|
||||
})
|
||||
|
||||
const completeAuthMutation = useMutation({
|
||||
mutationFn: ({ name, code }: { name: string; code: string }) =>
|
||||
mcpApi.completeAuth(name, code),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['mcp-status'] })
|
||||
toast.success('Authentication completed')
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error(`Failed to complete authentication: ${error.message}`)
|
||||
},
|
||||
})
|
||||
|
||||
const authenticateMutation = useMutation({
|
||||
mutationFn: (name: string) => mcpApi.authenticate(name),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['mcp-status'] })
|
||||
toast.success('Authentication completed')
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error(`Failed to authenticate: ${error.message}`)
|
||||
},
|
||||
})
|
||||
|
||||
const removeAuthMutation = useMutation({
|
||||
mutationFn: (name: string) => mcpApi.removeAuth(name),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['mcp-status'] })
|
||||
toast.success('Authentication credentials removed')
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error(`Failed to remove authentication: ${error.message}`)
|
||||
},
|
||||
})
|
||||
|
||||
const toggleServer = async (name: string, currentStatus: McpStatus) => {
|
||||
if (currentStatus.status === 'connected') {
|
||||
return disconnectMutation.mutateAsync(name)
|
||||
} else if (currentStatus.status === 'disabled') {
|
||||
return connectMutation.mutateAsync(name)
|
||||
} else if (currentStatus.status === 'needs_auth') {
|
||||
return authenticateMutation.mutateAsync(name)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
status: statusQuery.data as McpStatusMap | undefined,
|
||||
isLoading: statusQuery.isLoading,
|
||||
isError: statusQuery.isError,
|
||||
error: statusQuery.error,
|
||||
refetch: statusQuery.refetch,
|
||||
|
||||
addServer: addServerMutation.mutate,
|
||||
addServerAsync: addServerMutation.mutateAsync,
|
||||
isAddingServer: addServerMutation.isPending,
|
||||
|
||||
connect: connectMutation.mutate,
|
||||
connectAsync: connectMutation.mutateAsync,
|
||||
isConnecting: connectMutation.isPending,
|
||||
|
||||
disconnect: disconnectMutation.mutate,
|
||||
disconnectAsync: disconnectMutation.mutateAsync,
|
||||
isDisconnecting: disconnectMutation.isPending,
|
||||
|
||||
toggleServer,
|
||||
isToggling: connectMutation.isPending || disconnectMutation.isPending || authenticateMutation.isPending,
|
||||
|
||||
startAuth: startAuthMutation.mutate,
|
||||
startAuthAsync: startAuthMutation.mutateAsync,
|
||||
isStartingAuth: startAuthMutation.isPending,
|
||||
|
||||
completeAuth: completeAuthMutation.mutate,
|
||||
completeAuthAsync: completeAuthMutation.mutateAsync,
|
||||
isCompletingAuth: completeAuthMutation.isPending,
|
||||
|
||||
authenticate: authenticateMutation.mutate,
|
||||
authenticateAsync: authenticateMutation.mutateAsync,
|
||||
isAuthenticating: authenticateMutation.isPending,
|
||||
|
||||
removeAuth: removeAuthMutation.mutate,
|
||||
removeAuthAsync: removeAuthMutation.mutateAsync,
|
||||
isRemovingAuth: removeAuthMutation.isPending,
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user