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 { NextResponse } from "next/server"
import type { McpCatalogEntry } from "@/app/lib/mcpServerStore" 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 = { type RegistryArgument = {
value?: string value?: string
@@ -126,7 +126,8 @@ export async function GET(request: Request) {
const requestUrl = new URL(request.url) const requestUrl = new URL(request.url)
const search = requestUrl.searchParams.get("search") || requestUrl.searchParams.get("q") || "" 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 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("limit", String(limit))
registryUrl.searchParams.set("is_latest", "true") registryUrl.searchParams.set("is_latest", "true")
if (search.trim()) registryUrl.searchParams.set("search", search.trim()) 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 path from "node:path"
import { promisify } from "node:util" import { promisify } from "node:util"
import { preflightMcpServer } from "@/app/lib/mcpPreflight" 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 execFileAsync = promisify(execFile)
const HOME = process.env.HOME || "/tmp" 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 runtime = String(form.get("runtime") || "python3").trim()
const entrypoint = String(form.get("entrypoint") || "server.py").trim() const entrypoint = String(form.get("entrypoint") || "server.py").trim()
const entryMode = normalizeEntryMode(form.get("entryMode")) 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) const root = path.join(UPLOAD_DIR, id)
if (!runtime) throw new Error("runtime command is required") 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 projectRoot = await resolveProjectRoot(root, entrypointPath)
const bootstrap = await bootstrapUploadedServer(projectRoot, runtime, entrypoint) const bootstrap = await bootstrapUploadedServer(projectRoot, runtime, entrypoint)
const launch = await launchCommandForUpload(projectRoot, bootstrap, entryMode, entrypoint, entrypointPath, parseLines(form.get("args"))) const launch = await launchCommandForUpload(projectRoot, bootstrap, entryMode, entrypoint, entrypointPath, parseLines(form.get("args")))
const candidate = { let candidate = {
id, id,
name, name,
summary, summary,
@@ -322,7 +325,7 @@ export async function POST(request: Request) {
tags: ["uploaded", "custom"], tags: ["uploaded", "custom"],
source: "custom", source: "custom",
enabled: true, enabled: true,
} as const satisfies { } satisfies {
id: string id: string
name: string name: string
summary: string summary: string
@@ -334,13 +337,51 @@ export async function POST(request: Request) {
source: "custom" source: "custom"
enabled: boolean enabled: boolean
} }
const preflight = await preflightMcpServer({ const installCandidate = (): McpServerInstall => ({
...candidate, ...candidate,
installedAt: new Date().toISOString(), installedAt: new Date().toISOString(),
updatedAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
accessMode: "disabled", accessMode: "disabled",
allowedSandboxIds: [], 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({ const server = await installMcpServer({
...candidate, ...candidate,
enabled: preflight.ok, enabled: preflight.ok,
@@ -357,6 +398,7 @@ export async function POST(request: Request) {
logs: bootstrap.logs, logs: bootstrap.logs,
}, },
preflight, preflight,
repair,
...(await listMcpServers()), ...(await listMcpServers()),
}) })
} catch (error) { } catch (error) {
+330 -126
View File
@@ -32,6 +32,14 @@ type McpResponse = {
error?: string error?: string
} }
type McpRegistry = {
id: string
name: string
baseUrl: string
description: string
addedAt: string
}
type McpPreflightResult = { type McpPreflightResult = {
ok: boolean ok: boolean
checkedAt: string 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 = { type McpSandbox = {
id: string id: string
name: 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> 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) { function parseLines(value: string) {
return value return value
.split(/\r?\n/) .split(/\r?\n/)
@@ -100,6 +134,8 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
const [uploadRuntime, setUploadRuntime] = useState("python3") const [uploadRuntime, setUploadRuntime] = useState("python3")
const [uploadEntryMode, setUploadEntryMode] = useState<"file" | "python-module" | "console-script">("file") const [uploadEntryMode, setUploadEntryMode] = useState<"file" | "python-module" | "console-script">("file")
const [uploadEntrypoint, setUploadEntrypoint] = useState("server.py") const [uploadEntrypoint, setUploadEntrypoint] = useState("server.py")
const [uploadRepair, setUploadRepair] = useState(true)
const [repairSandboxId, setRepairSandboxId] = useState("")
const [editingServerId, setEditingServerId] = useState<string | null>(null) const [editingServerId, setEditingServerId] = useState<string | null>(null)
const [editorText, setEditorText] = useState("") const [editorText, setEditorText] = useState("")
const [registrySearch, setRegistrySearch] = useState("github") const [registrySearch, setRegistrySearch] = useState("github")
@@ -107,14 +143,25 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
const [registryLoading, setRegistryLoading] = useState(false) const [registryLoading, setRegistryLoading] = useState(false)
const [registryPage, setRegistryPage] = useState(1) const [registryPage, setRegistryPage] = useState(1)
const [lastRegistrySearch, setLastRegistrySearch] = useState("") 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 [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 [catalogOpen, setCatalogOpen] = useState(false)
const [customOpen, setCustomOpen] = 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 installedIds = useMemo(() => new Set(servers.map((server) => server.id)), [servers])
const enabledCount = servers.filter((server) => server.enabled).length const enabledCount = servers.filter((server) => server.enabled).length
const configText = JSON.stringify(config, null, 2) const configText = JSON.stringify(config, null, 2)
const registryPageCount = Math.max(1, Math.ceil(registryResults.length / REGISTRY_PAGE_SIZE)) 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( const pagedRegistryResults = registryResults.slice(
(registryPage - 1) * REGISTRY_PAGE_SIZE, (registryPage - 1) * REGISTRY_PAGE_SIZE,
registryPage * REGISTRY_PAGE_SIZE, registryPage * REGISTRY_PAGE_SIZE,
@@ -123,12 +170,20 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
async function load() { async function load() {
try { try {
setLoading(true) 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 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 (!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 : []) setCatalog(Array.isArray(data.catalog) ? data.catalog : [])
setServers(Array.isArray(data.servers) ? data.servers : []) setServers(Array.isArray(data.servers) ? data.servers : [])
setConfig(data.config || { mcpServers: {} }) 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("") setMessage("")
} catch (error) { } catch (error) {
setMessage(error instanceof Error ? error.message : "Failed to load MCP configuration") 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) { async function postUpdate(body: Record<string, unknown>, success: string) {
try { try {
setSaving(true) 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}` 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) { async function preflightServer(server: McpServerInstall) {
try { try {
setSaving(true) setSaving(true)
@@ -357,6 +490,8 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
form.set("entrypoint", uploadEntrypoint) form.set("entrypoint", uploadEntrypoint)
form.set("args", customArgs) form.set("args", customArgs)
form.set("env", customEnv) form.set("env", customEnv)
form.set("repair", uploadRepair ? "true" : "false")
if (repairSandboxId) form.set("sandboxId", repairSandboxId)
if (uploadArchive) { if (uploadArchive) {
form.set("archive", uploadArchive) form.set("archive", uploadArchive)
} else { } else {
@@ -366,7 +501,7 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
}) })
} }
const response = await fetch("/api/mcp/upload", { method: "POST", body: form }) 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") if (!response.ok) throw new Error(data.error || "Failed to upload MCP server")
setCatalog(Array.isArray(data.catalog) ? data.catalog : catalog) setCatalog(Array.isArray(data.catalog) ? data.catalog : catalog)
setServers(Array.isArray(data.servers) ? data.servers : []) setServers(Array.isArray(data.servers) ? data.servers : [])
@@ -382,7 +517,7 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
const preflightNote = data.preflight const preflightNote = data.preflight
? `\nPreflight ${data.preflight.ok ? "passed" : "failed; server saved disabled"}.\n${summarizePreflight(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) { } catch (error) {
setMessage(error instanceof Error ? error.message : "Failed to upload MCP server") setMessage(error instanceof Error ? error.message : "Failed to upload MCP server")
} finally { } finally {
@@ -408,18 +543,22 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
async function searchRegistry() { async function searchRegistry() {
const query = registrySearch.trim() const query = registrySearch.trim()
if (!selectedRegistry) {
setMessage("Add an MCP Registry before searching.")
return
}
try { try {
setRegistryLoading(true) setRegistryLoading(true)
setRegistryResults([]) setRegistryResults([])
setRegistryPage(1) setRegistryPage(1)
setLastRegistrySearch(query) 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 response = await fetch(`/api/mcp/registry?${params}`, { cache: "no-store" })
const data = await response.json() const data = await response.json()
if (!response.ok) throw new Error(data.error || "Failed to search MCP registry") if (!response.ok) throw new Error(data.error || "Failed to search MCP registry")
const results = Array.isArray(data.results) ? data.results : [] const results = Array.isArray(data.results) ? data.results : []
setRegistryResults(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) { } catch (error) {
setRegistryResults([]) setRegistryResults([])
setMessage(error instanceof Error ? error.message : "Failed to search MCP registry") setMessage(error instanceof Error ? error.message : "Failed to search MCP registry")
@@ -475,54 +614,58 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
<div className="grid grid-cols-1 gap-6 xl:grid-cols-[minmax(0,1fr)_400px]"> <div className="grid grid-cols-1 gap-6 xl:grid-cols-[minmax(0,1fr)_400px]">
<section className="space-y-6"> <section className="space-y-6">
<div className="panel p-6"> <div className="panel p-6">
<div className="border-b border-[var(--border-subtle)] pb-4"> <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> <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> <p className="mt-1 text-xs text-[var(--foreground-dim)]">Control which installed MCP servers are available to sandboxes.</p>
</div> </div>
<div className="mt-5 space-y-4"> <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 ? ( {servers.length === 0 ? (
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 text-xs text-[var(--foreground-dim)]"> <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. Install an MCP server before configuring sandbox access.
</div> </div>
) : servers.map((server) => ( ) : servers.map((server) => {
<div key={server.id} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4"> const expanded = openSecurityServers[server.id] !== false
<div className="flex items-start justify-between gap-4 max-lg:flex-col"> return (
<div className="min-w-0"> <div key={server.id} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)]">
<div className="flex items-center gap-2"> <button
<h3 className="truncate text-sm font-mono font-semibold text-[var(--foreground)]">{server.name}</h3> 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}
>
<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)]"}`}> <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"} {server.enabled ? "enabled" : "disabled"}
</span> </span>
</div> </span>
<p className="mt-2 break-all font-mono text-[11px] text-[var(--foreground-dim)]">{server.command} {server.args.join(" ")}</p> <span className="mt-2 block break-all font-mono text-[11px] text-[var(--foreground-dim)]">{server.command} {server.args.join(" ")}</span>
</div> </span>
<div className="flex shrink-0 gap-2 max-sm:w-full max-sm:[&>button]:flex-1"> <span className="text-sm text-[var(--foreground)]">{expanded ? "-" : "+"}</span>
<button
onClick={() => setServerEnabled(server, true)}
disabled={saving || server.enabled}
className="action-button px-3 py-2"
>
Enable
</button> </button>
<button
onClick={() => setServerEnabled(server, false)}
disabled={saving || !server.enabled}
className="action-button px-3 py-2"
>
Disable
</button>
</div>
</div>
{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="mt-4 grid grid-cols-1 gap-3 lg:grid-cols-[240px_minmax(0,1fr)]">
<div className="space-y-2"> <div className="space-y-2">
<FieldLabel>Availability</FieldLabel> <FieldLabel>Availability</FieldLabel>
<select <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">
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="disabled">Disabled</option>
<option value="allow_all">Allow All</option> <option value="allow_all">Allow All</option>
<option value="allow_only">Allow Only</option> <option value="allow_only">Allow Only</option>
@@ -531,9 +674,7 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
<div className={server.accessMode === "allow_only" ? "space-y-2" : "opacity-50"}> <div className={server.accessMode === "allow_only" ? "space-y-2" : "opacity-50"}>
<FieldLabel>Allowed Sandboxes</FieldLabel> <FieldLabel>Allowed Sandboxes</FieldLabel>
{sandboxes.length === 0 ? ( {sandboxes.length === 0 ? (
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-3 text-xs text-[var(--foreground-dim)]"> <div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-3 text-xs text-[var(--foreground-dim)]">No sandboxes detected.</div>
No sandboxes detected.
</div>
) : ( ) : (
<div className="grid grid-cols-1 gap-2 md:grid-cols-2"> <div className="grid grid-cols-1 gap-2 md:grid-cols-2">
{sandboxes.map((sandbox) => ( {sandboxes.map((sandbox) => (
@@ -542,13 +683,7 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
<span className="block truncate font-mono text-[var(--foreground)]">{sandbox.name}</span> <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 className="mt-1 block truncate text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">{sandbox.status}</span>
</span> </span>
<input <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)]" />
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> </label>
))} ))}
</div> </div>
@@ -556,62 +691,112 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
</div> </div>
</div> </div>
</div> </div>
))} )}
</div> </div>
)
})}
</div>
)}
</div> </div>
<div className="panel p-6"> <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"> <button
type="button"
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={repoOpen}
>
<div> <div>
<h2 className="text-sm font-semibold uppercase tracking-wider text-[var(--foreground)]">Registry Search</h2> <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)]">Search the Official MCP Registry and install compatible stdio or remote HTTP servers.</p> <p className="mt-1 text-xs text-[var(--foreground-dim)]">Choose a registry, search installable MCP servers, or install a preset.</p>
</div> </div>
<a href="https://registry.modelcontextprotocol.io/" target="_blank" rel="noreferrer" className="action-button px-3 py-2"> <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)]">
Open Registry {repoOpen ? "-" : "+"}
</a> </span>
</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> </div>
<div className="mt-5 flex gap-3 max-sm:flex-col"> {registries.length === 0 ? (
<input <div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 text-xs text-[var(--foreground-dim)]">
value={registrySearch} Add an MCP Registry
onChange={(event) => setRegistrySearch(event.target.value)} </div>
onKeyDown={(event) => { ) : (
if (event.key === "Enter") searchRegistry() <div className="grid grid-cols-1 gap-2 md:grid-cols-2">
}} {registries.map((registry) => {
placeholder="Search GitHub, Slack, filesystem, Postgres..." const selected = registry.id === selectedRegistryId
className="field-control min-w-0 flex-1 px-3 py-2 text-sm" return (
/> <button
<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"> 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"} {registryLoading ? "Searching..." : "Search"}
</button> </button>
</div> </div>
{registryResults.length > 0 && ( {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"> <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)]"> <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} Showing {((registryPage - 1) * REGISTRY_PAGE_SIZE) + 1}-{Math.min(registryPage * REGISTRY_PAGE_SIZE, registryResults.length)} of {registryResults.length}
{lastRegistrySearch ? ` for "${lastRegistrySearch}"` : ""} {lastRegistrySearch ? ` for "${lastRegistrySearch}"` : ""}{selectedRegistry ? ` in ${selectedRegistry.name}` : ""}
</p> </p>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<button <button onClick={() => setRegistryPage((page) => Math.max(1, page - 1))} disabled={registryPage === 1} className="action-button px-3 py-2">Prev</button>
onClick={() => setRegistryPage((page) => Math.max(1, page - 1))} <span className="min-w-16 text-center text-xs font-mono text-[var(--foreground-dim)]">{registryPage} / {registryPageCount}</span>
disabled={registryPage === 1} <button onClick={() => setRegistryPage((page) => Math.min(registryPageCount, page + 1))} disabled={registryPage === registryPageCount} className="action-button px-3 py-2">Next</button>
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> </div>
<div className="mt-4 grid grid-cols-1 gap-3 md:grid-cols-2"> <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
{pagedRegistryResults.map((entry, index) => { {pagedRegistryResults.map((entry, index) => {
const installed = installedIds.has(entry.id) const installed = installedIds.has(entry.id)
return ( return (
@@ -628,11 +813,7 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
</div> </div>
<div className="mt-auto flex items-center justify-between gap-3 pt-4"> <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> <p className="truncate text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">{entry.tags.join(" / ")}</p>
<button <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"}>
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"} {installed ? "Refresh" : "Install"}
</button> </button>
</div> </div>
@@ -642,25 +823,16 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
</div> </div>
</> </>
)} )}
</div>
<div className="panel p-6"> <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}>
<button
type="button"
onClick={() => setCatalogOpen((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}
>
<div> <div>
<h2 className="text-sm font-semibold uppercase tracking-wider text-[var(--foreground)]">Preconfigured Servers</h2> <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> <p className="mt-1 text-xs text-[var(--foreground-dim)]">Presets install as MCP command definitions; clients start them when needed.</p>
</div> </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)]"> <span className="text-sm text-[var(--foreground)]">{catalogOpen ? "-" : "+"}</span>
{catalogOpen ? "-" : "+"}
</span>
</button> </button>
{catalogOpen && ( {catalogOpen && (
<div className="mt-5 grid grid-cols-1 gap-3 border-t border-[var(--border-subtle)] pt-5 md:grid-cols-2"> <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
{catalog.map((entry) => { {catalog.map((entry) => {
const installed = installedIds.has(entry.id) const installed = installedIds.has(entry.id)
return ( return (
@@ -669,11 +841,7 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
<div> <div>
<h3 className="text-sm font-semibold uppercase tracking-wider text-[var(--foreground)]">{entry.name}</h3> <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> <p className="mt-2 text-xs leading-5 text-[var(--foreground-dim)]">{entry.summary}</p>
{entry.websiteUrl && ( {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>}
<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> </div>
<span className="status-chip bg-[var(--status-pending-bg)] px-2 py-1 text-[var(--status-pending)]">{entry.transport}</span> <span className="status-chip bg-[var(--status-pending-bg)] px-2 py-1 text-[var(--status-pending)]">{entry.transport}</span>
</div> </div>
@@ -682,11 +850,7 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
</div> </div>
<div className="mt-auto flex items-center justify-between gap-3 pt-4"> <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> <p className="truncate text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">{entry.tags.join(" / ")}</p>
<button <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"}>
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"} {installed ? "Refresh" : "Install"}
</button> </button>
</div> </div>
@@ -696,6 +860,8 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
</div> </div>
)} )}
</div> </div>
)}
</div>
<div className="panel p-6"> <div className="panel p-6">
<button <button
@@ -705,8 +871,8 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
aria-expanded={customOpen} aria-expanded={customOpen}
> >
<div> <div>
<h2 className="text-sm font-semibold uppercase tracking-wider text-[var(--foreground)]">Custom Server</h2> <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)]">Add a server command that is not in the catalog.</p> <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> </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)]"> <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 ? "-" : "+"} {customOpen ? "-" : "+"}
@@ -714,40 +880,52 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
</button> </button>
{customOpen && ( {customOpen && (
<div className="mt-5 border-t border-[var(--border-subtle)] pt-5"> <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="grid grid-cols-1 gap-4 md:grid-cols-2">
<div className="space-y-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" /> <input value={customName} onChange={(event) => setCustomName(event.target.value)} className="field-control w-full px-3 py-2 text-sm font-mono" />
</div> </div>
<div className="space-y-2"> <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"> <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="stdio">stdio</option>
<option value="http">http</option> <option value="http">http</option>
</select> </select>
</div> </div>
<div className="space-y-2 md:col-span-2"> <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" /> <input value={customSummary} onChange={(event) => setCustomSummary(event.target.value)} className="field-control w-full px-3 py-2 text-sm" />
</div> </div>
<div className="space-y-2 md:col-span-2"> <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" /> <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>
<div className="space-y-2"> <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" /> <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>
<div className="space-y-2"> <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" /> <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>
<div className="space-y-2"> <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" /> <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>
<div className="space-y-2"> <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"> <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="file">File</option>
<option value="python-module">Python module</option> <option value="python-module">Python module</option>
@@ -755,9 +933,35 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
</select> </select>
</div> </div>
<div className="space-y-2"> <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" /> <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>
<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>
<div className="mt-5 flex flex-wrap items-center gap-3"> <div className="mt-5 flex flex-wrap items-center gap-3">
<button <button
@@ -776,7 +980,7 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
disabled={saving} 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" 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> </button>
<label className="action-button cursor-pointer px-4 py-2"> <label className="action-button cursor-pointer px-4 py-2">
Choose Directory 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 }
}
+40 -3
View File
@@ -14,11 +14,15 @@ const uploadRoutePath = path.join(root, 'app/api/mcp/upload/route.ts')
const preflightRoutePath = path.join(root, 'app/api/mcp/preflight/route.ts') const preflightRoutePath = path.join(root, 'app/api/mcp/preflight/route.ts')
const healthRoutePath = path.join(root, 'app/api/mcp/health/route.ts') const healthRoutePath = path.join(root, 'app/api/mcp/health/route.ts')
const registryRoutePath = path.join(root, 'app/api/mcp/registry/route.ts') const registryRoutePath = path.join(root, 'app/api/mcp/registry/route.ts')
const registriesRoutePath = path.join(root, 'app/api/mcp/registries/route.ts')
const registriesAssistRoutePath = path.join(root, 'app/api/mcp/registries/assist/route.ts')
const registryStorePath = path.join(root, 'app/lib/mcpRegistryStore.ts')
const brokerCapabilitiesRoutePath = path.join(root, 'app/api/mcp/broker/capabilities/route.ts') const brokerCapabilitiesRoutePath = path.join(root, 'app/api/mcp/broker/capabilities/route.ts')
const brokerCallRoutePath = path.join(root, 'app/api/mcp/broker/call/route.ts') const brokerCallRoutePath = path.join(root, 'app/api/mcp/broker/call/route.ts')
const sandboxMcpRoutePath = path.join(root, 'app/api/sandbox/[sandboxId]/mcp/route.ts') const sandboxMcpRoutePath = path.join(root, 'app/api/sandbox/[sandboxId]/mcp/route.ts')
const brokerUrlPath = path.join(root, 'app/lib/mcpBrokerUrl.ts') const brokerUrlPath = path.join(root, 'app/lib/mcpBrokerUrl.ts')
const preflightLibPath = path.join(root, 'app/lib/mcpPreflight.ts') const preflightLibPath = path.join(root, 'app/lib/mcpPreflight.ts')
const preflightRepairLibPath = path.join(root, 'app/lib/mcpPreflightRepair.ts')
const middlewarePath = path.join(root, 'middleware.ts') const middlewarePath = path.join(root, 'middleware.ts')
const panelPath = path.join(root, 'app/components/McpConfigurationPanel.tsx') const panelPath = path.join(root, 'app/components/McpConfigurationPanel.tsx')
const helpPath = path.join(root, 'app/components/HelpPanel.tsx') const helpPath = path.join(root, 'app/components/HelpPanel.tsx')
@@ -26,7 +30,7 @@ const sidebarPath = path.join(root, 'app/components/Sidebar.tsx')
const sandboxListPath = path.join(root, 'app/components/SandboxList.tsx') const sandboxListPath = path.join(root, 'app/components/SandboxList.tsx')
const pagePath = path.join(root, 'app/page.tsx') const pagePath = path.join(root, 'app/page.tsx')
const [storeSource, brokerStoreSource, brokerClientSource, manifestSource, privilegedFilesSource, routeSource, uploadRouteSource, preflightRouteSource, healthRouteSource, registryRouteSource, brokerCapabilitiesRouteSource, brokerCallRouteSource, sandboxMcpRouteSource, brokerUrlSource, preflightLibSource, middlewareSource, panelSource, helpSource, sidebarSource, sandboxListSource, pageSource] = await Promise.all([ const [storeSource, brokerStoreSource, brokerClientSource, manifestSource, privilegedFilesSource, routeSource, uploadRouteSource, preflightRouteSource, healthRouteSource, registryRouteSource, registriesRouteSource, registriesAssistRouteSource, registryStoreSource, brokerCapabilitiesRouteSource, brokerCallRouteSource, sandboxMcpRouteSource, brokerUrlSource, preflightLibSource, preflightRepairLibSource, middlewareSource, panelSource, helpSource, sidebarSource, sandboxListSource, pageSource] = await Promise.all([
readFile(storePath, 'utf8'), readFile(storePath, 'utf8'),
readFile(brokerStorePath, 'utf8'), readFile(brokerStorePath, 'utf8'),
readFile(brokerClientPath, 'utf8'), readFile(brokerClientPath, 'utf8'),
@@ -37,11 +41,15 @@ const [storeSource, brokerStoreSource, brokerClientSource, manifestSource, privi
readFile(preflightRoutePath, 'utf8'), readFile(preflightRoutePath, 'utf8'),
readFile(healthRoutePath, 'utf8'), readFile(healthRoutePath, 'utf8'),
readFile(registryRoutePath, 'utf8'), readFile(registryRoutePath, 'utf8'),
readFile(registriesRoutePath, 'utf8'),
readFile(registriesAssistRoutePath, 'utf8'),
readFile(registryStorePath, 'utf8'),
readFile(brokerCapabilitiesRoutePath, 'utf8'), readFile(brokerCapabilitiesRoutePath, 'utf8'),
readFile(brokerCallRoutePath, 'utf8'), readFile(brokerCallRoutePath, 'utf8'),
readFile(sandboxMcpRoutePath, 'utf8'), readFile(sandboxMcpRoutePath, 'utf8'),
readFile(brokerUrlPath, 'utf8'), readFile(brokerUrlPath, 'utf8'),
readFile(preflightLibPath, 'utf8'), readFile(preflightLibPath, 'utf8'),
readFile(preflightRepairLibPath, 'utf8'),
readFile(middlewarePath, 'utf8'), readFile(middlewarePath, 'utf8'),
readFile(panelPath, 'utf8'), readFile(panelPath, 'utf8'),
readFile(helpPath, 'utf8'), readFile(helpPath, 'utf8'),
@@ -108,6 +116,8 @@ assert.match(uploadRouteSource, /python-module/, 'MCP upload API must support Py
assert.match(uploadRouteSource, /console-script/, 'MCP upload API must support installed console script launch') assert.match(uploadRouteSource, /console-script/, 'MCP upload API must support installed console script launch')
assert.match(uploadRouteSource, /resolveProjectRoot/, 'MCP upload API must find project manifests inside uploaded directories') assert.match(uploadRouteSource, /resolveProjectRoot/, 'MCP upload API must find project manifests inside uploaded directories')
assert.match(uploadRouteSource, /preflightMcpServer/, 'MCP upload API must preflight uploaded server bundles') assert.match(uploadRouteSource, /preflightMcpServer/, 'MCP upload API must preflight uploaded server bundles')
assert.match(uploadRouteSource, /repairUploadedMcpServerWithLlm/, 'MCP upload API must attempt bounded LLM repair when uploaded server preflight fails')
assert.match(uploadRouteSource, /form\.get\("sandboxId"\)/, 'MCP upload API must accept a sandbox id so repair can mirror that sandbox LLM route')
assert.match(uploadRouteSource, /preflight-failed/, 'MCP upload API must mark failed preflight installs') assert.match(uploadRouteSource, /preflight-failed/, 'MCP upload API must mark failed preflight installs')
assert.match(uploadRouteSource, /installMcpServer/, 'MCP upload API must install uploaded server bundles') assert.match(uploadRouteSource, /installMcpServer/, 'MCP upload API must install uploaded server bundles')
assert.match(preflightRouteSource, /export async function POST/, 'MCP preflight API must expose a POST check endpoint') assert.match(preflightRouteSource, /export async function POST/, 'MCP preflight API must expose a POST check endpoint')
@@ -115,6 +125,11 @@ assert.match(preflightRouteSource, /preflightMcpServer/, 'MCP preflight API must
assert.match(preflightLibSource, /listBrokerServerTools/, 'MCP preflight must validate servers through SDK tool discovery') assert.match(preflightLibSource, /listBrokerServerTools/, 'MCP preflight must validate servers through SDK tool discovery')
assert.match(preflightLibSource, /attempted relative import/, 'MCP preflight assistant must recognize Python package launch failures') assert.match(preflightLibSource, /attempted relative import/, 'MCP preflight assistant must recognize Python package launch failures')
assert.match(preflightLibSource, /FastMCP/, 'MCP preflight assistant must recognize MCP SDK compatibility failures') assert.match(preflightLibSource, /FastMCP/, 'MCP preflight assistant must recognize MCP SDK compatibility failures')
assert.match(preflightRepairLibSource, /getSandboxInferenceConfig/, 'MCP preflight repair must reuse the selected sandbox inference profile when available')
assert.match(preflightRepairLibSource, /chat\/completions/, 'MCP preflight repair must call an OpenAI-compatible chat endpoint')
assert.match(preflightRepairLibSource, /response_format: \{ type: "json_object" \}/, 'MCP preflight repair must ask the model for structured JSON')
assert.match(preflightRepairLibSource, /repair path must stay inside the uploaded server/, 'MCP preflight repair must confine edits to the uploaded server')
assert.match(preflightRepairLibSource, /provided context/, 'MCP preflight repair must only edit files shown to the model')
assert.match(healthRouteSource, /listBrokerServerTools/, 'MCP health API must inspect server tools through the broker client') assert.match(healthRouteSource, /listBrokerServerTools/, 'MCP health API must inspect server tools through the broker client')
assert.match(healthRouteSource, /enabledServers/, 'MCP health API must check enabled MCP servers') assert.match(healthRouteSource, /enabledServers/, 'MCP health API must check enabled MCP servers')
assert.match(registryRouteSource, /registry\.modelcontextprotocol\.io/, 'MCP registry search should default to the official registry') assert.match(registryRouteSource, /registry\.modelcontextprotocol\.io/, 'MCP registry search should default to the official registry')
@@ -122,7 +137,16 @@ assert.match(registryRouteSource, /\/v0\/servers/, 'MCP registry search should c
assert.match(registryRouteSource, /normalizeRegistryEntry/, 'MCP registry search should normalize results into installable entries') assert.match(registryRouteSource, /normalizeRegistryEntry/, 'MCP registry search should normalize results into installable entries')
assert.match(registryRouteSource, /packageInstall/, 'MCP registry search should support package-backed stdio installs') assert.match(registryRouteSource, /packageInstall/, 'MCP registry search should support package-backed stdio installs')
assert.match(registryRouteSource, /remoteInstall/, 'MCP registry search should support remote HTTP installs') assert.match(registryRouteSource, /remoteInstall/, 'MCP registry search should support remote HTTP installs')
assert.match(panelSource, /Install Custom Server/, 'MCP page must expose a custom server install action') assert.match(registryRouteSource, /searchParams\.get\("baseUrl"\)/, 'MCP registry search must accept a selected registry base URL')
assert.match(registryStoreSource, /mcp-registries\.json/, 'MCP registries must persist to dashboard state')
assert.match(registryStoreSource, /DEFAULT_MCP_REGISTRY/, 'MCP registries should start with the official registry before user changes')
assert.match(registriesRouteSource, /listMcpRegistries/, 'MCP registries API must list registries')
assert.match(registriesRouteSource, /saveMcpRegistry/, 'MCP registries API must save registries')
assert.match(registriesRouteSource, /deleteMcpRegistry/, 'MCP registries API must delete registries')
assert.match(registriesAssistRouteSource, /chat\/completions/, 'MCP registry assistant must use the running OpenAI-compatible LLM endpoint')
assert.match(registriesAssistRouteSource, /response_format: \{ type: "json_object" \}/, 'MCP registry assistant must request structured JSON')
assert.match(panelSource, /Install Server Command/, 'MCP page must expose a server command install action')
assert.match(panelSource, /Server Install Wizard/, 'MCP page must present custom installation as a wizard')
assert.match(panelSource, /Upload Server/, 'MCP custom server accordion must support uploaded server bundles') assert.match(panelSource, /Upload Server/, 'MCP custom server accordion must support uploaded server bundles')
assert.match(panelSource, /Choose Directory/, 'MCP custom server upload must accept directories') assert.match(panelSource, /Choose Directory/, 'MCP custom server upload must accept directories')
assert.match(panelSource, /Choose Archive/, 'MCP custom server upload must accept archives') assert.match(panelSource, /Choose Archive/, 'MCP custom server upload must accept archives')
@@ -132,13 +156,24 @@ assert.match(panelSource, /uploadEntrypoint/, 'MCP custom server upload must col
assert.match(panelSource, /uploadEntryMode/, 'MCP custom server upload must collect a launch mode') assert.match(panelSource, /uploadEntryMode/, 'MCP custom server upload must collect a launch mode')
assert.match(panelSource, /Python module/, 'MCP custom server upload must expose Python module launch mode') assert.match(panelSource, /Python module/, 'MCP custom server upload must expose Python module launch mode')
assert.match(panelSource, /Console script/, 'MCP custom server upload must expose console script launch mode') assert.match(panelSource, /Console script/, 'MCP custom server upload must expose console script launch mode')
assert.match(panelSource, /uploadRepair/, 'MCP custom server upload must expose LLM repair controls')
assert.match(panelSource, /repairSandboxId/, 'MCP custom server upload must let operators pick a sandbox LLM route for repair')
assert.match(panelSource, /LLM repair/, 'MCP custom server upload must summarize LLM-assisted repair results')
assert.match(panelSource, /FieldHint/, 'MCP server install wizard fields must include tooltips')
assert.match(panelSource, /wizardStep/, 'MCP server install wizard must expose install workflow steps')
assert.match(panelSource, /preflightServer/, 'MCP page must let operators preflight installed servers') assert.match(panelSource, /preflightServer/, 'MCP page must let operators preflight installed servers')
assert.match(panelSource, /Preflight/, 'MCP page must show preflight controls and results') assert.match(panelSource, /Preflight/, 'MCP page must show preflight controls and results')
assert.match(panelSource, /serverPayloadFromJson/, 'MCP page must parse edited server JSON') assert.match(panelSource, /serverPayloadFromJson/, 'MCP page must parse edited server JSON')
assert.match(panelSource, /startEditingServer/, 'MCP installed server list must expose edit state') assert.match(panelSource, /startEditingServer/, 'MCP installed server list must expose edit state')
assert.match(panelSource, /Server JSON/, 'MCP installed server editor must render an inline JSON file editor') assert.match(panelSource, /Server JSON/, 'MCP installed server editor must render an inline JSON file editor')
assert.match(panelSource, /Registry Search/, 'MCP page must expose official registry search') assert.match(panelSource, /MCP Repo Search and Preconfigured Servers/, 'MCP page must combine repo search and preconfigured servers')
assert.match(panelSource, /Available Registries/, 'MCP page must display available registries')
assert.match(panelSource, /Add an MCP Registry/, 'MCP page must show an add-registry empty state')
assert.match(panelSource, /Draft With LLM/, 'MCP page must let the running LLM draft registry fields')
assert.match(panelSource, /Delete Selected Registry/, 'MCP page must allow deleting registries')
assert.match(panelSource, /selectedRegistryId/, 'MCP page must track and highlight the selected registry')
assert.match(panelSource, /\/api\/mcp\/registry/, 'MCP page must query the registry search API') assert.match(panelSource, /\/api\/mcp\/registry/, 'MCP page must query the registry search API')
assert.match(panelSource, /\/api\/mcp\/registries/, 'MCP page must manage registry sources through the registry API')
assert.match(panelSource, /const REGISTRY_PAGE_SIZE = 4/, 'MCP registry search should page results four at a time') assert.match(panelSource, /const REGISTRY_PAGE_SIZE = 4/, 'MCP registry search should page results four at a time')
assert.match(panelSource, /setRegistryResults\(\[\]\)/, 'MCP registry search should clear stale results before a new search') assert.match(panelSource, /setRegistryResults\(\[\]\)/, 'MCP registry search should clear stale results before a new search')
assert.match(panelSource, /pagedRegistryResults/, 'MCP registry search should render paged results instead of the full result set') assert.match(panelSource, /pagedRegistryResults/, 'MCP registry search should render paged results instead of the full result set')
@@ -146,6 +181,8 @@ assert.match(panelSource, /Preconfigured Servers/, 'MCP page should label catalo
assert.match(panelSource, /aria-expanded=\{catalogOpen\}/, 'MCP preconfigured servers should render as an accordion') assert.match(panelSource, /aria-expanded=\{catalogOpen\}/, 'MCP preconfigured servers should render as an accordion')
assert.match(panelSource, /aria-expanded=\{customOpen\}/, 'MCP custom server form should render as an accordion') assert.match(panelSource, /aria-expanded=\{customOpen\}/, 'MCP custom server form should render as an accordion')
assert.match(panelSource, /MCP Security/, 'MCP page must expose sandbox access controls') assert.match(panelSource, /MCP Security/, 'MCP page must expose sandbox access controls')
assert.match(panelSource, /openSecurityServers/, 'MCP security must render installed servers as sub accordions')
assert.match(panelSource, /aria-expanded=\{securityOpen\}/, 'MCP security must render as an accordion')
assert.match(panelSource, /Allow All/, 'MCP security must support allow-all access') assert.match(panelSource, /Allow All/, 'MCP security must support allow-all access')
assert.match(panelSource, /Allow Only/, 'MCP security must support allow-list access') assert.match(panelSource, /Allow Only/, 'MCP security must support allow-list access')
assert.match(panelSource, /syncSandboxBrokerConfig/, 'MCP configuration grants must sync the sandbox broker config automatically') assert.match(panelSource, /syncSandboxBrokerConfig/, 'MCP configuration grants must sync the sandbox broker config automatically')