"use client" import { useEffect, useMemo, useState } from "react" type McpTransport = "stdio" | "http" type McpCatalogEntry = { id: string name: string summary: string websiteUrl?: string transport: McpTransport command: string args: string[] env: Record tags: string[] } type McpServerInstall = McpCatalogEntry & { installedAt: string updatedAt: string source: "catalog" | "custom" | "registry" enabled: boolean accessMode: "disabled" | "allow_all" | "allow_only" allowedSandboxIds: string[] } type McpResponse = { catalog: McpCatalogEntry[] servers: McpServerInstall[] config: Record error?: string } type McpPreflightResult = { ok: boolean checkedAt: string toolCount: number tools: string[] durationMs: number error?: string diagnosis: { summary: string likelyCauses: string[] suggestedFixes: string[] confidence: "low" | "medium" | "high" } } type McpSandbox = { id: string name: string status: string } type McpConfigurationPanelProps = { sandboxes?: McpSandbox[] } const REGISTRY_PAGE_SIZE = 4 function FieldLabel({ children }: { children: React.ReactNode }) { return } function parseLines(value: string) { return value .split(/\r?\n/) .map((line) => line.trim()) .filter(Boolean) } function parseEnv(value: string) { return Object.fromEntries( parseLines(value) .map((line) => { const [key, ...rest] = line.split("=") return [key?.trim() || "", rest.join("=").trim()] }) .filter(([key]) => Boolean(key)), ) } export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurationPanelProps) { const [loading, setLoading] = useState(true) const [saving, setSaving] = useState(false) const [message, setMessage] = useState("") const [catalog, setCatalog] = useState([]) const [servers, setServers] = useState([]) const [config, setConfig] = useState>({ mcpServers: {} }) const [customName, setCustomName] = useState("custom-tools") const [customSummary, setCustomSummary] = useState("Custom MCP server") const [customTransport, setCustomTransport] = useState("stdio") const [customCommand, setCustomCommand] = useState("npx") const [customArgs, setCustomArgs] = useState("-y\n@modelcontextprotocol/server-memory") const [customEnv, setCustomEnv] = useState("") const [uploadFiles, setUploadFiles] = useState([]) const [uploadPaths, setUploadPaths] = useState([]) const [uploadArchive, setUploadArchive] = useState(null) const [uploadRuntime, setUploadRuntime] = useState("python3") const [uploadEntryMode, setUploadEntryMode] = useState<"file" | "python-module" | "console-script">("file") const [uploadEntrypoint, setUploadEntrypoint] = useState("server.py") const [editingServerId, setEditingServerId] = useState(null) const [editorText, setEditorText] = useState("") const [registrySearch, setRegistrySearch] = useState("github") const [registryResults, setRegistryResults] = useState([]) const [registryLoading, setRegistryLoading] = useState(false) const [registryPage, setRegistryPage] = useState(1) const [lastRegistrySearch, setLastRegistrySearch] = useState("") const [preflightResults, setPreflightResults] = useState>({}) const [catalogOpen, setCatalogOpen] = useState(false) const [customOpen, setCustomOpen] = useState(false) const installedIds = useMemo(() => new Set(servers.map((server) => server.id)), [servers]) const enabledCount = servers.filter((server) => server.enabled).length const configText = JSON.stringify(config, null, 2) const registryPageCount = Math.max(1, Math.ceil(registryResults.length / REGISTRY_PAGE_SIZE)) const pagedRegistryResults = registryResults.slice( (registryPage - 1) * REGISTRY_PAGE_SIZE, registryPage * REGISTRY_PAGE_SIZE, ) async function load() { try { setLoading(true) const response = await fetch("/api/mcp", { cache: "no-store" }) const data = await response.json() as McpResponse if (!response.ok) throw new Error(data.error || "Failed to load MCP configuration") setCatalog(Array.isArray(data.catalog) ? data.catalog : []) setServers(Array.isArray(data.servers) ? data.servers : []) setConfig(data.config || { mcpServers: {} }) setMessage("") } catch (error) { setMessage(error instanceof Error ? error.message : "Failed to load MCP configuration") } finally { setLoading(false) } } async function postUpdate(body: Record, success: string) { try { setSaving(true) const response = await fetch("/api/mcp", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }) const data = await response.json() as McpResponse if (!response.ok) throw new Error(data.error || "Failed to update MCP configuration") setCatalog(Array.isArray(data.catalog) ? data.catalog : catalog) setServers(Array.isArray(data.servers) ? data.servers : []) setConfig(data.config || { mcpServers: {} }) setMessage(success) return true } catch (error) { setMessage(error instanceof Error ? error.message : "Failed to update MCP configuration") return false } finally { setSaving(false) } } function sandboxAllowed(server: McpServerInstall, sandbox: McpSandbox) { return server.allowedSandboxIds.includes(sandbox.id) || server.allowedSandboxIds.includes(sandbox.name) } function toggleServerSandbox(server: McpServerInstall, sandbox: McpSandbox, allowed: boolean) { const current = new Set(server.allowedSandboxIds) current.delete(sandbox.id) current.delete(sandbox.name) if (allowed) current.add(sandbox.id) const hasOtherMcpAccess = servers.some((candidate) => candidate.id !== server.id && sandboxAllowed(candidate, sandbox)) return postUpdate({ action: "update-access", serverId: server.id, accessMode: "allow_only", allowedSandboxIds: Array.from(current), }, `${server.name} sandbox access updated.`).then((updated) => { if (!updated) return return syncSandboxBrokerConfig(sandbox, allowed || hasOtherMcpAccess ? "sync" : "revoke") }) } async function syncSandboxBrokerConfig(sandbox: McpSandbox, action: "sync" | "revoke" = "sync") { try { setSaving(true) const response = await fetch(`/api/sandbox/${encodeURIComponent(sandbox.id)}/mcp`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ sandboxName: sandbox.name, action }), }) const data = await response.json() if (!response.ok) throw new Error(data.error || "Failed to sync MCP broker config") setMessage(data.note || (action === "revoke" ? `${sandbox.name} MCP broker config revoked.` : `${sandbox.name} MCP broker config synced.`)) } catch (error) { setMessage(error instanceof Error ? error.message : "Failed to sync MCP broker config") } finally { setSaving(false) } } async function syncAccessModeChange(server: McpServerInstall, accessMode: string) { const updated = await postUpdate({ action: "update-access", serverId: server.id, accessMode, }, `${server.name} availability updated.`) if (!updated) return if (accessMode === "allow_all") { await Promise.all(sandboxes.map((sandbox) => syncSandboxBrokerConfig(sandbox))) return } if (accessMode === "disabled") { await Promise.all(sandboxes .filter((sandbox) => sandboxAllowed(server, sandbox)) .map((sandbox) => { const hasOtherMcpAccess = servers.some((candidate) => candidate.id !== server.id && sandboxAllowed(candidate, sandbox)) return syncSandboxBrokerConfig(sandbox, hasOtherMcpAccess ? "sync" : "revoke") })) } } async function setServerEnabled(server: McpServerInstall, enabled: boolean) { const updated = await postUpdate({ action: "update-access", serverId: server.id, enabled, }, `${server.name} ${enabled ? "enabled" : "disabled"}.`) if (!updated) return const affectedSandboxes = sandboxes.filter((sandbox) => sandboxAllowed(server, sandbox)) await Promise.all(affectedSandboxes.map((sandbox) => { const hasOtherMcpAccess = servers.some((candidate) => candidate.id !== server.id && sandboxAllowed(candidate, sandbox)) return syncSandboxBrokerConfig(sandbox, enabled || hasOtherMcpAccess ? "sync" : "revoke") })) } function editableServerJson(server: McpServerInstall) { return JSON.stringify({ id: server.id, name: server.name, summary: server.summary, websiteUrl: server.websiteUrl || "", transport: server.transport, command: server.command, args: server.args, env: server.env, tags: server.tags, enabled: server.enabled, accessMode: server.accessMode, allowedSandboxIds: server.allowedSandboxIds, source: server.source, }, null, 2) } function serverPayloadFromJson(text: string, fallbackId = "uploaded-server") { const parsed = JSON.parse(text) const firstMcpEntry = parsed?.mcpServers && typeof parsed.mcpServers === "object" ? Object.entries(parsed.mcpServers)[0] : null const id = firstMcpEntry?.[0] || parsed?.id || parsed?.name || fallbackId const body = firstMcpEntry?.[1] && typeof firstMcpEntry[1] === "object" ? firstMcpEntry[1] as Record : parsed const command = typeof body?.command === "string" ? body.command : typeof body?.url === "string" ? body.url : typeof parsed?.command === "string" ? parsed.command : typeof parsed?.url === "string" ? parsed.url : "" const transport = body?.url || parsed?.transport === "http" ? "http" : "stdio" return { action: "install", id, name: parsed?.name || id, summary: parsed?.summary || "Uploaded MCP server", websiteUrl: parsed?.websiteUrl || "", transport, command, args: Array.isArray(body?.args) ? body.args : Array.isArray(parsed?.args) ? parsed.args : [], env: typeof body?.env === "object" && body.env ? body.env : typeof body?.headers === "object" && body.headers ? body.headers : parsed?.env || {}, tags: Array.isArray(parsed?.tags) ? parsed.tags : ["uploaded"], source: parsed?.source || "custom", enabled: typeof parsed?.enabled === "boolean" ? parsed.enabled : true, accessMode: parsed?.accessMode, allowedSandboxIds: parsed?.allowedSandboxIds, } } function chooseUploadDirectory(fileList: FileList | null) { const files = Array.from(fileList || []) setUploadFiles(files) setUploadPaths(files.map((file) => { const withRelativePath = file as File & { webkitRelativePath?: string } return withRelativePath.webkitRelativePath || file.name })) if (files.length > 0) setUploadArchive(null) } function chooseUploadArchive(file: File | null) { setUploadArchive(file) if (file) { setUploadFiles([]) setUploadPaths([]) } } function summarizePreflight(preflight: McpPreflightResult) { if (preflight.ok) { return `${preflight.diagnosis.summary}${preflight.tools.length > 0 ? ` Tools: ${preflight.tools.join(", ")}.` : ""}` } const causes = preflight.diagnosis.likelyCauses.length > 0 ? `\nLikely: ${preflight.diagnosis.likelyCauses.join(" ")}` : "" const fixes = preflight.diagnosis.suggestedFixes.length > 0 ? `\nTry: ${preflight.diagnosis.suggestedFixes.join(" ")}` : "" return `${preflight.diagnosis.summary}\n${preflight.error || "MCP tool discovery failed."}${causes}${fixes}` } async function preflightServer(server: McpServerInstall) { try { setSaving(true) const response = await fetch("/api/mcp/preflight", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ serverId: server.id }), }) const data = await response.json() as { preflight?: McpPreflightResult; error?: string } if (!response.ok || !data.preflight) throw new Error(data.error || "Failed to preflight MCP server") setPreflightResults((current) => ({ ...current, [server.id]: data.preflight as McpPreflightResult })) setMessage(`${server.name} preflight ${data.preflight.ok ? "passed" : "failed"}.\n${summarizePreflight(data.preflight)}`) } catch (error) { setMessage(error instanceof Error ? error.message : "Failed to preflight MCP server") } finally { setSaving(false) } } async function uploadServer() { try { if (!uploadArchive && uploadFiles.length === 0) { setMessage("Choose a server directory or archive before uploading.") return } setSaving(true) const form = new FormData() form.set("id", customName) form.set("name", customName) form.set("summary", customSummary) form.set("runtime", uploadRuntime) form.set("entryMode", uploadEntryMode) form.set("entrypoint", uploadEntrypoint) form.set("args", customArgs) form.set("env", customEnv) if (uploadArchive) { form.set("archive", uploadArchive) } else { uploadFiles.forEach((file, index) => { form.append("files", file) form.append("paths", uploadPaths[index] || file.name) }) } const response = await fetch("/api/mcp/upload", { method: "POST", body: form }) const data = await response.json() as McpResponse & { dependencyInstall?: { kind?: string; logs?: string[] }; preflight?: McpPreflightResult; server?: McpServerInstall } if (!response.ok) throw new Error(data.error || "Failed to upload MCP server") setCatalog(Array.isArray(data.catalog) ? data.catalog : catalog) setServers(Array.isArray(data.servers) ? data.servers : []) setConfig(data.config || { mcpServers: {} }) if (data.preflight && data.server?.id) { setPreflightResults((current) => ({ ...current, [data.server!.id]: data.preflight as McpPreflightResult })) } setUploadFiles([]) setUploadPaths([]) setUploadArchive(null) const installKind = data.dependencyInstall?.kind || "generic" const installLogCount = data.dependencyInstall?.logs?.filter(Boolean).length || 0 const preflightNote = data.preflight ? `\nPreflight ${data.preflight.ok ? "passed" : "failed; server saved disabled"}.\n${summarizePreflight(data.preflight)}` : "" setMessage(`${customName} uploaded. ${installKind === "generic" ? "No dependency bootstrap was needed." : `${installKind} dependencies bootstrapped${installLogCount > 0 ? ` with ${installLogCount} install step${installLogCount === 1 ? "" : "s"}` : ""}.`}${preflightNote}`) } catch (error) { setMessage(error instanceof Error ? error.message : "Failed to upload MCP server") } finally { setSaving(false) } } function startEditingServer(server: McpServerInstall) { setEditingServerId(server.id) setEditorText(editableServerJson(server)) } async function saveEditedServer() { try { const payload = serverPayloadFromJson(editorText, editingServerId || "edited-server") await postUpdate(payload, `${String(payload.name || payload.id)} updated.`) setEditingServerId(null) setEditorText("") } catch (error) { setMessage(error instanceof Error ? error.message : "Failed to save MCP server JSON") } } async function searchRegistry() { const query = registrySearch.trim() try { setRegistryLoading(true) setRegistryResults([]) setRegistryPage(1) setLastRegistrySearch(query) const params = new URLSearchParams({ search: query, limit: "24" }) const response = await fetch(`/api/mcp/registry?${params}`, { cache: "no-store" }) const data = await response.json() if (!response.ok) throw new Error(data.error || "Failed to search MCP registry") const results = Array.isArray(data.results) ? data.results : [] setRegistryResults(results) setMessage(results.length > 0 ? `Found ${results.length} registry server${results.length === 1 ? "" : "s"}.` : "No registry servers matched that search.") } catch (error) { setRegistryResults([]) setMessage(error instanceof Error ? error.message : "Failed to search MCP registry") } finally { setRegistryLoading(false) } } useEffect(() => { load() }, []) return (

Model Context Protocol

MCP CONFIGURATION

Install MCP server definitions for local tools, files, and remote context providers.

Installed

{servers.length} servers

Enabled

{enabledCount} active

Catalog

{catalog.length} presets

{message && (
{message}
)} {loading ? (
Loading MCP servers...
) : (

MCP Security

Control which installed MCP servers are available to sandboxes.

{servers.length === 0 ? (
Install an MCP server before configuring sandbox access.
) : servers.map((server) => (

{server.name}

{server.enabled ? "enabled" : "disabled"}

{server.command} {server.args.join(" ")}

Availability
Allowed Sandboxes {sandboxes.length === 0 ? (
No sandboxes detected.
) : (
{sandboxes.map((sandbox) => ( ))}
)}
))}

Registry Search

Search the Official MCP Registry and install compatible stdio or remote HTTP servers.

Open Registry
setRegistrySearch(event.target.value)} onKeyDown={(event) => { if (event.key === "Enter") searchRegistry() }} placeholder="Search GitHub, Slack, filesystem, Postgres..." className="field-control min-w-0 flex-1 px-3 py-2 text-sm" />
{registryResults.length > 0 && ( <>

Showing {((registryPage - 1) * REGISTRY_PAGE_SIZE) + 1}-{Math.min(registryPage * REGISTRY_PAGE_SIZE, registryResults.length)} of {registryResults.length} {lastRegistrySearch ? ` for "${lastRegistrySearch}"` : ""}

{registryPage} / {registryPageCount}
{pagedRegistryResults.map((entry, index) => { const installed = installedIds.has(entry.id) return (

{entry.name}

{entry.summary}

{entry.transport}
{entry.command} {entry.args.join(" ")}

{entry.tags.join(" / ")}

) })}
)}
{catalogOpen && (
{catalog.map((entry) => { const installed = installedIds.has(entry.id) return (

{entry.name}

{entry.summary}

{entry.websiteUrl && ( Setup Guide )}
{entry.transport}
{entry.command} {entry.args.join(" ")}

{entry.tags.join(" / ")}

) })}
)}
{customOpen && (
Name setCustomName(event.target.value)} className="field-control w-full px-3 py-2 text-sm font-mono" />
Transport
Summary setCustomSummary(event.target.value)} className="field-control w-full px-3 py-2 text-sm" />
{customTransport === "http" ? "URL" : "Command"} setCustomCommand(event.target.value)} placeholder={customTransport === "http" ? "https://mcp.example.com/mcp" : "npx, uvx, node, python"} className="field-control w-full px-3 py-2 text-sm font-mono" />
Args