Add MCP registry wizard preflight flow

This commit is contained in:
Codex
2026-04-29 15:32:28 +00:00
parent 42561a7eff
commit ce4303a602
8 changed files with 955 additions and 223 deletions
+67
View File
@@ -0,0 +1,67 @@
import { NextResponse } from "next/server"
const REQUEST_TIMEOUT_MS = Number.parseInt(process.env.MCP_REGISTRY_ASSIST_TIMEOUT_MS || "45000", 10)
const MODEL = process.env.MCP_PREFLIGHT_LLM_MODEL || process.env.OPENAI_MODEL || "gpt-4o-mini"
const BASE_URL = (process.env.MCP_PREFLIGHT_LLM_BASE_URL || process.env.OPENAI_BASE_URL || process.env.VLLM_BASE_URL || "http://localhost:8000/v1").replace(/\/+$/, "")
function extractJsonObject(value: string) {
const trimmed = value.trim()
if (trimmed.startsWith("{")) return trimmed
const match = trimmed.match(/\{[\s\S]*\}/)
if (!match) throw new Error("registry assistant did not return JSON")
return match[0]
}
export async function POST(request: Request) {
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)
try {
const body = await request.json().catch(() => ({}))
const prompt = typeof body?.prompt === "string" ? body.prompt.trim() : ""
if (!prompt) throw new Error("registry prompt is required")
const response = await fetch(`${BASE_URL}/chat/completions`, {
method: "POST",
signal: controller.signal,
headers: {
"Content-Type": "application/json",
...(process.env.MCP_PREFLIGHT_LLM_API_KEY || process.env.OPENAI_API_KEY
? { Authorization: `Bearer ${process.env.MCP_PREFLIGHT_LLM_API_KEY || process.env.OPENAI_API_KEY}` }
: {}),
},
body: JSON.stringify({
model: MODEL,
temperature: 0.1,
response_format: { type: "json_object" },
messages: [
{
role: "system",
content: "Convert a user's MCP registry description into JSON with name, baseUrl, and description. The baseUrl must be the registry origin/root, not the /v0/servers path. Return only JSON.",
},
{
role: "user",
content: prompt,
},
],
}),
})
const data = await response.json().catch(() => null)
if (!response.ok) throw new Error(data?.error?.message || data?.error || `registry assistant failed (${response.status})`)
const content = data?.choices?.[0]?.message?.content
if (typeof content !== "string" || !content.trim()) throw new Error("registry assistant returned an empty response")
const suggestion = JSON.parse(extractJsonObject(content))
return NextResponse.json({
suggestion: {
name: typeof suggestion?.name === "string" ? suggestion.name : "",
baseUrl: typeof suggestion?.baseUrl === "string" ? suggestion.baseUrl : "",
description: typeof suggestion?.description === "string" ? suggestion.description : "",
},
model: MODEL,
})
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to assist registry setup"
return NextResponse.json({ error: message }, { status: /required/.test(message) ? 400 : 502 })
} finally {
clearTimeout(timeout)
}
}
+34
View File
@@ -0,0 +1,34 @@
import { NextResponse } from "next/server"
import { deleteMcpRegistry, listMcpRegistries, saveMcpRegistry } from "@/app/lib/mcpRegistryStore"
export async function GET() {
try {
return NextResponse.json({ registries: await listMcpRegistries() })
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to load MCP registries"
return NextResponse.json({ error: message }, { status: 500 })
}
}
export async function POST(request: Request) {
try {
const body = await request.json().catch(() => ({}))
const action = typeof body?.action === "string" ? body.action : "save"
if (action === "delete") {
const registryId = typeof body?.registryId === "string" ? body.registryId : ""
return NextResponse.json({ deleted: await deleteMcpRegistry(registryId), registries: await listMcpRegistries() })
}
const registry = await saveMcpRegistry({
id: body?.id,
name: body?.name,
baseUrl: body?.baseUrl,
description: body?.description,
})
return NextResponse.json({ registry, registries: await listMcpRegistries() })
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to update MCP registries"
return NextResponse.json({ error: message }, { status: /required|URL|delete/.test(message) ? 400 : 500 })
}
}
+3 -2
View File
@@ -1,7 +1,7 @@
import { NextResponse } from "next/server"
import type { McpCatalogEntry } from "@/app/lib/mcpServerStore"
const REGISTRY_BASE_URL = process.env.MCP_REGISTRY_BASE_URL || "https://registry.modelcontextprotocol.io"
const DEFAULT_REGISTRY_BASE_URL = process.env.MCP_REGISTRY_BASE_URL || "https://registry.modelcontextprotocol.io"
type RegistryArgument = {
value?: string
@@ -126,7 +126,8 @@ export async function GET(request: Request) {
const requestUrl = new URL(request.url)
const search = requestUrl.searchParams.get("search") || requestUrl.searchParams.get("q") || ""
const limit = Math.max(1, Math.min(Number.parseInt(requestUrl.searchParams.get("limit") || "12", 10) || 12, 30))
const registryUrl = new URL("/v0/servers", REGISTRY_BASE_URL)
const baseUrl = requestUrl.searchParams.get("baseUrl") || DEFAULT_REGISTRY_BASE_URL
const registryUrl = new URL("/v0/servers", baseUrl)
registryUrl.searchParams.set("limit", String(limit))
registryUrl.searchParams.set("is_latest", "true")
if (search.trim()) registryUrl.searchParams.set("search", search.trim())
+46 -4
View File
@@ -5,7 +5,8 @@ import os from "node:os"
import path from "node:path"
import { promisify } from "node:util"
import { preflightMcpServer } from "@/app/lib/mcpPreflight"
import { installMcpServer, listMcpServers } from "@/app/lib/mcpServerStore"
import { repairUploadedMcpServerWithLlm, type McpPreflightRepairResult } from "@/app/lib/mcpPreflightRepair"
import { installMcpServer, listMcpServers, type McpServerInstall } from "@/app/lib/mcpServerStore"
const execFileAsync = promisify(execFile)
const HOME = process.env.HOME || "/tmp"
@@ -295,6 +296,8 @@ export async function POST(request: Request) {
const runtime = String(form.get("runtime") || "python3").trim()
const entrypoint = String(form.get("entrypoint") || "server.py").trim()
const entryMode = normalizeEntryMode(form.get("entryMode"))
const sandboxId = String(form.get("sandboxId") || "").trim()
const repairEnabled = String(form.get("repair") || "true") !== "false"
const root = path.join(UPLOAD_DIR, id)
if (!runtime) throw new Error("runtime command is required")
@@ -311,7 +314,7 @@ export async function POST(request: Request) {
const projectRoot = await resolveProjectRoot(root, entrypointPath)
const bootstrap = await bootstrapUploadedServer(projectRoot, runtime, entrypoint)
const launch = await launchCommandForUpload(projectRoot, bootstrap, entryMode, entrypoint, entrypointPath, parseLines(form.get("args")))
const candidate = {
let candidate = {
id,
name,
summary,
@@ -322,7 +325,7 @@ export async function POST(request: Request) {
tags: ["uploaded", "custom"],
source: "custom",
enabled: true,
} as const satisfies {
} satisfies {
id: string
name: string
summary: string
@@ -334,13 +337,51 @@ export async function POST(request: Request) {
source: "custom"
enabled: boolean
}
const preflight = await preflightMcpServer({
const installCandidate = (): McpServerInstall => ({
...candidate,
installedAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
accessMode: "disabled",
allowedSandboxIds: [],
})
let preflight = await preflightMcpServer(installCandidate())
let repair: McpPreflightRepairResult | null = null
if (!preflight.ok && repairEnabled) {
try {
repair = await repairUploadedMcpServerWithLlm({
uploadRoot: root,
projectRoot,
server: installCandidate(),
preflight,
dependencyLogs: bootstrap.logs,
sandboxId: sandboxId || null,
})
if (repair.updatedServer) {
candidate = {
...candidate,
command: repair.updatedServer.command,
args: repair.updatedServer.args,
env: repair.updatedServer.env,
}
}
if (repair.ok) {
preflight = await preflightMcpServer(installCandidate())
}
} catch (error) {
repair = {
attempted: true,
ok: false,
provider: "openai-compatible",
model: process.env.MCP_PREFLIGHT_LLM_MODEL || process.env.OPENAI_MODEL || "",
baseUrl: process.env.MCP_PREFLIGHT_LLM_BASE_URL || process.env.OPENAI_BASE_URL || process.env.VLLM_BASE_URL || "",
summary: "LLM-assisted repair could not complete.",
changes: [],
error: error instanceof Error ? error.message : "MCP repair failed",
}
}
}
const server = await installMcpServer({
...candidate,
enabled: preflight.ok,
@@ -357,6 +398,7 @@ export async function POST(request: Request) {
logs: bootstrap.logs,
},
preflight,
repair,
...(await listMcpServers()),
})
} catch (error) {
+418 -214
View File
@@ -32,6 +32,14 @@ type McpResponse = {
error?: string
}
type McpRegistry = {
id: string
name: string
baseUrl: string
description: string
addedAt: string
}
type McpPreflightResult = {
ok: boolean
checkedAt: string
@@ -47,6 +55,21 @@ type McpPreflightResult = {
}
}
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 McpSandbox = {
id: string
name: string
@@ -63,6 +86,17 @@ function FieldLabel({ children }: { children: React.ReactNode }) {
return <label className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">{children}</label>
}
function FieldHint({ children }: { children: React.ReactNode }) {
return (
<span
title={typeof children === "string" ? children : undefined}
className="inline-flex h-4 w-4 items-center justify-center rounded-full border border-[var(--border-subtle)] text-[10px] text-[var(--foreground-dim)]"
>
?
</span>
)
}
function parseLines(value: string) {
return value
.split(/\r?\n/)
@@ -100,6 +134,8 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
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 [editingServerId, setEditingServerId] = useState<string | null>(null)
const [editorText, setEditorText] = useState("")
const [registrySearch, setRegistrySearch] = useState("github")
@@ -107,14 +143,25 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
const [registryLoading, setRegistryLoading] = useState(false)
const [registryPage, setRegistryPage] = useState(1)
const [lastRegistrySearch, setLastRegistrySearch] = useState("")
const [registries, setRegistries] = useState<McpRegistry[]>([])
const [selectedRegistryId, setSelectedRegistryId] = useState("")
const [registryName, setRegistryName] = useState("")
const [registryUrl, setRegistryUrl] = useState("")
const [registryDescription, setRegistryDescription] = useState("")
const [registryPrompt, setRegistryPrompt] = useState("")
const [preflightResults, setPreflightResults] = useState<Record<string, McpPreflightResult>>({})
const [securityOpen, setSecurityOpen] = useState(true)
const [openSecurityServers, setOpenSecurityServers] = useState<Record<string, boolean>>({})
const [repoOpen, setRepoOpen] = useState(true)
const [catalogOpen, setCatalogOpen] = useState(false)
const [customOpen, setCustomOpen] = useState(false)
const [wizardStep, setWizardStep] = useState<"basics" | "launch" | "upload" | "review">("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,
@@ -123,12 +170,20 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
async function load() {
try {
setLoading(true)
const response = await fetch("/api/mcp", { cache: "no-store" })
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")
@@ -137,6 +192,74 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
}
}
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<McpRegistry>; 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)
}
}
async function postUpdate(body: Record<string, unknown>, success: string) {
try {
setSaving(true)
@@ -322,6 +445,16 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
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)
@@ -357,6 +490,8 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
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 {
@@ -366,7 +501,7 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
})
}
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 }
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 : [])
@@ -382,7 +517,7 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
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}`)
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 {
@@ -408,18 +543,22 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
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" })
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} registry server${results.length === 1 ? "" : "s"}.` : "No registry servers matched that search.")
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")
@@ -475,224 +614,251 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
<div className="grid grid-cols-1 gap-6 xl:grid-cols-[minmax(0,1fr)_400px]">
<section className="space-y-6">
<div className="panel p-6">
<div className="border-b border-[var(--border-subtle)] pb-4">
<h2 className="text-sm font-semibold uppercase tracking-wider text-[var(--foreground)]">MCP Security</h2>
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Control which installed MCP servers are available to sandboxes.</p>
</div>
<div className="mt-5 space-y-4">
{servers.length === 0 ? (
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 text-xs text-[var(--foreground-dim)]">
Install an MCP server before configuring sandbox access.
</div>
) : servers.map((server) => (
<div key={server.id} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4">
<div className="flex items-start justify-between gap-4 max-lg:flex-col">
<div className="min-w-0">
<div className="flex items-center gap-2">
<h3 className="truncate text-sm font-mono font-semibold text-[var(--foreground)]">{server.name}</h3>
<span className={`status-chip px-2 py-1 ${server.enabled ? "bg-[var(--status-running-bg)] text-[var(--status-running)]" : "bg-[var(--status-pending-bg)] text-[var(--status-pending)]"}`}>
{server.enabled ? "enabled" : "disabled"}
</span>
</div>
<p className="mt-2 break-all font-mono text-[11px] text-[var(--foreground-dim)]">{server.command} {server.args.join(" ")}</p>
</div>
<div className="flex shrink-0 gap-2 max-sm:w-full max-sm:[&>button]:flex-1">
<button
onClick={() => setServerEnabled(server, true)}
disabled={saving || server.enabled}
className="action-button px-3 py-2"
>
Enable
</button>
<button
onClick={() => setServerEnabled(server, false)}
disabled={saving || !server.enabled}
className="action-button px-3 py-2"
>
Disable
</button>
</div>
<button
type="button"
onClick={() => setSecurityOpen((open) => !open)}
className="flex w-full items-center justify-between gap-4 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--nvidia-green)]"
aria-expanded={securityOpen}
>
<div>
<h2 className="text-sm font-semibold uppercase tracking-wider text-[var(--foreground)]">MCP Security</h2>
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Control which installed MCP servers are available to sandboxes.</p>
</div>
<span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] text-sm text-[var(--foreground)]">
{securityOpen ? "-" : "+"}
</span>
</button>
{securityOpen && (
<div className="mt-5 space-y-3 border-t border-[var(--border-subtle)] pt-5">
{servers.length === 0 ? (
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 text-xs text-[var(--foreground-dim)]">
Install an MCP server before configuring sandbox access.
</div>
<div className="mt-4 grid grid-cols-1 gap-3 lg:grid-cols-[240px_minmax(0,1fr)]">
<div className="space-y-2">
<FieldLabel>Availability</FieldLabel>
<select
value={server.accessMode}
onChange={(event) => syncAccessModeChange(server, event.target.value)}
disabled={saving}
className="field-control w-full px-3 py-2 text-xs font-mono uppercase tracking-wider"
) : servers.map((server) => {
const expanded = openSecurityServers[server.id] !== false
return (
<div key={server.id} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)]">
<button
type="button"
onClick={() => setOpenSecurityServers((current) => ({ ...current, [server.id]: !expanded }))}
className="flex w-full items-start justify-between gap-4 p-4 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--nvidia-green)]"
aria-expanded={expanded}
>
<option value="disabled">Disabled</option>
<option value="allow_all">Allow All</option>
<option value="allow_only">Allow Only</option>
</select>
</div>
<div className={server.accessMode === "allow_only" ? "space-y-2" : "opacity-50"}>
<FieldLabel>Allowed Sandboxes</FieldLabel>
{sandboxes.length === 0 ? (
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-3 text-xs text-[var(--foreground-dim)]">
No sandboxes detected.
</div>
) : (
<div className="grid grid-cols-1 gap-2 md:grid-cols-2">
{sandboxes.map((sandbox) => (
<label key={sandbox.id} className="flex items-center justify-between gap-3 rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-3 text-xs">
<span className="min-w-0">
<span className="block truncate font-mono text-[var(--foreground)]">{sandbox.name}</span>
<span className="mt-1 block truncate text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">{sandbox.status}</span>
</span>
<input
type="checkbox"
checked={sandboxAllowed(server, sandbox)}
disabled={saving || server.accessMode !== "allow_only"}
onChange={(event) => toggleServerSandbox(server, sandbox, event.target.checked)}
className="h-4 w-4 accent-[var(--nvidia-green)]"
/>
</label>
))}
<span className="min-w-0">
<span className="flex items-center gap-2">
<span className="truncate text-sm font-mono font-semibold text-[var(--foreground)]">{server.name}</span>
<span className={`status-chip px-2 py-1 ${server.enabled ? "bg-[var(--status-running-bg)] text-[var(--status-running)]" : "bg-[var(--status-pending-bg)] text-[var(--status-pending)]"}`}>
{server.enabled ? "enabled" : "disabled"}
</span>
</span>
<span className="mt-2 block break-all font-mono text-[11px] text-[var(--foreground-dim)]">{server.command} {server.args.join(" ")}</span>
</span>
<span className="text-sm text-[var(--foreground)]">{expanded ? "-" : "+"}</span>
</button>
{expanded && (
<div className="border-t border-[var(--border-subtle)] p-4">
<div className="flex gap-2 max-sm:[&>button]:flex-1">
<button onClick={() => setServerEnabled(server, true)} disabled={saving || server.enabled} className="action-button px-3 py-2">Enable</button>
<button onClick={() => setServerEnabled(server, false)} disabled={saving || !server.enabled} className="action-button px-3 py-2">Disable</button>
</div>
<div className="mt-4 grid grid-cols-1 gap-3 lg:grid-cols-[240px_minmax(0,1fr)]">
<div className="space-y-2">
<FieldLabel>Availability</FieldLabel>
<select value={server.accessMode} onChange={(event) => syncAccessModeChange(server, event.target.value)} disabled={saving} className="field-control w-full px-3 py-2 text-xs font-mono uppercase tracking-wider">
<option value="disabled">Disabled</option>
<option value="allow_all">Allow All</option>
<option value="allow_only">Allow Only</option>
</select>
</div>
<div className={server.accessMode === "allow_only" ? "space-y-2" : "opacity-50"}>
<FieldLabel>Allowed Sandboxes</FieldLabel>
{sandboxes.length === 0 ? (
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-3 text-xs text-[var(--foreground-dim)]">No sandboxes detected.</div>
) : (
<div className="grid grid-cols-1 gap-2 md:grid-cols-2">
{sandboxes.map((sandbox) => (
<label key={sandbox.id} className="flex items-center justify-between gap-3 rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-3 text-xs">
<span className="min-w-0">
<span className="block truncate font-mono text-[var(--foreground)]">{sandbox.name}</span>
<span className="mt-1 block truncate text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">{sandbox.status}</span>
</span>
<input type="checkbox" checked={sandboxAllowed(server, sandbox)} disabled={saving || server.accessMode !== "allow_only"} onChange={(event) => toggleServerSandbox(server, sandbox, event.target.checked)} className="h-4 w-4 accent-[var(--nvidia-green)]" />
</label>
))}
</div>
)}
</div>
</div>
</div>
)}
</div>
</div>
</div>
))}
</div>
</div>
<div className="panel p-6">
<div className="flex items-start justify-between gap-4 border-b border-[var(--border-subtle)] pb-4 max-md:flex-col">
<div>
<h2 className="text-sm font-semibold uppercase tracking-wider text-[var(--foreground)]">Registry Search</h2>
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Search the Official MCP Registry and install compatible stdio or remote HTTP servers.</p>
)
})}
</div>
<a href="https://registry.modelcontextprotocol.io/" target="_blank" rel="noreferrer" className="action-button px-3 py-2">
Open Registry
</a>
</div>
<div className="mt-5 flex gap-3 max-sm:flex-col">
<input
value={registrySearch}
onChange={(event) => 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"
/>
<button onClick={searchRegistry} disabled={registryLoading || saving} className="rounded-sm bg-[var(--nvidia-green)] px-4 py-2 text-xs font-mono uppercase tracking-wider text-black disabled:opacity-50">
{registryLoading ? "Searching..." : "Search"}
</button>
</div>
{registryResults.length > 0 && (
<>
<div className="mt-5 flex items-center justify-between gap-3 border-t border-[var(--border-subtle)] pt-4 max-sm:flex-col max-sm:items-start">
<p className="text-xs text-[var(--foreground-dim)]">
Showing {((registryPage - 1) * REGISTRY_PAGE_SIZE) + 1}-{Math.min(registryPage * REGISTRY_PAGE_SIZE, registryResults.length)} of {registryResults.length}
{lastRegistrySearch ? ` for "${lastRegistrySearch}"` : ""}
</p>
<div className="flex items-center gap-2">
<button
onClick={() => setRegistryPage((page) => Math.max(1, page - 1))}
disabled={registryPage === 1}
className="action-button px-3 py-2"
>
Prev
</button>
<span className="min-w-16 text-center text-xs font-mono text-[var(--foreground-dim)]">
{registryPage} / {registryPageCount}
</span>
<button
onClick={() => setRegistryPage((page) => Math.min(registryPageCount, page + 1))}
disabled={registryPage === registryPageCount}
className="action-button px-3 py-2"
>
Next
</button>
</div>
</div>
<div className="mt-4 grid grid-cols-1 gap-3 md:grid-cols-2">
{pagedRegistryResults.map((entry, index) => {
const installed = installedIds.has(entry.id)
return (
<div key={`${entry.id}-${entry.command}-${entry.args.join("|")}-${index}`} className="metric flex min-h-44 flex-col p-4">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<h3 className="truncate text-sm font-semibold text-[var(--foreground)]">{entry.name}</h3>
<p className="mt-2 text-xs leading-5 text-[var(--foreground-dim)]">{entry.summary}</p>
</div>
<span className="status-chip bg-[var(--status-pending-bg)] px-2 py-1 text-[var(--status-pending)]">{entry.transport}</span>
</div>
<div className="mt-3 min-w-0 rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-2 font-mono text-[11px] text-[var(--foreground-dim)]">
<span className="text-[var(--foreground)]">{entry.command}</span> {entry.args.join(" ")}
</div>
<div className="mt-auto flex items-center justify-between gap-3 pt-4">
<p className="truncate text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">{entry.tags.join(" / ")}</p>
<button
onClick={() => postUpdate({ action: "install", ...entry, source: "registry" }, installed ? `${entry.name} refreshed from registry.` : `${entry.name} installed from registry.`)}
disabled={saving}
className={installed ? "action-button px-3 py-2" : "rounded-sm bg-[var(--nvidia-green)] px-3 py-2 text-xs font-mono uppercase tracking-wider text-black disabled:opacity-50"}
>
{installed ? "Refresh" : "Install"}
</button>
</div>
</div>
)
})}
</div>
</>
)}
</div>
<div className="panel p-6">
<button
type="button"
onClick={() => setCatalogOpen((open) => !open)}
onClick={() => setRepoOpen((open) => !open)}
className="flex w-full items-center justify-between gap-4 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--nvidia-green)]"
aria-expanded={catalogOpen}
aria-expanded={repoOpen}
>
<div>
<h2 className="text-sm font-semibold uppercase tracking-wider text-[var(--foreground)]">Preconfigured Servers</h2>
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Presets install as MCP command definitions; clients start them when needed.</p>
<h2 className="text-sm font-semibold uppercase tracking-wider text-[var(--foreground)]">MCP Repo Search and Preconfigured Servers</h2>
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Choose a registry, search installable MCP servers, or install a preset.</p>
</div>
<span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] text-sm text-[var(--foreground)]">
{catalogOpen ? "-" : "+"}
{repoOpen ? "-" : "+"}
</span>
</button>
{catalogOpen && (
<div className="mt-5 grid grid-cols-1 gap-3 border-t border-[var(--border-subtle)] pt-5 md:grid-cols-2">
{catalog.map((entry) => {
const installed = installedIds.has(entry.id)
return (
<div key={entry.id} className="metric flex min-h-44 flex-col p-4">
<div className="flex items-start justify-between gap-3">
<div>
<h3 className="text-sm font-semibold uppercase tracking-wider text-[var(--foreground)]">{entry.name}</h3>
<p className="mt-2 text-xs leading-5 text-[var(--foreground-dim)]">{entry.summary}</p>
{entry.websiteUrl && (
<a href={entry.websiteUrl} target="_blank" rel="noreferrer" className="mt-2 inline-block text-[11px] font-mono uppercase tracking-wider text-[var(--nvidia-green)] hover:underline">
Setup Guide
</a>
)}
</div>
<span className="status-chip bg-[var(--status-pending-bg)] px-2 py-1 text-[var(--status-pending)]">{entry.transport}</span>
</div>
<div className="mt-3 min-w-0 rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-2 font-mono text-[11px] text-[var(--foreground-dim)]">
<span className="text-[var(--foreground)]">{entry.command}</span> {entry.args.join(" ")}
</div>
<div className="mt-auto flex items-center justify-between gap-3 pt-4">
<p className="truncate text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">{entry.tags.join(" / ")}</p>
<button
onClick={() => postUpdate({ action: "install", id: entry.id }, installed ? `${entry.name} refreshed.` : `${entry.name} installed.`)}
disabled={saving}
className={installed ? "action-button px-3 py-2" : "rounded-sm bg-[var(--nvidia-green)] px-3 py-2 text-xs font-mono uppercase tracking-wider text-black disabled:opacity-50"}
>
{installed ? "Refresh" : "Install"}
</button>
{repoOpen && (
<div className="mt-5 space-y-5 border-t border-[var(--border-subtle)] pt-5">
<div className="space-y-3">
<div className="flex items-center justify-between gap-3">
<FieldLabel>Available Registries</FieldLabel>
{selectedRegistry && (
<a href={selectedRegistry.baseUrl} target="_blank" rel="noreferrer" className="text-[11px] font-mono uppercase tracking-wider text-[var(--nvidia-green)] hover:underline">Open</a>
)}
</div>
{registries.length === 0 ? (
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 text-xs text-[var(--foreground-dim)]">
Add an MCP Registry
</div>
) : (
<div className="grid grid-cols-1 gap-2 md:grid-cols-2">
{registries.map((registry) => {
const selected = registry.id === selectedRegistryId
return (
<button
key={registry.id}
type="button"
onClick={() => { setSelectedRegistryId(registry.id); setRegistryResults([]) }}
className={`rounded-sm border p-3 text-left ${selected ? "border-[var(--nvidia-green)] bg-[var(--status-running-bg)]" : "border-[var(--border-subtle)] bg-[var(--background)]"}`}
>
<span className="block truncate text-xs font-mono font-semibold text-[var(--foreground)]">{registry.name}</span>
<span className="mt-1 block truncate text-[11px] text-[var(--foreground-dim)]">{registry.baseUrl}</span>
</button>
)
})}
</div>
)}
{selectedRegistry && (
<button onClick={() => deleteRegistry(selectedRegistry)} disabled={saving} className="action-button px-3 py-2">
Delete Selected Registry
</button>
)}
</div>
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4">
<div className="grid grid-cols-1 gap-3 md:grid-cols-2">
<div className="space-y-2">
<div className="flex items-center gap-2"><FieldLabel>Registry Name</FieldLabel><FieldHint>Name shown in the registry selector.</FieldHint></div>
<input value={registryName} onChange={(event) => setRegistryName(event.target.value)} placeholder="Company MCP Repo" className="field-control w-full px-3 py-2 text-sm" />
</div>
<div className="space-y-2">
<div className="flex items-center gap-2"><FieldLabel>Registry URL</FieldLabel><FieldHint>Root URL for a registry that exposes /v0/servers.</FieldHint></div>
<input value={registryUrl} onChange={(event) => setRegistryUrl(event.target.value)} placeholder="https://registry.example.com" className="field-control w-full px-3 py-2 text-sm font-mono" />
</div>
<div className="space-y-2 md:col-span-2">
<div className="flex items-center gap-2"><FieldLabel>LLM Registry Assist</FieldLabel><FieldHint>Describe a registry and the running LLM endpoint drafts the fields.</FieldHint></div>
<textarea value={registryPrompt} onChange={(event) => setRegistryPrompt(event.target.value)} rows={3} placeholder="Add the Acme internal MCP registry at https://mcp.acme.example" className="field-control w-full resize-y px-3 py-2 text-sm" />
</div>
<div className="space-y-2 md:col-span-2">
<div className="flex items-center gap-2"><FieldLabel>Description</FieldLabel><FieldHint>Short operator-facing note for this registry.</FieldHint></div>
<input value={registryDescription} onChange={(event) => setRegistryDescription(event.target.value)} className="field-control w-full px-3 py-2 text-sm" />
</div>
</div>
<div className="mt-3 flex flex-wrap gap-2">
<button onClick={assistRegistry} disabled={saving || (!registryPrompt.trim() && !registryUrl.trim())} className="action-button px-3 py-2">Draft With LLM</button>
<button onClick={saveRegistry} disabled={saving || !registryUrl.trim()} className="rounded-sm bg-[var(--nvidia-green)] px-3 py-2 text-xs font-mono uppercase tracking-wider text-black disabled:opacity-50">Add Registry</button>
</div>
</div>
<div className="flex gap-3 max-sm:flex-col">
<input value={registrySearch} onChange={(event) => 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" />
<button onClick={searchRegistry} disabled={registryLoading || saving || !selectedRegistry} className="rounded-sm bg-[var(--nvidia-green)] px-4 py-2 text-xs font-mono uppercase tracking-wider text-black disabled:opacity-50">
{registryLoading ? "Searching..." : "Search"}
</button>
</div>
{registryResults.length > 0 && (
<>
<div className="flex items-center justify-between gap-3 border-t border-[var(--border-subtle)] pt-4 max-sm:flex-col max-sm:items-start">
<p className="text-xs text-[var(--foreground-dim)]">
Showing {((registryPage - 1) * REGISTRY_PAGE_SIZE) + 1}-{Math.min(registryPage * REGISTRY_PAGE_SIZE, registryResults.length)} of {registryResults.length}
{lastRegistrySearch ? ` for "${lastRegistrySearch}"` : ""}{selectedRegistry ? ` in ${selectedRegistry.name}` : ""}
</p>
<div className="flex items-center gap-2">
<button onClick={() => setRegistryPage((page) => Math.max(1, page - 1))} disabled={registryPage === 1} className="action-button px-3 py-2">Prev</button>
<span className="min-w-16 text-center text-xs font-mono text-[var(--foreground-dim)]">{registryPage} / {registryPageCount}</span>
<button onClick={() => setRegistryPage((page) => Math.min(registryPageCount, page + 1))} disabled={registryPage === registryPageCount} className="action-button px-3 py-2">Next</button>
</div>
</div>
)
})}
<div className="grid grid-cols-1 gap-3 md:grid-cols-2">
{pagedRegistryResults.map((entry, index) => {
const installed = installedIds.has(entry.id)
return (
<div key={`${entry.id}-${entry.command}-${entry.args.join("|")}-${index}`} className="metric flex min-h-44 flex-col p-4">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<h3 className="truncate text-sm font-semibold text-[var(--foreground)]">{entry.name}</h3>
<p className="mt-2 text-xs leading-5 text-[var(--foreground-dim)]">{entry.summary}</p>
</div>
<span className="status-chip bg-[var(--status-pending-bg)] px-2 py-1 text-[var(--status-pending)]">{entry.transport}</span>
</div>
<div className="mt-3 min-w-0 rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-2 font-mono text-[11px] text-[var(--foreground-dim)]">
<span className="text-[var(--foreground)]">{entry.command}</span> {entry.args.join(" ")}
</div>
<div className="mt-auto flex items-center justify-between gap-3 pt-4">
<p className="truncate text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">{entry.tags.join(" / ")}</p>
<button onClick={() => postUpdate({ action: "install", ...entry, source: "registry" }, installed ? `${entry.name} refreshed from registry.` : `${entry.name} installed from registry.`)} disabled={saving} className={installed ? "action-button px-3 py-2" : "rounded-sm bg-[var(--nvidia-green)] px-3 py-2 text-xs font-mono uppercase tracking-wider text-black disabled:opacity-50"}>
{installed ? "Refresh" : "Install"}
</button>
</div>
</div>
)
})}
</div>
</>
)}
<button type="button" onClick={() => setCatalogOpen((open) => !open)} className="flex w-full items-center justify-between gap-4 border-t border-[var(--border-subtle)] pt-5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--nvidia-green)]" aria-expanded={catalogOpen}>
<div>
<h3 className="text-sm font-semibold uppercase tracking-wider text-[var(--foreground)]">Preconfigured Servers</h3>
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Presets install as MCP command definitions; clients start them when needed.</p>
</div>
<span className="text-sm text-[var(--foreground)]">{catalogOpen ? "-" : "+"}</span>
</button>
{catalogOpen && (
<div className="grid grid-cols-1 gap-3 md:grid-cols-2">
{catalog.map((entry) => {
const installed = installedIds.has(entry.id)
return (
<div key={entry.id} className="metric flex min-h-44 flex-col p-4">
<div className="flex items-start justify-between gap-3">
<div>
<h3 className="text-sm font-semibold uppercase tracking-wider text-[var(--foreground)]">{entry.name}</h3>
<p className="mt-2 text-xs leading-5 text-[var(--foreground-dim)]">{entry.summary}</p>
{entry.websiteUrl && <a href={entry.websiteUrl} target="_blank" rel="noreferrer" className="mt-2 inline-block text-[11px] font-mono uppercase tracking-wider text-[var(--nvidia-green)] hover:underline">Setup Guide</a>}
</div>
<span className="status-chip bg-[var(--status-pending-bg)] px-2 py-1 text-[var(--status-pending)]">{entry.transport}</span>
</div>
<div className="mt-3 min-w-0 rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-2 font-mono text-[11px] text-[var(--foreground-dim)]">
<span className="text-[var(--foreground)]">{entry.command}</span> {entry.args.join(" ")}
</div>
<div className="mt-auto flex items-center justify-between gap-3 pt-4">
<p className="truncate text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">{entry.tags.join(" / ")}</p>
<button onClick={() => postUpdate({ action: "install", id: entry.id }, installed ? `${entry.name} refreshed.` : `${entry.name} installed.`)} disabled={saving} className={installed ? "action-button px-3 py-2" : "rounded-sm bg-[var(--nvidia-green)] px-3 py-2 text-xs font-mono uppercase tracking-wider text-black disabled:opacity-50"}>
{installed ? "Refresh" : "Install"}
</button>
</div>
</div>
)
})}
</div>
)}
</div>
)}
</div>
@@ -705,8 +871,8 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
aria-expanded={customOpen}
>
<div>
<h2 className="text-sm font-semibold uppercase tracking-wider text-[var(--foreground)]">Custom Server</h2>
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Add a server command that is not in the catalog.</p>
<h2 className="text-sm font-semibold uppercase tracking-wider text-[var(--foreground)]">Server Install Wizard</h2>
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Install a command, HTTP endpoint, or uploaded MCP bundle with assisted preflight repair.</p>
</div>
<span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] text-sm text-[var(--foreground)]">
{customOpen ? "-" : "+"}
@@ -714,40 +880,52 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
</button>
{customOpen && (
<div className="mt-5 border-t border-[var(--border-subtle)] pt-5">
<div className="mb-5 grid grid-cols-2 gap-2 md:grid-cols-4">
{(["basics", "launch", "upload", "review"] as const).map((step) => (
<button
key={step}
type="button"
onClick={() => setWizardStep(step)}
className={`rounded-sm border px-3 py-2 text-xs font-mono uppercase tracking-wider ${wizardStep === step ? "border-[var(--nvidia-green)] bg-[var(--status-running-bg)] text-[var(--foreground)]" : "border-[var(--border-subtle)] bg-[var(--background)] text-[var(--foreground-dim)]"}`}
>
{step}
</button>
))}
</div>
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
<div className="space-y-2">
<FieldLabel>Name</FieldLabel>
<div className="flex items-center gap-2"><FieldLabel>Name</FieldLabel><FieldHint>Stable display name and default id for this MCP server.</FieldHint></div>
<input value={customName} onChange={(event) => setCustomName(event.target.value)} className="field-control w-full px-3 py-2 text-sm font-mono" />
</div>
<div className="space-y-2">
<FieldLabel>Transport</FieldLabel>
<div className="flex items-center gap-2"><FieldLabel>Transport</FieldLabel><FieldHint>Use stdio for local commands, HTTP for remote streamable MCP endpoints.</FieldHint></div>
<select value={customTransport} onChange={(event) => setCustomTransport(event.target.value as McpTransport)} className="field-control w-full px-3 py-2 text-sm font-mono">
<option value="stdio">stdio</option>
<option value="http">http</option>
</select>
</div>
<div className="space-y-2 md:col-span-2">
<FieldLabel>Summary</FieldLabel>
<div className="flex items-center gap-2"><FieldLabel>Summary</FieldLabel><FieldHint>Short note shown in the installed server list.</FieldHint></div>
<input value={customSummary} onChange={(event) => setCustomSummary(event.target.value)} className="field-control w-full px-3 py-2 text-sm" />
</div>
<div className="space-y-2 md:col-span-2">
<FieldLabel>{customTransport === "http" ? "URL" : "Command"}</FieldLabel>
<div className="flex items-center gap-2"><FieldLabel>{customTransport === "http" ? "URL" : "Command"}</FieldLabel><FieldHint>{customTransport === "http" ? "Full remote MCP endpoint URL." : "Executable available to the controller, such as npx, uvx, node, or python."}</FieldHint></div>
<input value={customCommand} onChange={(event) => 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" />
</div>
<div className="space-y-2">
<FieldLabel>Args</FieldLabel>
<div className="flex items-center gap-2"><FieldLabel>Args</FieldLabel><FieldHint>One argument per line, passed to the command in order.</FieldHint></div>
<textarea value={customArgs} onChange={(event) => setCustomArgs(event.target.value)} rows={6} className="field-control w-full resize-y px-3 py-2 text-sm font-mono" />
</div>
<div className="space-y-2">
<FieldLabel>{customTransport === "http" ? "Headers" : "Env"}</FieldLabel>
<div className="flex items-center gap-2"><FieldLabel>{customTransport === "http" ? "Headers" : "Env"}</FieldLabel><FieldHint>KEY=value lines. HTTP entries become headers; stdio entries become environment variables.</FieldHint></div>
<textarea value={customEnv} onChange={(event) => setCustomEnv(event.target.value)} rows={6} placeholder={customTransport === "http" ? "Authorization=Bearer token" : "API_KEY=value\nBASE_URL=http://localhost:3000"} className="field-control w-full resize-y px-3 py-2 text-sm font-mono" />
</div>
<div className="space-y-2">
<FieldLabel>Upload Runtime</FieldLabel>
<div className="flex items-center gap-2"><FieldLabel>Upload Runtime</FieldLabel><FieldHint>Runtime used to bootstrap uploaded bundles before preflight.</FieldHint></div>
<input value={uploadRuntime} onChange={(event) => setUploadRuntime(event.target.value)} placeholder="python3, node, uv, uvx" className="field-control w-full px-3 py-2 text-sm font-mono" />
</div>
<div className="space-y-2">
<FieldLabel>Upload Launch Mode</FieldLabel>
<div className="flex items-center gap-2"><FieldLabel>Upload Launch Mode</FieldLabel><FieldHint>How the uploaded server should start after dependencies are installed.</FieldHint></div>
<select value={uploadEntryMode} onChange={(event) => setUploadEntryMode(event.target.value as "file" | "python-module" | "console-script")} className="field-control w-full px-3 py-2 text-sm font-mono">
<option value="file">File</option>
<option value="python-module">Python module</option>
@@ -755,9 +933,35 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
</select>
</div>
<div className="space-y-2">
<FieldLabel>Upload Entrypoint</FieldLabel>
<div className="flex items-center gap-2"><FieldLabel>Upload Entrypoint</FieldLabel><FieldHint>File path, Python module name, or installed console script to launch.</FieldHint></div>
<input value={uploadEntrypoint} onChange={(event) => setUploadEntrypoint(event.target.value)} placeholder={uploadEntryMode === "python-module" ? "isaac_mcp_poc.server" : uploadEntryMode === "console-script" ? "isaac-mcp-poc" : "server.py, src/server.py, index.js"} className="field-control w-full px-3 py-2 text-sm font-mono" />
</div>
<div className="space-y-2">
<div className="flex items-center gap-2"><FieldLabel>Preflight Repair</FieldLabel><FieldHint>When preflight fails, ask the running LLM endpoint for a bounded repair and run preflight again.</FieldHint></div>
<label className="flex min-h-10 items-center justify-between gap-3 rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-3 py-2 text-xs text-[var(--foreground)]">
<span>Use sandbox LLM on failed uploads</span>
<input
type="checkbox"
checked={uploadRepair}
onChange={(event) => setUploadRepair(event.target.checked)}
className="h-4 w-4 accent-[var(--nvidia-green)]"
/>
</label>
</div>
<div className="space-y-2">
<div className="flex items-center gap-2"><FieldLabel>Repair Route</FieldLabel><FieldHint>Optional sandbox whose configured model should be used for repair assistance.</FieldHint></div>
<select
value={repairSandboxId}
onChange={(event) => setRepairSandboxId(event.target.value)}
disabled={!uploadRepair}
className="field-control w-full px-3 py-2 text-sm font-mono"
>
<option value="">Default controller model</option>
{sandboxes.map((sandbox) => (
<option key={sandbox.id} value={sandbox.id}>{sandbox.name}</option>
))}
</select>
</div>
</div>
<div className="mt-5 flex flex-wrap items-center gap-3">
<button
@@ -776,7 +980,7 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
disabled={saving}
className="rounded-sm bg-[var(--nvidia-green)] px-4 py-2 text-xs font-mono uppercase tracking-wider text-black disabled:opacity-50"
>
Install Custom Server
Install Server Command
</button>
<label className="action-button cursor-pointer px-4 py-2">
Choose Directory
+253
View File
@@ -0,0 +1,253 @@
import { readdir, readFile, stat, writeFile } from "node:fs/promises"
import path from "node:path"
import { getSandboxInferenceConfig } from "./sandboxInferenceStore"
import type { McpPreflightResult } from "./mcpPreflight"
import type { McpServerInstall } from "./mcpServerStore"
export type McpPreflightRepairChange = {
type: "file" | "launch"
path?: string
summary: string
}
export type McpPreflightRepairResult = {
attempted: boolean
ok: boolean
provider: "openai-compatible"
model: string
baseUrl: string
summary: string
changes: McpPreflightRepairChange[]
error?: string
updatedServer?: Pick<McpServerInstall, "command" | "args" | "env">
}
type RepairContext = {
uploadRoot: string
projectRoot: string
server: McpServerInstall
preflight: McpPreflightResult
dependencyLogs?: string[]
sandboxId?: string | null
}
type LlmRepairResponse = {
summary?: string
files?: Array<{ path?: string; content?: string; summary?: string }>
launch?: {
command?: string
args?: string[]
env?: Record<string, string>
summary?: string
}
}
const MAX_CONTEXT_FILE_BYTES = Number.parseInt(process.env.MCP_PREFLIGHT_REPAIR_MAX_FILE_BYTES || String(40 * 1024), 10)
const MAX_CONTEXT_FILES = Number.parseInt(process.env.MCP_PREFLIGHT_REPAIR_MAX_FILES || "18", 10)
const MAX_REPAIR_FILE_BYTES = Number.parseInt(process.env.MCP_PREFLIGHT_REPAIR_MAX_OUTPUT_FILE_BYTES || String(512 * 1024), 10)
const REQUEST_TIMEOUT_MS = Number.parseInt(process.env.MCP_PREFLIGHT_REPAIR_TIMEOUT_MS || "60000", 10)
const DEFAULT_MODEL = process.env.MCP_PREFLIGHT_LLM_MODEL || process.env.OPENAI_MODEL || "gpt-4o-mini"
const DEFAULT_BASE_URL = process.env.MCP_PREFLIGHT_LLM_BASE_URL || process.env.OPENAI_BASE_URL || process.env.VLLM_BASE_URL || "http://localhost:8000/v1"
function cleanBaseUrl(value: string) {
return value.replace(/\/+$/, "")
}
function relativeInside(root: string, candidate: string) {
const fullPath = path.resolve(root, candidate)
if (fullPath !== root && !fullPath.startsWith(`${root}${path.sep}`)) {
throw new Error("repair path must stay inside the uploaded server")
}
return fullPath
}
function normalizeRepairPath(value: string) {
const normalized = path.posix.normalize(value.replace(/\\/g, "/")).replace(/^\/+/, "")
if (!normalized || normalized === "." || normalized.startsWith("../") || normalized.includes("/../")) {
throw new Error("repair file path must be relative to the uploaded server")
}
return normalized
}
function isLikelyUsefulFile(filePath: string) {
if (/(^|\/)(node_modules|\.venv|\.git|dist|build|__pycache__)(\/|$)/.test(filePath)) return false
return /\.(py|js|mjs|cjs|ts|json|toml|txt|md|yaml|yml)$/i.test(filePath)
|| /(^|\/)(requirements\.txt|package\.json|pyproject\.toml)$/.test(filePath)
}
async function collectFiles(root: string, directory = root): Promise<string[]> {
const entries = await readdir(directory, { withFileTypes: true }).catch(() => [])
const files: string[] = []
for (const entry of entries) {
const fullPath = path.join(directory, entry.name)
const relative = path.relative(root, fullPath).replace(/\\/g, "/")
if (entry.isDirectory()) {
if (/(^|\/)(node_modules|\.venv|\.git|dist|build|__pycache__)(\/|$)/.test(relative)) continue
files.push(...await collectFiles(root, fullPath))
} else if (entry.isFile()) {
if (!isLikelyUsefulFile(relative)) continue
files.push(relative)
}
}
return files
}
async function readContextFiles(root: string) {
const files = (await collectFiles(root)).slice(0, MAX_CONTEXT_FILES)
const context: Array<{ path: string; content: string; truncated: boolean }> = []
for (const file of files) {
const fullPath = relativeInside(root, file)
const stats = await stat(fullPath).catch(() => null)
if (!stats || stats.size > MAX_CONTEXT_FILE_BYTES * 2) continue
const content = await readFile(fullPath, "utf8").catch(() => "")
context.push({
path: file,
content: content.length > MAX_CONTEXT_FILE_BYTES ? content.slice(0, MAX_CONTEXT_FILE_BYTES) : content,
truncated: content.length > MAX_CONTEXT_FILE_BYTES,
})
}
return context
}
async function resolveRepairRoute(sandboxId?: string | null) {
if (sandboxId) {
const config = await getSandboxInferenceConfig(sandboxId)
const enabled = config.routes.filter((route) => route.enabled)
const primary = enabled.find((route) => route.id === config.primaryRouteId) || enabled[0]
if (primary?.model) {
return {
model: process.env.MCP_PREFLIGHT_LLM_MODEL || primary.model,
baseUrl: cleanBaseUrl(DEFAULT_BASE_URL),
}
}
}
return {
model: DEFAULT_MODEL,
baseUrl: cleanBaseUrl(DEFAULT_BASE_URL),
}
}
function extractJsonObject(value: string) {
const trimmed = value.trim()
if (trimmed.startsWith("{")) return trimmed
const match = trimmed.match(/\{[\s\S]*\}/)
if (!match) throw new Error("repair model did not return JSON")
return match[0]
}
async function requestRepairPlan(context: RepairContext, files: Awaited<ReturnType<typeof readContextFiles>>) {
const route = await resolveRepairRoute(context.sandboxId)
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)
try {
const response = await fetch(`${route.baseUrl}/chat/completions`, {
method: "POST",
signal: controller.signal,
headers: {
"Content-Type": "application/json",
...(process.env.MCP_PREFLIGHT_LLM_API_KEY || process.env.OPENAI_API_KEY
? { Authorization: `Bearer ${process.env.MCP_PREFLIGHT_LLM_API_KEY || process.env.OPENAI_API_KEY}` }
: {}),
},
body: JSON.stringify({
model: route.model,
temperature: 0.1,
response_format: { type: "json_object" },
messages: [
{
role: "system",
content: [
"You repair uploaded Model Context Protocol stdio servers.",
"Return only JSON with optional files and launch keys.",
"Only modify files that are included in the context.",
"Do not invent dependencies unless required by the observed error.",
"Prefer minimal, runnable fixes that let MCP initialize and list tools.",
].join(" "),
},
{
role: "user",
content: JSON.stringify({
server: {
command: context.server.command,
args: context.server.args,
envKeys: Object.keys(context.server.env || {}),
},
preflight: context.preflight,
dependencyLogs: context.dependencyLogs || [],
files,
expectedJson: {
summary: "short explanation",
files: [{ path: "relative/path.py", content: "complete replacement content", summary: "what changed" }],
launch: { command: context.server.command, args: context.server.args, env: context.server.env, summary: "optional launch change" },
},
}),
},
],
}),
})
const data = await response.json().catch(() => null)
if (!response.ok) throw new Error(data?.error?.message || data?.error || `repair model request failed (${response.status})`)
const content = data?.choices?.[0]?.message?.content
if (typeof content !== "string" || !content.trim()) throw new Error("repair model returned an empty response")
return {
route,
plan: JSON.parse(extractJsonObject(content)) as LlmRepairResponse,
}
} finally {
clearTimeout(timeout)
}
}
function normalizeLaunch(server: McpServerInstall, launch?: LlmRepairResponse["launch"]) {
if (!launch || typeof launch !== "object") return null
const command = typeof launch.command === "string" && launch.command.trim() ? launch.command.trim() : server.command
const args = Array.isArray(launch.args)
? launch.args.map((arg) => String(arg ?? "").trim()).filter(Boolean)
: server.args
const env = launch.env && typeof launch.env === "object" && !Array.isArray(launch.env)
? Object.fromEntries(Object.entries(launch.env).map(([key, value]) => [key.trim(), String(value ?? "").trim()]).filter(([key]) => Boolean(key)))
: server.env
if (command === server.command && JSON.stringify(args) === JSON.stringify(server.args) && JSON.stringify(env) === JSON.stringify(server.env)) {
return null
}
return { command, args, env, summary: launch.summary || "Adjusted launch metadata." }
}
export async function repairUploadedMcpServerWithLlm(context: RepairContext): Promise<McpPreflightRepairResult> {
const files = await readContextFiles(context.projectRoot)
const { route, plan } = await requestRepairPlan(context, files)
const changes: McpPreflightRepairChange[] = []
for (const file of Array.isArray(plan.files) ? plan.files : []) {
if (typeof file?.path !== "string" || typeof file?.content !== "string") continue
if (Buffer.byteLength(file.content, "utf8") > MAX_REPAIR_FILE_BYTES) {
throw new Error(`repair output for ${file.path} is too large`)
}
const relative = normalizeRepairPath(file.path)
if (!files.some((contextFile) => contextFile.path === relative)) {
throw new Error(`repair model tried to edit a file outside provided context: ${relative}`)
}
await writeFile(relativeInside(context.projectRoot, relative), file.content, { mode: 0o600 })
changes.push({ type: "file", path: relative, summary: file.summary || `Updated ${relative}` })
}
const launch = normalizeLaunch(context.server, plan.launch)
if (launch) {
changes.push({ type: "launch", summary: launch.summary })
}
return {
attempted: true,
ok: changes.length > 0,
provider: "openai-compatible",
model: route.model,
baseUrl: route.baseUrl,
summary: plan.summary || (changes.length > 0 ? "Applied LLM-assisted MCP repair." : "The repair model did not suggest changes."),
changes,
updatedServer: launch ? {
command: launch.command,
args: launch.args,
env: launch.env,
} : undefined,
}
}
+94
View File
@@ -0,0 +1,94 @@
import { mkdir, readFile, writeFile } from "node:fs/promises"
import path from "node:path"
export type McpRegistry = {
id: string
name: string
baseUrl: string
description: string
addedAt: string
}
type StoreShape = {
registries: McpRegistry[]
}
const HOME = process.env.HOME || "/tmp"
const STORE_DIR = process.env.NEMOCLAW_DASHBOARD_STATE_DIR || path.join(HOME, ".nemoclaw-dashboard")
const STORE_PATH = path.join(STORE_DIR, "mcp-registries.json")
export const DEFAULT_MCP_REGISTRY: McpRegistry = {
id: "official",
name: "Official MCP Registry",
baseUrl: process.env.MCP_REGISTRY_BASE_URL || "https://registry.modelcontextprotocol.io",
description: "The public Model Context Protocol registry.",
addedAt: "default",
}
function slugify(value: string) {
return value
.trim()
.toLowerCase()
.replace(/[^a-z0-9-]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 64) || "mcp-registry"
}
function normalizeRegistry(input: Partial<McpRegistry>, existing?: McpRegistry | null): McpRegistry {
const name = typeof input.name === "string" && input.name.trim() ? input.name.trim() : existing?.name || "MCP Registry"
const rawUrl = typeof input.baseUrl === "string" && input.baseUrl.trim() ? input.baseUrl.trim() : existing?.baseUrl || ""
if (!rawUrl) throw new Error("registry URL is required")
const parsed = new URL(rawUrl)
parsed.pathname = parsed.pathname.replace(/\/+$/, "")
parsed.search = ""
parsed.hash = ""
return {
id: slugify(input.id || existing?.id || name),
name,
baseUrl: parsed.toString().replace(/\/+$/, ""),
description: typeof input.description === "string" ? input.description.trim() : existing?.description || "",
addedAt: existing?.addedAt || new Date().toISOString(),
}
}
async function readStore(): Promise<StoreShape | null> {
try {
const raw = await readFile(STORE_PATH, "utf8")
const parsed = JSON.parse(raw)
return parsed && typeof parsed === "object" && Array.isArray(parsed.registries)
? parsed
: null
} catch {
return null
}
}
async function writeStore(store: StoreShape) {
await mkdir(STORE_DIR, { recursive: true, mode: 0o700 })
await writeFile(STORE_PATH, JSON.stringify(store, null, 2), { mode: 0o600 })
}
export async function listMcpRegistries() {
const store = await readStore()
return store?.registries || [DEFAULT_MCP_REGISTRY]
}
export async function saveMcpRegistry(input: Partial<McpRegistry>) {
const store = await readStore() || { registries: [DEFAULT_MCP_REGISTRY] }
const id = slugify(input.id || input.name || "mcp-registry")
const existing = store.registries.find((registry) => registry.id === id)
const next = normalizeRegistry({ ...input, id }, existing)
const filtered = store.registries.filter((registry) => registry.id !== next.id)
store.registries = [next, ...filtered]
await writeStore(store)
return next
}
export async function deleteMcpRegistry(registryId: string) {
const id = slugify(registryId)
const store = await readStore() || { registries: [DEFAULT_MCP_REGISTRY] }
store.registries = store.registries.filter((registry) => registry.id !== id)
await writeStore(store)
return { id }
}