import { useState } from 'react' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' import { Loader2 } from 'lucide-react' import { Switch } from '@/components/ui/switch' import { mcpOAuthRedirectUri, type McpServerConfig, type McpTimeoutConfig, } from '@opencode-manager/shared/opencode' import { useMutation, useQueryClient } from '@tanstack/react-query' interface AddMcpServerDialogProps { open: boolean onOpenChange: (open: boolean) => void onSubmit: (serverId: string, config: McpServerConfig) => Promise showConnectToggle?: boolean } interface KeyValueEntry { key: string value: string } function toRecord(entries: KeyValueEntry[]): Record | undefined { const record = Object.fromEntries( entries .filter((entry) => entry.key.trim() && entry.value.trim()) .map((entry) => [entry.key.trim(), entry.value.trim()]), ) return Object.keys(record).length > 0 ? record : undefined } interface KeyValueRowsProps { label: string hint: string entries: KeyValueEntry[] onChange: (entries: KeyValueEntry[]) => void keyPlaceholder: string valuePlaceholder: string } function KeyValueRows({ label, hint, entries, onChange, keyPlaceholder, valuePlaceholder }: KeyValueRowsProps) { const updateEntry = (index: number, field: keyof KeyValueEntry, value: string) => { onChange(entries.map((entry, i) => (i === index ? { ...entry, [field]: value } : entry))) } return (
{entries.map((entry, index) => (
updateEntry(index, 'key', e.target.value)} placeholder={keyPlaceholder} aria-label={`${label} name ${index + 1}`} className="bg-background border-border font-mono" /> updateEntry(index, 'value', e.target.value)} placeholder={valuePlaceholder} aria-label={`${label} value ${index + 1}`} className="bg-background border-border font-mono" />
))}

{hint}

) } export function AddMcpServerDialog({ open, onOpenChange, onSubmit, showConnectToggle = true }: AddMcpServerDialogProps) { const [serverId, setServerId] = useState('') const [serverType, setServerType] = useState<'local' | 'remote'>('local') const [command, setCommand] = useState('') const [url, setUrl] = useState('') const [environment, setEnvironment] = useState([]) const [headers, setHeaders] = useState([]) const [timeout, setTimeout] = useState('') const [enabled, setEnabled] = useState(true) const [oauthEnabled, setOauthEnabled] = useState(false) const [oauthClientId, setOauthClientId] = useState('') const [oauthClientSecret, setOauthClientSecret] = useState('') const [oauthScope, setOauthScope] = useState('') const queryClient = useQueryClient() const buildTimeout = (): McpTimeoutConfig | undefined => { const parsed = parseInt(timeout) return Number.isFinite(parsed) ? { catalog: parsed, execution: parsed } : undefined } const buildMcpServerConfig = (): McpServerConfig => { const timeoutConfig = buildTimeout() const shared = { disabled: !enabled, ...(timeoutConfig ? { timeout: timeoutConfig } : {}), } if (serverType === 'local') { const commandArray = command.split(' ').filter((arg) => arg.trim()) if (commandArray.length === 0) { throw new Error('Command is required for local MCP servers') } const environmentVariables = toRecord(environment) return { type: 'local', command: commandArray, ...(environmentVariables ? { environment: environmentVariables } : {}), ...shared, } } if (!url.trim()) { throw new Error('URL is required for remote MCP servers') } const requestHeaders = toRecord(headers) return { type: 'remote', url: url.trim(), ...(requestHeaders ? { headers: requestHeaders } : {}), oauth: oauthEnabled ? { ...(oauthClientId.trim() ? { client_id: oauthClientId.trim() } : {}), ...(oauthClientSecret.trim() ? { client_secret: oauthClientSecret.trim() } : {}), ...(oauthScope.trim() ? { scope: oauthScope.trim() } : {}), redirect_uri: mcpOAuthRedirectUri(window.location.origin), } : false, ...shared, } } const addMcpServerMutation = useMutation({ mutationFn: () => onSubmit(serverId, buildMcpServerConfig()), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['mcp-status'] }) handleClose() }, }) const handleAdd = () => { if (serverId) { addMcpServerMutation.mutate() } } const handleClose = () => { setServerId('') setServerType('local') setCommand('') setUrl('') setEnvironment([]) setHeaders([]) setTimeout('') setEnabled(true) setOauthEnabled(false) setOauthClientId('') setOauthClientSecret('') setOauthScope('') onOpenChange(false) } const isPending = addMcpServerMutation.isPending return ( Add MCP Server
setServerId(e.target.value)} placeholder="e.g., filesystem, git, my-server" className="bg-background border-border" />

Unique identifier for this MCP server (lowercase, no spaces)

{serverType === 'local' ? (
setCommand(e.target.value)} placeholder="npx @modelcontextprotocol/server-filesystem /tmp" className="bg-background border-border font-mono" />

Command and arguments to run the MCP server

) : (
setUrl(e.target.value)} placeholder="http://localhost:3000/mcp" className="bg-background border-border font-mono" />

URL of the remote MCP server

)} {serverType === 'remote' && (
{oauthEnabled && (

Leave fields blank to use the server's default OAuth discovery

setOauthClientId(e.target.value)} placeholder="Optional" className="bg-background border-border font-mono" />
setOauthClientSecret(e.target.value)} placeholder="Optional" className="bg-background border-border font-mono" />
setOauthScope(e.target.value)} placeholder="e.g., read write" className="bg-background border-border font-mono" />
)}
)} {serverType === 'local' && ( )} {serverType === 'remote' && ( )}
setTimeout(e.target.value)} placeholder="5000" className="bg-background border-border" />

Timeout in milliseconds for listing and calling tools

{showConnectToggle && (
)}
) }