Add MCP registry wizard preflight flow

This commit is contained in:
Codex
2026-04-29 15:32:28 +00:00
parent 42561a7eff
commit ce4303a602
8 changed files with 955 additions and 223 deletions
+67
View File
@@ -0,0 +1,67 @@
import { NextResponse } from "next/server"
const REQUEST_TIMEOUT_MS = Number.parseInt(process.env.MCP_REGISTRY_ASSIST_TIMEOUT_MS || "45000", 10)
const MODEL = process.env.MCP_PREFLIGHT_LLM_MODEL || process.env.OPENAI_MODEL || "gpt-4o-mini"
const BASE_URL = (process.env.MCP_PREFLIGHT_LLM_BASE_URL || process.env.OPENAI_BASE_URL || process.env.VLLM_BASE_URL || "http://localhost:8000/v1").replace(/\/+$/, "")
function extractJsonObject(value: string) {
const trimmed = value.trim()
if (trimmed.startsWith("{")) return trimmed
const match = trimmed.match(/\{[\s\S]*\}/)
if (!match) throw new Error("registry assistant did not return JSON")
return match[0]
}
export async function POST(request: Request) {
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)
try {
const body = await request.json().catch(() => ({}))
const prompt = typeof body?.prompt === "string" ? body.prompt.trim() : ""
if (!prompt) throw new Error("registry prompt is required")
const response = await fetch(`${BASE_URL}/chat/completions`, {
method: "POST",
signal: controller.signal,
headers: {
"Content-Type": "application/json",
...(process.env.MCP_PREFLIGHT_LLM_API_KEY || process.env.OPENAI_API_KEY
? { Authorization: `Bearer ${process.env.MCP_PREFLIGHT_LLM_API_KEY || process.env.OPENAI_API_KEY}` }
: {}),
},
body: JSON.stringify({
model: MODEL,
temperature: 0.1,
response_format: { type: "json_object" },
messages: [
{
role: "system",
content: "Convert a user's MCP registry description into JSON with name, baseUrl, and description. The baseUrl must be the registry origin/root, not the /v0/servers path. Return only JSON.",
},
{
role: "user",
content: prompt,
},
],
}),
})
const data = await response.json().catch(() => null)
if (!response.ok) throw new Error(data?.error?.message || data?.error || `registry assistant failed (${response.status})`)
const content = data?.choices?.[0]?.message?.content
if (typeof content !== "string" || !content.trim()) throw new Error("registry assistant returned an empty response")
const suggestion = JSON.parse(extractJsonObject(content))
return NextResponse.json({
suggestion: {
name: typeof suggestion?.name === "string" ? suggestion.name : "",
baseUrl: typeof suggestion?.baseUrl === "string" ? suggestion.baseUrl : "",
description: typeof suggestion?.description === "string" ? suggestion.description : "",
},
model: MODEL,
})
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to assist registry setup"
return NextResponse.json({ error: message }, { status: /required/.test(message) ? 400 : 502 })
} finally {
clearTimeout(timeout)
}
}
+34
View File
@@ -0,0 +1,34 @@
import { NextResponse } from "next/server"
import { deleteMcpRegistry, listMcpRegistries, saveMcpRegistry } from "@/app/lib/mcpRegistryStore"
export async function GET() {
try {
return NextResponse.json({ registries: await listMcpRegistries() })
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to load MCP registries"
return NextResponse.json({ error: message }, { status: 500 })
}
}
export async function POST(request: Request) {
try {
const body = await request.json().catch(() => ({}))
const action = typeof body?.action === "string" ? body.action : "save"
if (action === "delete") {
const registryId = typeof body?.registryId === "string" ? body.registryId : ""
return NextResponse.json({ deleted: await deleteMcpRegistry(registryId), registries: await listMcpRegistries() })
}
const registry = await saveMcpRegistry({
id: body?.id,
name: body?.name,
baseUrl: body?.baseUrl,
description: body?.description,
})
return NextResponse.json({ registry, registries: await listMcpRegistries() })
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to update MCP registries"
return NextResponse.json({ error: message }, { status: /required|URL|delete/.test(message) ? 400 : 500 })
}
}
+3 -2
View File
@@ -1,7 +1,7 @@
import { NextResponse } from "next/server"
import type { McpCatalogEntry } from "@/app/lib/mcpServerStore"
const REGISTRY_BASE_URL = process.env.MCP_REGISTRY_BASE_URL || "https://registry.modelcontextprotocol.io"
const DEFAULT_REGISTRY_BASE_URL = process.env.MCP_REGISTRY_BASE_URL || "https://registry.modelcontextprotocol.io"
type RegistryArgument = {
value?: string
@@ -126,7 +126,8 @@ export async function GET(request: Request) {
const requestUrl = new URL(request.url)
const search = requestUrl.searchParams.get("search") || requestUrl.searchParams.get("q") || ""
const limit = Math.max(1, Math.min(Number.parseInt(requestUrl.searchParams.get("limit") || "12", 10) || 12, 30))
const registryUrl = new URL("/v0/servers", REGISTRY_BASE_URL)
const baseUrl = requestUrl.searchParams.get("baseUrl") || DEFAULT_REGISTRY_BASE_URL
const registryUrl = new URL("/v0/servers", baseUrl)
registryUrl.searchParams.set("limit", String(limit))
registryUrl.searchParams.set("is_latest", "true")
if (search.trim()) registryUrl.searchParams.set("search", search.trim())
+46 -4
View File
@@ -5,7 +5,8 @@ import os from "node:os"
import path from "node:path"
import { promisify } from "node:util"
import { preflightMcpServer } from "@/app/lib/mcpPreflight"
import { installMcpServer, listMcpServers } from "@/app/lib/mcpServerStore"
import { repairUploadedMcpServerWithLlm, type McpPreflightRepairResult } from "@/app/lib/mcpPreflightRepair"
import { installMcpServer, listMcpServers, type McpServerInstall } from "@/app/lib/mcpServerStore"
const execFileAsync = promisify(execFile)
const HOME = process.env.HOME || "/tmp"
@@ -295,6 +296,8 @@ export async function POST(request: Request) {
const runtime = String(form.get("runtime") || "python3").trim()
const entrypoint = String(form.get("entrypoint") || "server.py").trim()
const entryMode = normalizeEntryMode(form.get("entryMode"))
const sandboxId = String(form.get("sandboxId") || "").trim()
const repairEnabled = String(form.get("repair") || "true") !== "false"
const root = path.join(UPLOAD_DIR, id)
if (!runtime) throw new Error("runtime command is required")
@@ -311,7 +314,7 @@ export async function POST(request: Request) {
const projectRoot = await resolveProjectRoot(root, entrypointPath)
const bootstrap = await bootstrapUploadedServer(projectRoot, runtime, entrypoint)
const launch = await launchCommandForUpload(projectRoot, bootstrap, entryMode, entrypoint, entrypointPath, parseLines(form.get("args")))
const candidate = {
let candidate = {
id,
name,
summary,
@@ -322,7 +325,7 @@ export async function POST(request: Request) {
tags: ["uploaded", "custom"],
source: "custom",
enabled: true,
} as const satisfies {
} satisfies {
id: string
name: string
summary: string
@@ -334,13 +337,51 @@ export async function POST(request: Request) {
source: "custom"
enabled: boolean
}
const preflight = await preflightMcpServer({
const installCandidate = (): McpServerInstall => ({
...candidate,
installedAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
accessMode: "disabled",
allowedSandboxIds: [],
})
let preflight = await preflightMcpServer(installCandidate())
let repair: McpPreflightRepairResult | null = null
if (!preflight.ok && repairEnabled) {
try {
repair = await repairUploadedMcpServerWithLlm({
uploadRoot: root,
projectRoot,
server: installCandidate(),
preflight,
dependencyLogs: bootstrap.logs,
sandboxId: sandboxId || null,
})
if (repair.updatedServer) {
candidate = {
...candidate,
command: repair.updatedServer.command,
args: repair.updatedServer.args,
env: repair.updatedServer.env,
}
}
if (repair.ok) {
preflight = await preflightMcpServer(installCandidate())
}
} catch (error) {
repair = {
attempted: true,
ok: false,
provider: "openai-compatible",
model: process.env.MCP_PREFLIGHT_LLM_MODEL || process.env.OPENAI_MODEL || "",
baseUrl: process.env.MCP_PREFLIGHT_LLM_BASE_URL || process.env.OPENAI_BASE_URL || process.env.VLLM_BASE_URL || "",
summary: "LLM-assisted repair could not complete.",
changes: [],
error: error instanceof Error ? error.message : "MCP repair failed",
}
}
}
const server = await installMcpServer({
...candidate,
enabled: preflight.ok,
@@ -357,6 +398,7 @@ export async function POST(request: Request) {
logs: bootstrap.logs,
},
preflight,
repair,
...(await listMcpServers()),
})
} catch (error) {