Outbound MCP connections: Notion-style client integrations (Settings -> MCP)
Superbrain dials external MCP servers as a client (official modelcontextprotocol/go-sdk): Streamable HTTP or SSE, none/bearer/header auth. Management surface /api/mcp/connections (CRUD + test) with the house disciplines: - secrets encrypted at rest (internal/crypto), masked in every response, write-only (mask or omission keeps the stored value); authKind none clears them - mutating PATCH carries version (409 on stale); mask-only PATCH is a documented no-op returning the current projection - dials netguard-pinned (public ranges, ports 80/443 outside tests), no redirect following, header names restricted to RFC 7230 tokens - test endpoint: per-user limiter + shared outbound budget; 502 with an error class on dial/auth failure, never a silent ok; returns the tool list for the UI - cap of 10 connections per user under the user lock UI: Settings -> MCP tab (components/mcp-settings.tsx) — list with enable switch, add/edit dialog (secret never prefilled), Test showing the live tool list or the server's error verbatim. Migration 018 + schema.sql; integration test drives a go-sdk fake MCP server (incl. a Bearer-secured one) end to end. Tool USE by the assistant is phase 2.
This commit is contained in:
@@ -5,13 +5,14 @@ import { useSession } from 'next-auth/react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
|
||||
import { User, Mail, Server, Cloud, Shield, Bell, Sparkles, Bot, KeyRound, Check, X, AlertTriangle } from 'lucide-react'
|
||||
import { User, Mail, Server, Cloud, Shield, Bell, Sparkles, Bot, KeyRound, PlugZap, Check, X, AlertTriangle } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { invalidateReference } from '@/lib/reference-data'
|
||||
import { NotificationsSettings } from '@/components/notifications-settings'
|
||||
import { AutomationsSettings } from '@/components/automations-settings'
|
||||
import { AiSettings } from '@/components/ai-settings'
|
||||
import { ApiKeysSettings } from '@/components/api-keys-settings'
|
||||
import { McpSettings } from '@/components/mcp-settings'
|
||||
import type { OidcStatus } from '@/lib/oidc-config'
|
||||
|
||||
export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callbackUrl: string }) {
|
||||
@@ -103,6 +104,7 @@ export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callba
|
||||
<TabsTrigger value="automations" className="gap-1.5"><Sparkles className="h-3.5 w-3.5" /> Automations</TabsTrigger>
|
||||
<TabsTrigger value="ai" className="gap-1.5"><Bot className="h-3.5 w-3.5" /> AI</TabsTrigger>
|
||||
<TabsTrigger value="api-keys" className="gap-1.5"><KeyRound className="h-3.5 w-3.5" /> API Keys</TabsTrigger>
|
||||
<TabsTrigger value="mcp" className="gap-1.5"><PlugZap className="h-3.5 w-3.5" /> MCP</TabsTrigger>
|
||||
<TabsTrigger value="oidc" className="gap-1.5"><Shield className="h-3.5 w-3.5" /> OIDC</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
@@ -196,6 +198,10 @@ export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callba
|
||||
<ApiKeysSettings />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="mcp" className="space-y-4 mt-4">
|
||||
<McpSettings />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="oidc" className="space-y-4 mt-4">
|
||||
<div className="rounded-lg border p-4 space-y-3">
|
||||
<h3 className="font-medium flex items-center gap-2"><Shield className="h-4 w-4" /> OIDC Configuration</h3>
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
'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 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
|
||||
}
|
||||
|
||||
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 [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 : []))
|
||||
.catch(() => toast.error('Could not load MCP connections'))
|
||||
.finally(() => setLoading(false)), [])
|
||||
|
||||
useEffect(() => { reload() }, [reload])
|
||||
|
||||
const openCreate = () => setForm({ ...emptyForm })
|
||||
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’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>
|
||||
|
||||
{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 items-center gap-2">
|
||||
<Switch checked={c.enabled} onCheckedChange={() => toggle(c)} aria-label={`Enable ${c.name}`} />
|
||||
<span className="text-sm font-medium truncate">{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)` : '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>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user