Simplify MCP server install wizard

This commit is contained in:
Codex
2026-04-29 16:37:38 +00:00
parent 2dda1b8bee
commit f92268181b
3 changed files with 215 additions and 56 deletions
+157 -23
View File
@@ -1,6 +1,6 @@
import { NextResponse } from "next/server"
import { execFile } from "node:child_process"
import { access, mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises"
import { access, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises"
import os from "node:os"
import path from "node:path"
import { promisify } from "node:util"
@@ -45,8 +45,8 @@ function parseEnv(value: unknown) {
}
function normalizeEntryMode(value: unknown) {
const mode = String(value || "file").trim()
return ENTRY_MODES.has(mode) ? mode : "file"
const mode = String(value || "").trim()
return ENTRY_MODES.has(mode) ? mode : ""
}
function normalizeUploadMode(value: unknown) {
@@ -115,6 +115,28 @@ async function findFileByName(root: string, fileName: string): Promise<string |
return null
}
async function findFirstExistingFile(root: string, candidates: string[]) {
for (const candidate of candidates) {
const fullPath = path.join(root, candidate)
if (await pathExists(fullPath)) return fullPath
}
return null
}
async function findLikelySourceFile(root: string, extension: RegExp): Promise<string | null> {
const entries = await readdir(root, { withFileTypes: true }).catch(() => [])
for (const entry of entries) {
if (entry.name === "node_modules" || entry.name === ".venv" || entry.name === ".git" || entry.name.startsWith(".")) continue
const fullPath = path.join(root, entry.name)
if (entry.isFile() && extension.test(entry.name)) return fullPath
if (entry.isDirectory()) {
const nested = await findLikelySourceFile(fullPath, extension)
if (nested) return nested
}
}
return null
}
async function resolveEntryPath(root: string, entrypoint: string) {
const direct = safeEntryPath(root, entrypoint)
if (await pathExists(direct)) return direct
@@ -151,6 +173,119 @@ async function resolveProjectRoot(root: string, entrypointPath: string | null) {
return await findSingleNestedProjectRoot(root) || root
}
async function readJsonFile(filePath: string) {
const content = await readFile(filePath, "utf8").catch(() => "")
if (!content) return null
try {
return JSON.parse(content) as Record<string, any>
} catch {
return null
}
}
async function inferPythonConsoleScript(projectRoot: string) {
const pyproject = await readFile(path.join(projectRoot, "pyproject.toml"), "utf8").catch(() => "")
const projectScripts = pyproject.match(/\[project\.scripts\]([\s\S]*?)(?:\n\[|$)/)
const scriptLine = projectScripts?.[1]?.split(/\r?\n/).find((line) => /^[A-Za-z0-9_.-]+\s*=/.test(line.trim()))
return scriptLine?.split("=")[0]?.trim() || ""
}
async function inferUploadLaunch(root: string, runtime: string, entryMode: string, entrypoint: string) {
if (runtime && entryMode && entrypoint) {
const entrypointPath = entryMode === "file" ? await resolveEntryPath(root, entrypoint) : null
const projectRoot = await resolveProjectRoot(root, entrypointPath)
return { runtime, entryMode, entrypoint, entrypointPath, projectRoot }
}
const projectRoot = await resolveProjectRoot(root, null)
if (entryMode && entrypoint) {
const resolvedRuntime = runtime || (entryMode === "python-module" ? "python3" : "node")
const entrypointPath = entryMode === "file" ? await resolveEntryPath(root, entrypoint) : null
return { runtime: resolvedRuntime, entryMode, entrypoint, entrypointPath, projectRoot: await resolveProjectRoot(root, entrypointPath) }
}
const packageJsonPath = path.join(projectRoot, "package.json")
if (await pathExists(packageJsonPath)) {
const packageJson = await readJsonFile(packageJsonPath)
const bin = typeof packageJson?.bin === "string"
? packageJson.bin
: packageJson?.bin && typeof packageJson.bin === "object"
? Object.values(packageJson.bin).find((value) => typeof value === "string") as string | undefined
: ""
const main = typeof packageJson?.main === "string" ? packageJson.main : ""
const nodeEntry = await findFirstExistingFile(projectRoot, [
entrypoint,
main,
bin || "",
"server.js",
"server.mjs",
"index.js",
"index.mjs",
"src/server.js",
"src/server.mjs",
"src/index.js",
"src/index.mjs",
"dist/server.js",
"dist/index.js",
"build/server.js",
"build/index.js",
].filter(Boolean))
|| await findLikelySourceFile(projectRoot, /\.(mjs|cjs|js)$/i)
if (!nodeEntry) throw new Error("could not detect a Node MCP server entrypoint")
return {
runtime: runtime || "node",
entryMode: "file",
entrypoint: path.relative(root, nodeEntry).replace(/\\/g, "/"),
entrypointPath: nodeEntry,
projectRoot,
}
}
if (await pathExists(path.join(projectRoot, "pyproject.toml")) || await pathExists(path.join(projectRoot, "requirements.txt"))) {
const consoleScript = entryMode === "console-script" ? entrypoint : await inferPythonConsoleScript(projectRoot)
if (consoleScript) {
return {
runtime: runtime || "python3",
entryMode: "console-script",
entrypoint: consoleScript,
entrypointPath: null,
projectRoot,
}
}
const pythonEntry = await findFirstExistingFile(projectRoot, [
entrypoint,
"server.py",
"main.py",
"mcp_server.py",
"src/server.py",
"src/main.py",
].filter(Boolean))
|| await findLikelySourceFile(projectRoot, /\.py$/i)
if (!pythonEntry) throw new Error("could not detect a Python MCP server entrypoint")
return {
runtime: runtime || "python3",
entryMode: "file",
entrypoint: path.relative(root, pythonEntry).replace(/\\/g, "/"),
entrypointPath: pythonEntry,
projectRoot: await resolveProjectRoot(root, pythonEntry),
}
}
const genericEntry = entrypoint
? await resolveEntryPath(root, entrypoint).catch(() => null)
: await findFirstExistingFile(root, ["server.py", "main.py", "server.js", "index.js"])
|| await findLikelySourceFile(root, /\.(py|mjs|cjs|js)$/i)
if (!genericEntry) throw new Error("could not detect an MCP server entrypoint")
const inferredRuntime = runtime || (/\.py$/i.test(genericEntry) ? "python3" : "node")
return {
runtime: inferredRuntime,
entryMode: "file",
entrypoint: path.relative(root, genericEntry).replace(/\\/g, "/"),
entrypointPath: genericEntry,
projectRoot: await resolveProjectRoot(root, genericEntry),
}
}
async function runInstallCommand(command: string, args: string[], cwd: string) {
try {
const { stdout, stderr } = await execFileAsync(command, args, {
@@ -276,10 +411,9 @@ async function buildUploadCandidate({
args: string[]
env: Record<string, string>
}) {
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 inferred = await inferUploadLaunch(root, runtime, entryMode, entrypoint)
const bootstrap = await bootstrapUploadedServer(inferred.projectRoot, inferred.runtime, inferred.entrypoint)
const launch = await launchCommandForUpload(inferred.projectRoot, bootstrap, inferred.entryMode, inferred.entrypoint, inferred.entrypointPath, args)
const candidate = {
id,
name,
@@ -303,7 +437,7 @@ async function buildUploadCandidate({
source: "custom"
enabled: boolean
}
return { candidate, projectRoot, bootstrap }
return { candidate, projectRoot: inferred.projectRoot, bootstrap, inferred }
}
function installCandidateFrom(candidate: Awaited<ReturnType<typeof buildUploadCandidate>>["candidate"]): McpServerInstall {
@@ -371,19 +505,16 @@ export async function POST(request: Request) {
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()
const runtime = String(form.get("runtime") || "python3").trim()
const entrypoint = String(form.get("entrypoint") || "server.py").trim()
const runtime = String(form.get("runtime") || "").trim()
const entrypoint = String(form.get("entrypoint") || "").trim()
const entryMode = normalizeEntryMode(form.get("entryMode"))
const sandboxId = String(form.get("sandboxId") || "").trim()
const repairEnabled = String(form.get("repair") || "true") !== "false"
const root = path.join(UPLOAD_DIR, id)
if (!runtime) throw new Error("runtime command is required")
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({
const built = await buildUploadCandidate({
root,
id,
name,
@@ -394,6 +525,10 @@ export async function POST(request: Request) {
args: parseLines(form.get("args")),
env: parseEnv(form.get("env")),
})
const projectRoot = built.projectRoot
const bootstrap = built.bootstrap
const inferred = built.inferred
const initialCandidate = built.candidate
let candidate = initialCandidate
if (mode === "preflight") {
@@ -441,9 +576,9 @@ export async function POST(request: Request) {
id,
name,
summary,
runtime,
entryMode,
entrypoint,
runtime: inferred.runtime,
entryMode: inferred.entryMode,
entrypoint: inferred.entrypoint,
uploadRoot: root,
projectRoot,
},
@@ -493,19 +628,18 @@ export async function POST(request: Request) {
if (!uploadedDirectory && !uploadedArchive) throw new Error("choose a directory, .zip, .tgz, .tar.gz, or .tar server upload")
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)
const inferred = await inferUploadLaunch(root, runtime, entryMode, entrypoint)
return NextResponse.json({
ok: true,
stagedUpload: {
id,
name,
summary,
runtime,
entryMode,
entrypoint,
runtime: inferred.runtime,
entryMode: inferred.entryMode,
entrypoint: inferred.entrypoint,
uploadRoot: root,
projectRoot,
projectRoot: inferred.projectRoot,
selectedBundle: uploadedArchive ? "archive" : "directory",
},
})
+49 -29
View File
@@ -154,6 +154,13 @@ function envToText(value: Record<string, string>) {
.join("\n")
}
const DEFAULT_CUSTOM_NAME = "custom-tools"
const DEFAULT_CUSTOM_SUMMARY = "Custom MCP server"
const DEFAULT_CUSTOM_ARGS = "-y\n@modelcontextprotocol/server-memory"
const DEFAULT_UPLOAD_RUNTIME = ""
const DEFAULT_UPLOAD_ENTRY_MODE: "file" | "python-module" | "console-script" = "file"
const DEFAULT_UPLOAD_ENTRYPOINT = ""
export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurationPanelProps) {
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
@@ -161,18 +168,18 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
const [catalog, setCatalog] = useState<McpCatalogEntry[]>([])
const [servers, setServers] = useState<McpServerInstall[]>([])
const [config, setConfig] = useState<Record<string, unknown>>({ mcpServers: {} })
const [customName, setCustomName] = useState("custom-tools")
const [customSummary, setCustomSummary] = useState("Custom MCP server")
const [customName, setCustomName] = useState(DEFAULT_CUSTOM_NAME)
const [customSummary, setCustomSummary] = useState(DEFAULT_CUSTOM_SUMMARY)
const [customTransport, setCustomTransport] = useState<McpTransport>("stdio")
const [customCommand, setCustomCommand] = useState("npx")
const [customArgs, setCustomArgs] = useState("-y\n@modelcontextprotocol/server-memory")
const [customArgs, setCustomArgs] = useState(DEFAULT_CUSTOM_ARGS)
const [customEnv, setCustomEnv] = useState("")
const [uploadFiles, setUploadFiles] = useState<File[]>([])
const [uploadPaths, setUploadPaths] = useState<string[]>([])
const [uploadArchive, setUploadArchive] = useState<File | null>(null)
const [uploadRuntime, setUploadRuntime] = useState("python3")
const [uploadEntryMode, setUploadEntryMode] = useState<"file" | "python-module" | "console-script">("file")
const [uploadEntrypoint, setUploadEntrypoint] = useState("server.py")
const [uploadRuntime, setUploadRuntime] = useState(DEFAULT_UPLOAD_RUNTIME)
const [uploadEntryMode, setUploadEntryMode] = useState<"file" | "python-module" | "console-script">(DEFAULT_UPLOAD_ENTRY_MODE)
const [uploadEntrypoint, setUploadEntrypoint] = useState(DEFAULT_UPLOAD_ENTRYPOINT)
const [uploadRepair, setUploadRepair] = useState(true)
const [repairSandboxId, setRepairSandboxId] = useState("")
const [stagedUpload, setStagedUpload] = useState<StagedMcpUpload | null>(null)
@@ -546,6 +553,28 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
setWizardInstallResult(null)
}
function resetWizardWorkflow() {
setCustomName(DEFAULT_CUSTOM_NAME)
setCustomSummary(DEFAULT_CUSTOM_SUMMARY)
setCustomArgs(DEFAULT_CUSTOM_ARGS)
setCustomEnv("")
setUploadRuntime(DEFAULT_UPLOAD_RUNTIME)
setUploadEntryMode(DEFAULT_UPLOAD_ENTRY_MODE)
setUploadEntrypoint(DEFAULT_UPLOAD_ENTRYPOINT)
setRepairSandboxId("")
setUploadRepair(true)
setUploadFiles([])
setUploadPaths([])
setUploadArchive(null)
resetWizardPreflightState()
setWizardStep("upload")
}
function cancelWizardWorkflow() {
resetWizardWorkflow()
setMessage("MCP server install canceled.")
}
function summarizePreflight(preflight: McpPreflightResult) {
if (preflight.ok) {
return `${preflight.diagnosis.summary}${preflight.tools.length > 0 ? ` Tools: ${preflight.tools.join(", ")}.` : ""}`
@@ -592,9 +621,6 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
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")
@@ -623,6 +649,9 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
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)
setUploadRuntime(data.stagedUpload.runtime)
setUploadEntryMode(data.stagedUpload.entryMode)
setUploadEntrypoint(data.stagedUpload.entrypoint)
setWizardPreflight(null)
setWizardRepair(null)
setWizardCandidate(null)
@@ -659,6 +688,11 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
}
if (!response.ok || !data.preflight || !data.candidate) throw new Error(data.error || "Failed to preflight MCP server")
setStagedUpload(data.stagedUpload || stagedUpload)
if (data.stagedUpload) {
setUploadRuntime(data.stagedUpload.runtime)
setUploadEntryMode(data.stagedUpload.entryMode)
setUploadEntrypoint(data.stagedUpload.entrypoint)
}
setWizardCandidate(data.candidate)
setWizardDependencyInstall(data.dependencyInstall || null)
setWizardPreflight(data.preflight)
@@ -697,10 +731,8 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
if (wizardPreflight) {
setPreflightResults((current) => ({ ...current, [data.server!.id]: wizardPreflight }))
}
setUploadFiles([])
setUploadPaths([])
setUploadArchive(null)
setMessage(`${data.server.name} installed${data.server.enabled ? "." : " disabled because preflight did not pass."}`)
resetWizardWorkflow()
} catch (error) {
setMessage(error instanceof Error ? error.message : "Failed to install staged MCP server")
} finally {
@@ -1104,22 +1136,6 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
<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); resetWizardPreflightState() }} 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>Upload Runtime</FieldLabel><FieldHint>Runtime used to bootstrap uploaded bundles before preflight.</FieldHint></div>
<input value={uploadRuntime} onChange={(event) => { setUploadRuntime(event.target.value); resetWizardPreflightState() }} placeholder="python3, node, uv, uvx" className="field-control w-full px-3 py-2 text-sm font-mono" />
</div>
<div className="space-y-2">
<div className="flex items-center gap-2"><FieldLabel>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"); resetWizardPreflightState() }} className="field-control w-full px-3 py-2 text-sm font-mono">
<option value="file">File</option>
<option value="python-module">Python module</option>
<option value="console-script">Console script</option>
</select>
</div>
<div className="space-y-2 md:col-span-2">
<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); resetWizardPreflightState() }} placeholder={uploadEntryMode === "python-module" ? "isaac_mcp_poc.server" : uploadEntryMode === "console-script" ? "isaac-mcp-poc" : "server.py, src/server.py, index.js"} className="field-control w-full px-3 py-2 text-sm font-mono" />
</div>
<div className="flex flex-wrap items-center gap-3 md:col-span-2">
<label className="action-button cursor-pointer px-4 py-2">
Choose Directory
@@ -1137,7 +1153,10 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
</div>
{stagedUpload && (
<div className="rounded-sm border border-[var(--status-running)] bg-[var(--status-running-bg)] p-3 text-xs text-[var(--status-running)] md:col-span-2">
Uploaded to staged server workspace: {stagedUpload.name}
<div>Uploaded to staged server workspace: {stagedUpload.name}</div>
<div className="mt-2 font-mono text-[11px]">
Detected {stagedUpload.runtime} / {stagedUpload.entryMode} / {stagedUpload.entrypoint}
</div>
</div>
)}
</div>
@@ -1234,6 +1253,7 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
)}
<div className="mt-5 flex flex-wrap items-center gap-3">
<button onClick={cancelWizardWorkflow} disabled={saving || (!hasUploadBundle && !stagedUpload && !wizardPreflight && !wizardCandidate)} className="action-button px-4 py-2">Cancel</button>
<button onClick={previousWizardStep} disabled={saving || wizardStepIndex === 0} className="action-button px-4 py-2">Back</button>
<button onClick={handleWizardNext} disabled={saving || wizardStepIndex === WIZARD_STEPS.length - 1 || (wizardStep === "upload" && !hasUploadBundle && !stagedUpload)} className="action-button px-4 py-2">Next</button>
</div>