Files
superbrain/web/components/mcp-settings.tsx
T
Andrew S Erwin a167e376f7 MCP settings: suggestion catalog for GitHub, HubSpot and Make
The connections list now serves a shipped catalog of well-known hosted
MCP servers (data in the binary, like the entitlements catalog — never a
TIER fork). 'Use' prefills name/url/transport/authKind and shows a
secretHint placeholder; the credential stays the user's to paste
(write-only discipline unchanged).

Verified against vendor docs: GitHub (api.githubcopilot.com/mcp/) and
Make (<zone>.make.com/mcp/v2) accept Bearer tokens and are connectable
today. HubSpot's remote MCP (mcp.hubspot.com) requires OAuth 2.1 + PKCE
with no static-token path — the client speaks none/bearer/header only,
so the entry is shown honestly labeled 'OAuth required' with a note and
docs link, and NO Use button. Go test asserts the catalog; browser
regression covers the prefill and the HubSpot treatment.
2026-11-25 00:51:23 -06:00

289 lines
14 KiB
TypeScript

'use client'
// Settings → MCP: Notion-style connections UI for OUTBOUND MCP servers.
// Superbrain dials these as a client (internal/mcpclient) so its AI can use
// their tools; this surface manages them. House disciplines visible here:
// secrets are write-only (never prefilled; the mask round-trips unchanged),
// every mutating PATCH carries the row version (409 reloads), and plan or
// policy refusals surface the server's message — the UI never guesses.
import { useCallback, useEffect, useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Switch } from '@/components/ui/switch'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Loader2, PlugZap, Plus, Trash2, FlaskConical } from 'lucide-react'
import { toast } from 'sonner'
const KEY_MASK = '••••••••'
type McpConnection = {
id: string; name: string; url: string; transport: string; authKind: string
headerName: string; secret: string; enabled: boolean; version: number
}
type Suggestion = {
kind: string; name: string; url: string; transport: string; authKind: string
available: boolean; description?: string; secretHint?: string; note?: string; docsUrl?: string
}
type TestResult = { ok: boolean; count?: number; tools?: { name: string; description: string }[]; error?: string }
type FormState = {
id: string | null; version: number
name: string; url: string; transport: string; authKind: string; headerName: string
secret: string; hasStoredSecret: boolean; secretHint?: string
}
const emptyForm: FormState = {
id: null, version: 0, name: '', url: '', transport: 'streamable-http',
authKind: 'none', headerName: '', secret: '', hasStoredSecret: false,
}
async function api(path: string, init?: RequestInit): Promise<Response> {
return fetch(path, { headers: { 'Content-Type': 'application/json' }, cache: 'no-store', ...init })
}
export function McpSettings() {
const [connections, setConnections] = useState<McpConnection[]>([])
const [suggestions, setSuggestions] = useState<Suggestion[]>([])
const [loading, setLoading] = useState(true)
const [form, setForm] = useState<FormState | null>(null)
const [saving, setSaving] = useState(false)
const [testing, setTesting] = useState<string | null>(null)
const [results, setResults] = useState<Record<string, TestResult>>({})
const reload = useCallback(() =>
api('/api/mcp/connections')
.then(r => r.json())
.then(data => {
setConnections(Array.isArray(data?.connections) ? data.connections : [])
setSuggestions(Array.isArray(data?.suggestions) ? data.suggestions : [])
})
.catch(() => toast.error('Could not load MCP connections'))
.finally(() => setLoading(false)), [])
useEffect(() => { reload() }, [reload])
const openCreate = () => setForm({ ...emptyForm })
// A suggestion prefills everything except the credential — the user still
// pastes their own token and confirms (write-only discipline unchanged).
const openSuggestion = (s: Suggestion) => setForm({
...emptyForm, name: s.name, url: s.url, transport: s.transport,
authKind: s.authKind, secretHint: s.secretHint,
})
const openEdit = (c: McpConnection) => setForm({
id: c.id, version: c.version, name: c.name, url: c.url, transport: c.transport,
authKind: c.authKind, headerName: c.headerName, secret: '', hasStoredSecret: c.secret === KEY_MASK,
})
const save = async () => {
if (!form) return
const body: Record<string, unknown> = {
name: form.name.trim(), url: form.url.trim(), transport: form.transport,
authKind: form.authKind, headerName: form.headerName.trim(),
}
// Write-only secret: send only what the user typed; the mask (or an
// empty field) tells the server to keep the stored value.
if (form.secret) body.secret = form.secret
setSaving(true)
try {
const res = form.id
? await api(`/api/mcp/connections/${form.id}`, { method: 'PATCH', body: JSON.stringify({ ...body, version: form.version }) })
: await api('/api/mcp/connections', { method: 'POST', body: JSON.stringify(body) })
const data = await res.json().catch(() => null)
if (res.status === 409) {
toast.error('Connection changed elsewhere — reloaded')
await reload()
setForm(null)
return
}
if (!res.ok) { toast.error(data?.error ?? 'Could not save the connection'); return }
toast.success(form.id ? 'Connection updated' : 'Connection added')
setForm(null)
await reload()
} catch { toast.error('Could not save the connection') }
finally { setSaving(false) }
}
const test = async (c: McpConnection) => {
setTesting(c.id)
setResults(prev => ({ ...prev, [c.id]: undefined as unknown as TestResult }))
try {
const res = await api(`/api/mcp/connections/${c.id}/test`, { method: 'POST', body: '{}' })
const data = await res.json().catch(() => null)
setResults(prev => ({ ...prev, [c.id]: data as TestResult }))
if (res.ok && data?.ok) toast.success(`${data.count} tool${data.count === 1 ? '' : 's'} available`)
} catch { setResults(prev => ({ ...prev, [c.id]: { ok: false, error: 'Network error' } })) }
finally { setTesting(null) }
}
const toggle = async (c: McpConnection) => {
const res = await api(`/api/mcp/connections/${c.id}`, {
method: 'PATCH', body: JSON.stringify({ enabled: !c.enabled, version: c.version }),
})
if (res.status === 409) { toast.error('Connection changed elsewhere — reloaded'); await reload(); return }
if (!res.ok) { toast.error((await res.json().catch(() => null))?.error ?? 'Could not update'); return }
await reload()
}
const remove = async (c: McpConnection) => {
const res = await api(`/api/mcp/connections/${c.id}`, { method: 'DELETE' })
if (res.ok) { toast.success(`Removed ${c.name}`); await reload() }
else toast.error((await res.json().catch(() => null))?.error ?? 'Could not remove')
}
if (loading) {
return (
<div className="rounded-lg border p-4 flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" /> Loading MCP connections…
</div>
)
}
return (
<div className="rounded-lg border p-4 space-y-4">
<div className="flex items-start justify-between gap-3">
<div>
<h3 className="font-medium flex items-center gap-2"><PlugZap className="h-4 w-4" /> MCP connections</h3>
<p className="text-sm text-muted-foreground mt-1">
Connect Superbrain&rsquo;s AI to external MCP servers (Streamable HTTP or SSE).
Credentials are encrypted at rest and never shown again after saving.
</p>
</div>
<Button size="sm" onClick={openCreate}><Plus className="h-4 w-4 mr-1" /> Add connection</Button>
</div>
{suggestions.length > 0 && (
<div className="space-y-2">
{suggestions.map(s => (
<div key={s.kind} className="flex items-start gap-3 rounded-md border border-dashed p-3">
<PlugZap className="mt-0.5 h-5 w-5 shrink-0 text-muted-foreground" />
<div className="min-w-0 flex-1 space-y-0.5">
<p className="text-sm font-medium flex items-center gap-2">
{s.name}
{!s.available && <Badge variant="outline" className="text-[10px] text-amber-600 dark:text-amber-400">OAuth required</Badge>}
</p>
{s.description && <p className="text-xs text-muted-foreground">{s.description}</p>}
<p className="truncate text-xs text-muted-foreground font-mono">{s.url}</p>
{s.note && <p className="text-xs text-muted-foreground">{s.note}</p>}
</div>
{s.available
? <Button size="sm" variant="outline" className="shrink-0" onClick={() => openSuggestion(s)}>Use</Button>
: s.docsUrl && (
<a href={s.docsUrl} target="_blank" rel="noreferrer" className="shrink-0 text-xs text-muted-foreground underline hover:text-foreground">Docs</a>
)}
</div>
))}
</div>
)}
{connections.length === 0 ? (
<p className="text-sm text-muted-foreground">No MCP connections yet.</p>
) : (
<ul className="divide-y rounded-md border">
{connections.map(c => (
<li key={c.id} className="space-y-2 p-3">
<div className="flex flex-wrap items-center gap-2">
<Switch checked={c.enabled} onCheckedChange={() => toggle(c)} aria-label={`Enable ${c.name}`} />
<span className="min-w-[6rem] flex-1 truncate text-sm font-medium">{c.name}</span>
<Badge variant="outline" className="shrink-0 font-mono text-[10px]">{c.transport}</Badge>
{c.authKind !== 'none' && <Badge variant="outline" className="shrink-0 text-[10px]">{c.authKind}{c.authKind === 'header' && c.headerName ? `: ${c.headerName}` : ''}</Badge>}
<span className="ml-auto flex items-center gap-1">
<Button size="sm" variant="outline" onClick={() => test(c)} loading={testing === c.id}>
<FlaskConical className="h-3.5 w-3.5 mr-1" /> Test
</Button>
<Button size="sm" variant="ghost" onClick={() => openEdit(c)}>Edit</Button>
<Button size="sm" variant="ghost" onClick={() => remove(c)} aria-label={`Remove ${c.name}`}>
<Trash2 className="h-4 w-4 text-muted-foreground hover:text-destructive" />
</Button>
</span>
</div>
<p className="text-xs text-muted-foreground font-mono truncate">{c.url}</p>
{results[c.id] && (
results[c.id].ok ? (
<div className="rounded-md bg-muted/50 p-2 text-xs space-y-1">
<p className="font-medium">{results[c.id].count} tools</p>
<ul className="max-h-28 space-y-0.5 overflow-y-auto text-muted-foreground">
{results[c.id].tools?.map(t => (
<li key={t.name}><span className="font-mono text-foreground">{t.name}</span>{t.description ? ` — ${t.description.slice(0, 90)}` : ''}</li>
))}
</ul>
</div>
) : (
<p className="rounded-md bg-destructive/10 p-2 text-xs text-destructive">{results[c.id].error}</p>
)
)}
</li>
))}
</ul>
)}
<Dialog open={form !== null} onOpenChange={(open) => { if (!open) setForm(null) }}>
<DialogContent className="max-w-lg">
<DialogHeader><DialogTitle>{form?.id ? 'Edit MCP connection' : 'Add MCP connection'}</DialogTitle></DialogHeader>
{form && (
<div className="space-y-3">
<div>
<label className="text-xs font-medium">Name</label>
<Input value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} placeholder="e.g. House gateway, Maps tools…" maxLength={100} />
</div>
<div>
<label className="text-xs font-medium">Server URL</label>
<Input value={form.url} onChange={e => setForm({ ...form, url: e.target.value })} placeholder="https://mcp.example.tld/mcp" />
<p className="mt-1 text-xs text-muted-foreground">Public http(s) endpoints on ports 80/443 — outbound dials are network-guarded.</p>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="text-xs font-medium">Transport</label>
<Select value={form.transport} onValueChange={v => setForm({ ...form, transport: v })}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="streamable-http">Streamable HTTP</SelectItem>
<SelectItem value="sse">SSE</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<label className="text-xs font-medium">Authentication</label>
<Select value={form.authKind} onValueChange={v => setForm({ ...form, authKind: v })}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="none">None</SelectItem>
<SelectItem value="bearer">Bearer token</SelectItem>
<SelectItem value="header">Custom header</SelectItem>
</SelectContent>
</Select>
</div>
</div>
{form.authKind === 'header' && (
<div>
<label className="text-xs font-medium">Header name</label>
<Input value={form.headerName} onChange={e => setForm({ ...form, headerName: e.target.value })} placeholder="X-API-Key" maxLength={100} />
</div>
)}
{form.authKind !== 'none' && (
<div>
<label className="text-xs font-medium">{form.authKind === 'bearer' ? 'Token' : 'Header value'}</label>
<Input
type="password"
value={form.secret}
onChange={e => setForm({ ...form, secret: e.target.value })}
placeholder={form.hasStoredSecret ? `${KEY_MASK} (leave blank to keep)` : (form.secretHint || 'Paste the credential')}
maxLength={2000}
/>
{form.hasStoredSecret && <p className="mt-1 text-xs text-muted-foreground">Stored credentials are never shown; blank keeps the current one.</p>}
</div>
)}
<div className="flex justify-end gap-2 pt-1">
<Button variant="outline" onClick={() => setForm(null)}>Cancel</Button>
<Button onClick={save} loading={saving}>{form.id ? 'Save changes' : 'Add connection'}</Button>
</div>
</div>
)}
</DialogContent>
</Dialog>
</div>
)
}