diff --git a/app/api/mcp/upload/route.ts b/app/api/mcp/upload/route.ts index 198c9d6..8e6009d 100644 --- a/app/api/mcp/upload/route.ts +++ b/app/api/mcp/upload/route.ts @@ -15,6 +15,7 @@ const UPLOAD_DIR = path.join(STORE_DIR, "mcp-server-uploads") const MAX_UPLOAD_BYTES = Number.parseInt(process.env.MCP_SERVER_UPLOAD_MAX_BYTES || String(128 * 1024 * 1024), 10) const INSTALL_TIMEOUT_MS = Number.parseInt(process.env.MCP_SERVER_DEPENDENCY_INSTALL_TIMEOUT_MS || String(5 * 60 * 1000), 10) const ENTRY_MODES = new Set(["file", "python-module", "console-script"]) +const UPLOAD_MODES = new Set(["stage", "preflight", "install-staged"]) function slugify(value: string) { return value @@ -48,6 +49,11 @@ function normalizeEntryMode(value: unknown) { return ENTRY_MODES.has(mode) ? mode : "file" } +function normalizeUploadMode(value: unknown) { + const mode = String(value || "").trim() + return UPLOAD_MODES.has(mode) ? mode : "" +} + function normalizeRelativePath(value: string) { const normalized = path.posix.normalize(value.replace(/\\/g, "/")).replace(/^\/+/, "") if (!normalized || normalized === "." || normalized.startsWith("../") || normalized.includes("/../")) { @@ -85,6 +91,16 @@ async function pathExists(candidate: string) { } } +async function ensureUploadRoot(id: string) { + const root = path.resolve(UPLOAD_DIR, id) + const uploadRoot = path.resolve(UPLOAD_DIR) + if (root !== uploadRoot && !root.startsWith(`${uploadRoot}${path.sep}`)) { + throw new Error("staged upload id must stay inside the MCP upload directory") + } + if (!await pathExists(root)) throw new Error("staged MCP server upload was not found") + return root +} + async function findFileByName(root: string, fileName: string): Promise { const entries = await readdir(root, { withFileTypes: true }).catch(() => []) for (const entry of entries) { @@ -239,6 +255,67 @@ async function launchCommandForUpload( return { command: bootstrap.command, args: [entrypointPath, ...extraArgs] } } +async function buildUploadCandidate({ + root, + id, + name, + summary, + runtime, + entryMode, + entrypoint, + args, + env, +}: { + root: string + id: string + name: string + summary: string + runtime: string + entryMode: string + entrypoint: string + args: string[] + env: Record +}) { + const entrypointPath = entryMode === "file" ? await resolveEntryPath(root, entrypoint) : null + const projectRoot = await resolveProjectRoot(root, entrypointPath) + const bootstrap = await bootstrapUploadedServer(projectRoot, runtime, entrypoint) + const launch = await launchCommandForUpload(projectRoot, bootstrap, entryMode, entrypoint, entrypointPath, args) + const candidate = { + id, + name, + summary, + transport: "stdio", + command: launch.command, + args: launch.args, + env, + tags: ["uploaded", "custom"], + source: "custom", + enabled: true, + } satisfies { + id: string + name: string + summary: string + transport: "stdio" + command: string + args: string[] + env: Record + tags: string[] + source: "custom" + enabled: boolean + } + return { candidate, projectRoot, bootstrap } +} + +function installCandidateFrom(candidate: Awaited>["candidate"]): McpServerInstall { + return { + ...candidate, + installedAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + accessMode: "disabled", + allowedSandboxIds: [], + } +} + async function writeDirectoryUpload(form: FormData, root: string) { const files = form.getAll("files") const paths = form.getAll("paths").map((item) => String(item || "")) @@ -290,6 +367,7 @@ async function writeArchiveUpload(form: FormData, root: string) { export async function POST(request: Request) { try { const form = await request.formData() + const mode = normalizeUploadMode(form.get("mode")) const name = String(form.get("name") || "uploaded-server").trim() const id = slugify(String(form.get("id") || name)) const summary = String(form.get("summary") || "Uploaded MCP server").trim() @@ -303,6 +381,110 @@ export async function POST(request: Request) { if (!runtime) throw new Error("runtime command is required") if (!entrypoint) throw new Error("entrypoint is required") + if (mode === "preflight" || mode === "install-staged") { + const root = await ensureUploadRoot(id) + const { candidate: initialCandidate, projectRoot, bootstrap } = await buildUploadCandidate({ + root, + id, + name, + summary, + runtime, + entryMode, + entrypoint, + args: parseLines(form.get("args")), + env: parseEnv(form.get("env")), + }) + let candidate = initialCandidate + + if (mode === "preflight") { + let preflight = await preflightMcpServer(installCandidateFrom(candidate)) + let repair: McpPreflightRepairResult | null = null + + if (!preflight.ok && repairEnabled) { + try { + repair = await repairUploadedMcpServerWithLlm({ + uploadRoot: root, + projectRoot, + server: installCandidateFrom(candidate), + 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(installCandidateFrom(candidate)) + } + } catch (error) { + repair = { + attempted: true, + ok: false, + provider: "openai-compatible", + 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", + } + } + } + + return NextResponse.json({ + ok: true, + stagedUpload: { + id, + name, + summary, + runtime, + entryMode, + entrypoint, + uploadRoot: root, + projectRoot, + }, + candidate, + dependencyInstall: { + kind: bootstrap.kind, + logs: bootstrap.logs, + }, + preflight, + repair, + }) + } + + const command = String(form.get("command") || candidate.command).trim() + const commandArgs = parseLines(form.get("commandArgs")) + const suppliedArgs = commandArgs.length > 0 ? commandArgs : candidate.args + const installEnvText = String(form.get("installEnv") || "") + const suppliedEnv = installEnvText ? parseEnv(installEnvText) : candidate.env + const preflightOk = String(form.get("preflightOk") || "true") !== "false" + const server = await installMcpServer({ + ...candidate, + command: command || candidate.command, + args: suppliedArgs, + env: suppliedEnv, + enabled: preflightOk, + tags: preflightOk ? candidate.tags : [...candidate.tags, "preflight-failed"], + }) + + return NextResponse.json({ + ok: true, + server, + uploadRoot: root, + projectRoot, + dependencyInstall: { + kind: bootstrap.kind, + logs: bootstrap.logs, + }, + ...(await listMcpServers()), + }) + } + await rm(root, { recursive: true, force: true }) await mkdir(root, { recursive: true, mode: 0o700 }) @@ -310,41 +492,40 @@ export async function POST(request: Request) { const uploadedArchive = uploadedDirectory ? false : await writeArchiveUpload(form, root) if (!uploadedDirectory && !uploadedArchive) throw new Error("choose a directory, .zip, .tgz, .tar.gz, or .tar server upload") - const entrypointPath = entryMode === "file" ? await resolveEntryPath(root, entrypoint) : null - 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"))) - let candidate = { + if (mode === "stage") { + const entrypointPath = entryMode === "file" ? await resolveEntryPath(root, entrypoint).catch(() => null) : null + const projectRoot = entrypointPath ? await resolveProjectRoot(root, entrypointPath) : await resolveProjectRoot(root, null) + return NextResponse.json({ + ok: true, + stagedUpload: { + id, + name, + summary, + runtime, + entryMode, + entrypoint, + uploadRoot: root, + projectRoot, + selectedBundle: uploadedArchive ? "archive" : "directory", + }, + }) + } + + const built = await buildUploadCandidate({ + root, id, name, summary, - transport: "stdio", - command: launch.command, - args: launch.args, + runtime, + entryMode, + entrypoint, + args: parseLines(form.get("args")), env: parseEnv(form.get("env")), - tags: ["uploaded", "custom"], - source: "custom", - enabled: true, - } satisfies { - id: string - name: string - summary: string - transport: "stdio" - command: string - args: string[] - env: Record - tags: string[] - source: "custom" - enabled: boolean - } - const installCandidate = (): McpServerInstall => ({ - ...candidate, - installedAt: new Date().toISOString(), - updatedAt: new Date().toISOString(), - accessMode: "disabled", - allowedSandboxIds: [], }) - let preflight = await preflightMcpServer(installCandidate()) + let candidate = built.candidate + const projectRoot = built.projectRoot + const bootstrap = built.bootstrap + let preflight = await preflightMcpServer(installCandidateFrom(candidate)) let repair: McpPreflightRepairResult | null = null if (!preflight.ok && repairEnabled) { @@ -352,7 +533,7 @@ export async function POST(request: Request) { repair = await repairUploadedMcpServerWithLlm({ uploadRoot: root, projectRoot, - server: installCandidate(), + server: installCandidateFrom(candidate), preflight, dependencyLogs: bootstrap.logs, sandboxId: sandboxId || null, @@ -366,7 +547,7 @@ export async function POST(request: Request) { } } if (repair.ok) { - preflight = await preflightMcpServer(installCandidate()) + preflight = await preflightMcpServer(installCandidateFrom(candidate)) } } catch (error) { repair = { diff --git a/app/components/McpConfigurationPanel.tsx b/app/components/McpConfigurationPanel.tsx index 7c2e707..222bb07 100644 --- a/app/components/McpConfigurationPanel.tsx +++ b/app/components/McpConfigurationPanel.tsx @@ -83,6 +83,18 @@ type McpInstallSuggestion = { notes?: string } +type StagedMcpUpload = { + id: string + name: string + summary: string + runtime: string + entryMode: "file" | "python-module" | "console-script" + entrypoint: string + uploadRoot: string + projectRoot: string + selectedBundle?: string +} + type McpSandbox = { id: string name: string @@ -94,8 +106,14 @@ type McpConfigurationPanelProps = { } const REGISTRY_PAGE_SIZE = 4 -const WIZARD_STEPS = ["basics", "launch", "upload", "review"] as const +const WIZARD_STEPS = ["upload", "preflight", "review", "install"] as const type WizardStep = typeof WIZARD_STEPS[number] +const WIZARD_STEP_LABELS: Record = { + upload: "Upload Server Files", + preflight: "Preflight Check", + review: "Review", + install: "Install", +} function FieldLabel({ children }: { children: React.ReactNode }) { return @@ -157,6 +175,12 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati const [uploadEntrypoint, setUploadEntrypoint] = useState("server.py") const [uploadRepair, setUploadRepair] = useState(true) const [repairSandboxId, setRepairSandboxId] = useState("") + const [stagedUpload, setStagedUpload] = useState(null) + const [wizardPreflight, setWizardPreflight] = useState(null) + const [wizardRepair, setWizardRepair] = useState(null) + const [wizardCandidate, setWizardCandidate] = useState(null) + const [wizardDependencyInstall, setWizardDependencyInstall] = useState<{ kind?: string; logs?: string[] } | null>(null) + const [wizardInstallResult, setWizardInstallResult] = useState(null) const [installPrompt, setInstallPrompt] = useState("") const [installAssistNotes, setInstallAssistNotes] = useState("") const [editingServerId, setEditingServerId] = useState(null) @@ -178,7 +202,7 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati const [repoOpen, setRepoOpen] = useState(true) const [catalogOpen, setCatalogOpen] = useState(false) const [customOpen, setCustomOpen] = useState(false) - const [wizardStep, setWizardStep] = useState("basics") + const [wizardStep, setWizardStep] = useState("upload") const installedIds = useMemo(() => new Set(servers.map((server) => server.id)), [servers]) const enabledCount = servers.filter((server) => server.enabled).length @@ -322,7 +346,7 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati const data = await response.json() as { suggestion?: McpInstallSuggestion; error?: string } if (!response.ok || !data.suggestion) throw new Error(data.error || "Failed to draft MCP install") applyInstallSuggestion(data.suggestion) - setWizardStep("launch") + setWizardStep("upload") setMessage("Install wizard fields drafted from the running LLM endpoint.") } catch (error) { setMessage(error instanceof Error ? error.message : "Failed to draft MCP install") @@ -501,6 +525,7 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati return withRelativePath.webkitRelativePath || file.name })) if (files.length > 0) setUploadArchive(null) + resetWizardPreflightState() } function chooseUploadArchive(file: File | null) { @@ -509,6 +534,16 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati setUploadFiles([]) setUploadPaths([]) } + resetWizardPreflightState() + } + + function resetWizardPreflightState() { + setStagedUpload(null) + setWizardPreflight(null) + setWizardRepair(null) + setWizardCandidate(null) + setWizardDependencyInstall(null) + setWizardInstallResult(null) } function summarizePreflight(preflight: McpPreflightResult) { @@ -553,24 +588,29 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati } } - async function uploadServer() { + function appendWizardMetadata(form: FormData) { + form.set("id", customName) + form.set("name", customName) + form.set("summary", customSummary) + form.set("runtime", uploadRuntime) + form.set("entryMode", uploadEntryMode) + form.set("entrypoint", uploadEntrypoint) + form.set("args", customArgs) + form.set("env", customEnv) + form.set("repair", uploadRepair ? "true" : "false") + if (repairSandboxId) form.set("sandboxId", repairSandboxId) + } + + async function stageUploadServer() { try { if (!uploadArchive && uploadFiles.length === 0) { setMessage("Choose a server directory or archive before uploading.") - return + return false } setSaving(true) const form = new FormData() - form.set("id", customName) - form.set("name", customName) - form.set("summary", customSummary) - form.set("runtime", uploadRuntime) - form.set("entryMode", uploadEntryMode) - form.set("entrypoint", uploadEntrypoint) - form.set("args", customArgs) - form.set("env", customEnv) - form.set("repair", uploadRepair ? "true" : "false") - if (repairSandboxId) form.set("sandboxId", repairSandboxId) + form.set("mode", "stage") + appendWizardMetadata(form) if (uploadArchive) { form.set("archive", uploadArchive) } else { @@ -580,30 +620,113 @@ 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; repair?: McpPreflightRepairResult; server?: McpServerInstall } - if (!response.ok) throw new Error(data.error || "Failed to upload MCP server") + const data = await response.json() as { stagedUpload?: StagedMcpUpload; error?: string } + if (!response.ok || !data.stagedUpload) throw new Error(data.error || "Failed to upload MCP server files") + setStagedUpload(data.stagedUpload) + setWizardPreflight(null) + setWizardRepair(null) + setWizardCandidate(null) + setWizardDependencyInstall(null) + setWizardInstallResult(null) + setMessage(`${data.stagedUpload.name} files uploaded. Continue to preflight when ready.`) + return true + } catch (error) { + setMessage(error instanceof Error ? error.message : "Failed to upload MCP server files") + return false + } finally { + setSaving(false) + } + } + + async function startWizardPreflightChecks() { + try { + if (!stagedUpload) { + setMessage("Upload server files before starting preflight checks.") + return + } + setSaving(true) + const form = new FormData() + form.set("mode", "preflight") + appendWizardMetadata(form) + const response = await fetch("/api/mcp/upload", { method: "POST", body: form }) + const data = await response.json() as { + stagedUpload?: StagedMcpUpload + candidate?: McpCatalogEntry + dependencyInstall?: { kind?: string; logs?: string[] } + preflight?: McpPreflightResult + repair?: McpPreflightRepairResult + error?: string + } + if (!response.ok || !data.preflight || !data.candidate) throw new Error(data.error || "Failed to preflight MCP server") + setStagedUpload(data.stagedUpload || stagedUpload) + setWizardCandidate(data.candidate) + setWizardDependencyInstall(data.dependencyInstall || null) + setWizardPreflight(data.preflight) + setWizardRepair(data.repair || null) + const installKind = data.dependencyInstall?.kind || "generic" + const installLogCount = data.dependencyInstall?.logs?.filter(Boolean).length || 0 + setMessage(`Preflight ${data.preflight.ok ? "passed" : "found failures"}. ${installKind === "generic" ? "No dependency bootstrap was needed." : `${installKind} dependencies bootstrapped${installLogCount > 0 ? ` with ${installLogCount} install step${installLogCount === 1 ? "" : "s"}` : ""}.`}${summarizeRepair(data.repair)}\n${summarizePreflight(data.preflight)}`) + } catch (error) { + setMessage(error instanceof Error ? error.message : "Failed to preflight MCP server") + } finally { + setSaving(false) + } + } + + async function installStagedUpload() { + try { + if (!stagedUpload || !wizardCandidate) { + setMessage("Run preflight before installing this MCP server.") + return + } + setSaving(true) + const form = new FormData() + form.set("mode", "install-staged") + appendWizardMetadata(form) + form.set("command", wizardCandidate.command) + form.set("commandArgs", wizardCandidate.args.join("\n")) + form.set("installEnv", envToText(wizardCandidate.env)) + form.set("preflightOk", wizardPreflight?.ok ? "true" : "false") + const response = await fetch("/api/mcp/upload", { method: "POST", body: form }) + const data = await response.json() as McpResponse & { server?: McpServerInstall; error?: string } + if (!response.ok || !data.server) throw new Error(data.error || "Failed to install staged MCP server") setCatalog(Array.isArray(data.catalog) ? data.catalog : catalog) setServers(Array.isArray(data.servers) ? data.servers : []) setConfig(data.config || { mcpServers: {} }) - if (data.preflight && data.server?.id) { - setPreflightResults((current) => ({ ...current, [data.server!.id]: data.preflight as McpPreflightResult })) + setWizardInstallResult(data.server) + if (wizardPreflight) { + setPreflightResults((current) => ({ ...current, [data.server!.id]: wizardPreflight })) } setUploadFiles([]) setUploadPaths([]) setUploadArchive(null) - const installKind = data.dependencyInstall?.kind || "generic" - const installLogCount = data.dependencyInstall?.logs?.filter(Boolean).length || 0 - const preflightNote = data.preflight - ? `\nPreflight ${data.preflight.ok ? "passed" : "failed; server saved disabled"}.\n${summarizePreflight(data.preflight)}` - : "" - setMessage(`${customName} uploaded. ${installKind === "generic" ? "No dependency bootstrap was needed." : `${installKind} dependencies bootstrapped${installLogCount > 0 ? ` with ${installLogCount} install step${installLogCount === 1 ? "" : "s"}` : ""}.`}${summarizeRepair(data.repair)}${preflightNote}`) + setMessage(`${data.server.name} installed${data.server.enabled ? "." : " disabled because preflight did not pass."}`) } catch (error) { - setMessage(error instanceof Error ? error.message : "Failed to upload MCP server") + setMessage(error instanceof Error ? error.message : "Failed to install staged MCP server") } finally { setSaving(false) } } + async function handleWizardNext() { + if (wizardStep === "upload") { + const staged = stagedUpload ? true : await stageUploadServer() + if (staged) nextWizardStep() + return + } + if (wizardStep === "preflight") { + if (!wizardPreflight) { + setMessage("Start preflight checks before reviewing this MCP server.") + return + } + nextWizardStep() + return + } + if (wizardStep === "review") { + nextWizardStep() + } + } + function startEditingServer(server: McpServerInstall) { setEditingServerId(server.id) setEditorText(editableServerJson(server)) @@ -960,72 +1083,34 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati {customOpen && (
- {(["basics", "launch", "upload", "review"] as const).map((step) => ( + {WIZARD_STEPS.map((step) => ( ))}
- {wizardStep === "basics" && ( -
-
-
Assist InstallDescribe the MCP server and the running LLM endpoint will draft the install fields.
-