From aa312a10d0eac3a5c3a70f2b2f2aaf733d6aab0e Mon Sep 17 00:00:00 2001 From: Codex Date: Wed, 29 Apr 2026 15:44:44 +0000 Subject: [PATCH] Complete MCP install wizard --- app/api/mcp/install-assist/route.ts | 99 ++++++++ app/components/McpConfigurationPanel.tsx | 301 ++++++++++++++++------- tests/mcp-configuration-page-check.mjs | 14 +- 3 files changed, 318 insertions(+), 96 deletions(-) create mode 100644 app/api/mcp/install-assist/route.ts diff --git a/app/api/mcp/install-assist/route.ts b/app/api/mcp/install-assist/route.ts new file mode 100644 index 0000000..674e50c --- /dev/null +++ b/app/api/mcp/install-assist/route.ts @@ -0,0 +1,99 @@ +import { NextResponse } from "next/server" + +const REQUEST_TIMEOUT_MS = Number.parseInt(process.env.MCP_INSTALL_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("install assistant did not return JSON") + return match[0] +} + +function stringArray(value: unknown) { + return Array.isArray(value) + ? value.map((item) => String(item ?? "").trim()).filter(Boolean) + : [] +} + +function stringMap(value: unknown) { + if (!value || typeof value !== "object" || Array.isArray(value)) return {} + return Object.fromEntries( + Object.entries(value) + .map(([key, item]) => [key.trim(), String(item ?? "").trim()]) + .filter(([key]) => Boolean(key)), + ) +} + +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("install 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: [ + "You draft install metadata for Model Context Protocol servers.", + "Return only JSON with name, summary, transport, command, args, env, uploadRuntime, uploadEntryMode, uploadEntrypoint, and notes.", + "Use transport stdio for local commands and http for streamable HTTP endpoints.", + "Args must be an array of strings; env must be an object.", + "If the user describes an uploaded bundle, set upload fields but still provide the most likely runtime and entrypoint.", + ].join(" "), + }, + { + role: "user", + content: JSON.stringify({ + prompt, + current: body?.current || {}, + }), + }, + ], + }), + }) + const data = await response.json().catch(() => null) + if (!response.ok) throw new Error(data?.error?.message || data?.error || `install assistant failed (${response.status})`) + const content = data?.choices?.[0]?.message?.content + if (typeof content !== "string" || !content.trim()) throw new Error("install assistant returned an empty response") + const suggestion = JSON.parse(extractJsonObject(content)) + + return NextResponse.json({ + suggestion: { + name: typeof suggestion?.name === "string" ? suggestion.name : "", + summary: typeof suggestion?.summary === "string" ? suggestion.summary : "", + transport: suggestion?.transport === "http" ? "http" : "stdio", + command: typeof suggestion?.command === "string" ? suggestion.command : "", + args: stringArray(suggestion?.args), + env: stringMap(suggestion?.env), + uploadRuntime: typeof suggestion?.uploadRuntime === "string" ? suggestion.uploadRuntime : "", + uploadEntryMode: ["file", "python-module", "console-script"].includes(suggestion?.uploadEntryMode) ? suggestion.uploadEntryMode : "", + uploadEntrypoint: typeof suggestion?.uploadEntrypoint === "string" ? suggestion.uploadEntrypoint : "", + notes: typeof suggestion?.notes === "string" ? suggestion.notes : "", + }, + model: MODEL, + }) + } catch (error) { + const message = error instanceof Error ? error.message : "Failed to assist MCP install" + return NextResponse.json({ error: message }, { status: /required/.test(message) ? 400 : 502 }) + } finally { + clearTimeout(timeout) + } +} diff --git a/app/components/McpConfigurationPanel.tsx b/app/components/McpConfigurationPanel.tsx index 6a68f64..7c2e707 100644 --- a/app/components/McpConfigurationPanel.tsx +++ b/app/components/McpConfigurationPanel.tsx @@ -70,6 +70,19 @@ type McpPreflightRepairResult = { error?: string } +type McpInstallSuggestion = { + name?: string + summary?: string + transport?: McpTransport + command?: string + args?: string[] + env?: Record + uploadRuntime?: string + uploadEntryMode?: "file" | "python-module" | "console-script" | "" + uploadEntrypoint?: string + notes?: string +} + type McpSandbox = { id: string name: string @@ -81,6 +94,8 @@ type McpConfigurationPanelProps = { } const REGISTRY_PAGE_SIZE = 4 +const WIZARD_STEPS = ["basics", "launch", "upload", "review"] as const +type WizardStep = typeof WIZARD_STEPS[number] function FieldLabel({ children }: { children: React.ReactNode }) { return @@ -115,6 +130,12 @@ function parseEnv(value: string) { ) } +function envToText(value: Record) { + return Object.entries(value) + .map(([key, item]) => `${key}=${item}`) + .join("\n") +} + export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurationPanelProps) { const [loading, setLoading] = useState(true) const [saving, setSaving] = useState(false) @@ -136,6 +157,8 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati const [uploadEntrypoint, setUploadEntrypoint] = useState("server.py") const [uploadRepair, setUploadRepair] = useState(true) const [repairSandboxId, setRepairSandboxId] = useState("") + const [installPrompt, setInstallPrompt] = useState("") + const [installAssistNotes, setInstallAssistNotes] = useState("") const [editingServerId, setEditingServerId] = useState(null) const [editorText, setEditorText] = useState("") const [registrySearch, setRegistrySearch] = useState("github") @@ -155,7 +178,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" | "launch" | "upload" | "review">("basics") + const [wizardStep, setWizardStep] = useState("basics") const installedIds = useMemo(() => new Set(servers.map((server) => server.id)), [servers]) const enabledCount = servers.filter((server) => server.enabled).length @@ -166,6 +189,8 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati (registryPage - 1) * REGISTRY_PAGE_SIZE, registryPage * REGISTRY_PAGE_SIZE, ) + const wizardStepIndex = WIZARD_STEPS.indexOf(wizardStep) + const hasUploadBundle = Boolean(uploadArchive || uploadFiles.length > 0) async function load() { try { @@ -260,6 +285,60 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati } } + function applyInstallSuggestion(suggestion: McpInstallSuggestion) { + if (suggestion.name) setCustomName(suggestion.name) + if (suggestion.summary) setCustomSummary(suggestion.summary) + if (suggestion.transport) setCustomTransport(suggestion.transport) + if (suggestion.command) setCustomCommand(suggestion.command) + if (Array.isArray(suggestion.args)) setCustomArgs(suggestion.args.join("\n")) + if (suggestion.env) setCustomEnv(envToText(suggestion.env)) + if (suggestion.uploadRuntime) setUploadRuntime(suggestion.uploadRuntime) + if (suggestion.uploadEntryMode) setUploadEntryMode(suggestion.uploadEntryMode) + if (suggestion.uploadEntrypoint) setUploadEntrypoint(suggestion.uploadEntrypoint) + if (suggestion.notes) setInstallAssistNotes(suggestion.notes) + } + + async function assistInstall() { + try { + setSaving(true) + const response = await fetch("/api/mcp/install-assist", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + prompt: installPrompt, + current: { + name: customName, + summary: customSummary, + transport: customTransport, + command: customCommand, + args: parseLines(customArgs), + env: parseEnv(customEnv), + uploadRuntime, + uploadEntryMode, + uploadEntrypoint, + }, + }), + }) + const data = await response.json() as { suggestion?: McpInstallSuggestion; error?: string } + if (!response.ok || !data.suggestion) throw new Error(data.error || "Failed to draft MCP install") + applyInstallSuggestion(data.suggestion) + setWizardStep("launch") + setMessage("Install wizard fields drafted from the running LLM endpoint.") + } catch (error) { + setMessage(error instanceof Error ? error.message : "Failed to draft MCP install") + } finally { + setSaving(false) + } + } + + function nextWizardStep() { + setWizardStep(WIZARD_STEPS[Math.min(WIZARD_STEPS.length - 1, wizardStepIndex + 1)]) + } + + function previousWizardStep() { + setWizardStep(WIZARD_STEPS[Math.max(0, wizardStepIndex - 1)]) + } + async function postUpdate(body: Record, success: string) { try { setSaving(true) @@ -892,78 +971,136 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati ))} -
-
-
NameStable display name and default id for this MCP server.
- setCustomName(event.target.value)} className="field-control w-full px-3 py-2 text-sm font-mono" /> + {wizardStep === "basics" && ( +
+
+
Assist InstallDescribe the MCP server and the running LLM endpoint will draft the install fields.
+