"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 McpRegistry = { id: string name: string baseUrl: string description: string addedAt: 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 McpPreflightRepairResult = { attempted: boolean ok: boolean provider: "openai-compatible" model: string baseUrl: string summary: string changes: Array<{ type: "file" | "launch" path?: string summary: string }> error?: string } type McpInstallSuggestion = { name?: string summary?: string transport?: McpTransport command?: string args?: string[] env?: Record uploadRuntime?: string uploadEntryMode?: "file" | "python-module" | "console-script" | "" uploadEntrypoint?: string notes?: string } type McpSandbox = { id: string name: string status: string } type McpConfigurationPanelProps = { sandboxes?: McpSandbox[] } const REGISTRY_PAGE_SIZE = 4 const WIZARD_STEPS = ["basics", "launch", "upload", "review"] as const type WizardStep = typeof WIZARD_STEPS[number] function FieldLabel({ children }: { children: React.ReactNode }) { return } function FieldHint({ 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)), ) } function envToText(value: Record) { return Object.entries(value) .map(([key, item]) => `${key}=${item}`) .join("\n") } 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 [uploadRepair, setUploadRepair] = useState(true) const [repairSandboxId, setRepairSandboxId] = useState("") const [installPrompt, setInstallPrompt] = useState("") const [installAssistNotes, setInstallAssistNotes] = useState("") 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 [registries, setRegistries] = useState([]) const [selectedRegistryId, setSelectedRegistryId] = useState("") const [registryName, setRegistryName] = useState("") const [registryUrl, setRegistryUrl] = useState("") const [registryDescription, setRegistryDescription] = useState("") const [registryPrompt, setRegistryPrompt] = useState("") const [preflightResults, setPreflightResults] = useState>({}) const [securityOpen, setSecurityOpen] = useState(true) const [openSecurityServers, setOpenSecurityServers] = useState>({}) const [repoOpen, setRepoOpen] = useState(true) const [catalogOpen, setCatalogOpen] = useState(false) const [customOpen, setCustomOpen] = useState(false) const [wizardStep, setWizardStep] = useState("basics") 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 selectedRegistry = registries.find((registry) => registry.id === selectedRegistryId) || registries[0] || null const pagedRegistryResults = registryResults.slice( (registryPage - 1) * REGISTRY_PAGE_SIZE, registryPage * REGISTRY_PAGE_SIZE, ) const wizardStepIndex = WIZARD_STEPS.indexOf(wizardStep) const hasUploadBundle = Boolean(uploadArchive || uploadFiles.length > 0) async function load() { try { setLoading(true) const [response, registryResponse] = await Promise.all([ fetch("/api/mcp", { cache: "no-store" }), fetch("/api/mcp/registries", { cache: "no-store" }), ]) const data = await response.json() as McpResponse const registryData = await registryResponse.json() as { registries?: McpRegistry[]; error?: string } if (!response.ok) throw new Error(data.error || "Failed to load MCP configuration") if (!registryResponse.ok) throw new Error(registryData.error || "Failed to load MCP registries") setCatalog(Array.isArray(data.catalog) ? data.catalog : []) setServers(Array.isArray(data.servers) ? data.servers : []) setConfig(data.config || { mcpServers: {} }) const nextRegistries = Array.isArray(registryData.registries) ? registryData.registries : [] setRegistries(nextRegistries) setSelectedRegistryId((current) => current && nextRegistries.some((registry) => registry.id === current) ? current : nextRegistries[0]?.id || "") setMessage("") } catch (error) { setMessage(error instanceof Error ? error.message : "Failed to load MCP configuration") } finally { setLoading(false) } } async function saveRegistry() { try { setSaving(true) const response = await fetch("/api/mcp/registries", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: registryName, baseUrl: registryUrl, description: registryDescription }), }) const data = await response.json() as { registry?: McpRegistry; registries?: McpRegistry[]; error?: string } if (!response.ok || !data.registry) throw new Error(data.error || "Failed to save MCP registry") const nextRegistries = Array.isArray(data.registries) ? data.registries : [] setRegistries(nextRegistries) setSelectedRegistryId(data.registry.id) setRegistryName("") setRegistryUrl("") setRegistryDescription("") setRegistryPrompt("") setMessage(`${data.registry.name} registry added.`) } catch (error) { setMessage(error instanceof Error ? error.message : "Failed to save MCP registry") } finally { setSaving(false) } } async function deleteRegistry(registry: McpRegistry) { try { setSaving(true) const response = await fetch("/api/mcp/registries", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "delete", registryId: registry.id }), }) const data = await response.json() as { registries?: McpRegistry[]; error?: string } if (!response.ok) throw new Error(data.error || "Failed to delete MCP registry") const nextRegistries = Array.isArray(data.registries) ? data.registries : [] setRegistries(nextRegistries) setSelectedRegistryId((current) => current === registry.id ? nextRegistries[0]?.id || "" : current) setRegistryResults([]) setMessage(`${registry.name} registry deleted.`) } catch (error) { setMessage(error instanceof Error ? error.message : "Failed to delete MCP registry") } finally { setSaving(false) } } async function assistRegistry() { try { setSaving(true) const response = await fetch("/api/mcp/registries/assist", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt: registryPrompt || `${registryName} ${registryUrl}`.trim() }), }) const data = await response.json() as { suggestion?: Partial; error?: string } if (!response.ok || !data.suggestion) throw new Error(data.error || "Failed to generate registry suggestion") setRegistryName(data.suggestion.name || registryName) setRegistryUrl(data.suggestion.baseUrl || registryUrl) setRegistryDescription(data.suggestion.description || registryDescription) setMessage("Registry fields drafted from the running LLM endpoint.") } catch (error) { setMessage(error instanceof Error ? error.message : "Failed to generate registry suggestion") } finally { setSaving(false) } } function applyInstallSuggestion(suggestion: McpInstallSuggestion) { if (suggestion.name) setCustomName(suggestion.name) if (suggestion.summary) setCustomSummary(suggestion.summary) if (suggestion.transport) setCustomTransport(suggestion.transport) if (suggestion.command) setCustomCommand(suggestion.command) if (Array.isArray(suggestion.args)) setCustomArgs(suggestion.args.join("\n")) if (suggestion.env) setCustomEnv(envToText(suggestion.env)) if (suggestion.uploadRuntime) setUploadRuntime(suggestion.uploadRuntime) if (suggestion.uploadEntryMode) setUploadEntryMode(suggestion.uploadEntryMode) if (suggestion.uploadEntrypoint) setUploadEntrypoint(suggestion.uploadEntrypoint) if (suggestion.notes) setInstallAssistNotes(suggestion.notes) } async function assistInstall() { try { setSaving(true) const response = await fetch("/api/mcp/install-assist", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt: installPrompt, current: { name: customName, summary: customSummary, transport: customTransport, command: customCommand, args: parseLines(customArgs), env: parseEnv(customEnv), uploadRuntime, uploadEntryMode, uploadEntrypoint, }, }), }) const data = await response.json() as { suggestion?: McpInstallSuggestion; error?: string } if (!response.ok || !data.suggestion) throw new Error(data.error || "Failed to draft MCP install") applyInstallSuggestion(data.suggestion) setWizardStep("launch") setMessage("Install wizard fields drafted from the running LLM endpoint.") } catch (error) { setMessage(error instanceof Error ? error.message : "Failed to draft MCP install") } finally { setSaving(false) } } function nextWizardStep() { setWizardStep(WIZARD_STEPS[Math.min(WIZARD_STEPS.length - 1, wizardStepIndex + 1)]) } function previousWizardStep() { setWizardStep(WIZARD_STEPS[Math.max(0, wizardStepIndex - 1)]) } 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}` } function summarizeRepair(repair?: McpPreflightRepairResult | null) { if (!repair?.attempted) return "" const changeSummary = repair.changes.length > 0 ? `\nChanged: ${repair.changes.map((change) => change.path ? `${change.path}: ${change.summary}` : change.summary).join(" ")}` : "" const route = repair.model ? `\nRepair model: ${repair.model}` : "" const error = repair.error ? `\nRepair error: ${repair.error}` : "" return `\nLLM repair ${repair.ok ? "applied" : "did not apply changes"}: ${repair.summary}${changeSummary}${route}${error}` } 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) form.set("repair", uploadRepair ? "true" : "false") if (repairSandboxId) form.set("sandboxId", repairSandboxId) 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; repair?: McpPreflightRepairResult; 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"}` : ""}.`}${summarizeRepair(data.repair)}${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() if (!selectedRegistry) { setMessage("Add an MCP Registry before searching.") return } try { setRegistryLoading(true) setRegistryResults([]) setRegistryPage(1) setLastRegistrySearch(query) const params = new URLSearchParams({ search: query, limit: "24", baseUrl: selectedRegistry.baseUrl }) 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} server${results.length === 1 ? "" : "s"} in ${selectedRegistry.name}.` : `${selectedRegistry.name} had no matches for 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...
) : (
{securityOpen && (
{servers.length === 0 ? (
Install an MCP server before configuring sandbox access.
) : servers.map((server) => { const expanded = openSecurityServers[server.id] !== false return (
{expanded && (
Availability
Allowed Sandboxes {sandboxes.length === 0 ? (
No sandboxes detected.
) : (
{sandboxes.map((sandbox) => ( ))}
)}
)}
) })}
)}
{repoOpen && (
Available Registries {selectedRegistry && ( Open )}
{registries.length === 0 ? (
Add an MCP Registry
) : (
{registries.map((registry) => { const selected = registry.id === selectedRegistryId return ( ) })}
)} {selectedRegistry && ( )}
Registry NameName shown in the registry selector.
setRegistryName(event.target.value)} placeholder="Company MCP Repo" className="field-control w-full px-3 py-2 text-sm" />
Registry URLRoot URL for a registry that exposes /v0/servers.
setRegistryUrl(event.target.value)} placeholder="https://registry.example.com" className="field-control w-full px-3 py-2 text-sm font-mono" />
LLM Registry AssistDescribe a registry and the running LLM endpoint drafts the fields.