Add MCP broker access controls

This commit is contained in:
Codex
2026-04-26 21:33:23 +00:00
parent db4d8ed7b8
commit faa51e3974
18 changed files with 2838 additions and 73 deletions
+50
View File
@@ -0,0 +1,50 @@
import { NextResponse } from "next/server"
import {
listAllowedBrokerServers,
readBrokerToken,
verifySandboxMcpBrokerToken,
} from "@/app/lib/mcpBrokerStore"
import { callBrokerServerTool } from "@/app/lib/mcpBrokerClient"
export async function POST(request: Request) {
try {
const token = readBrokerToken(request)
const session = token ? await verifySandboxMcpBrokerToken(token) : null
if (!session) {
return NextResponse.json({ ok: false, error: "MCP broker is unavailable for this sandbox." }, { status: 401 })
}
const body = await request.json().catch(() => ({}))
const requestedServerId = typeof body?.serverId === "string" ? body.serverId : ""
const toolName = typeof body?.toolName === "string" ? body.toolName : ""
const toolArguments = body?.arguments && typeof body.arguments === "object" && !Array.isArray(body.arguments)
? body.arguments as Record<string, unknown>
: {}
const allowedServers = await listAllowedBrokerServers(session)
const server = allowedServers.find((candidate) => candidate.id === requestedServerId)
if (!server) {
return NextResponse.json({ ok: false, error: "Requested MCP capability is unavailable." }, { status: 403 })
}
if (!toolName) {
return NextResponse.json({ ok: false, error: "toolName is required." }, { status: 400 })
}
const result = await callBrokerServerTool(server, toolName, toolArguments)
return NextResponse.json({
ok: true,
server: {
id: server.id,
name: server.name,
transport: server.transport,
},
toolName,
result,
})
} catch (error) {
return NextResponse.json({
ok: false,
error: error instanceof Error ? error.message : "MCP broker request failed.",
}, { status: 500 })
}
}
+54
View File
@@ -0,0 +1,54 @@
import { NextResponse } from "next/server"
import {
listAllowedBrokerServers,
readBrokerToken,
verifySandboxMcpBrokerToken,
} from "@/app/lib/mcpBrokerStore"
import { listBrokerServerTools } from "@/app/lib/mcpBrokerClient"
export async function GET(request: Request) {
try {
const token = readBrokerToken(request)
const session = token ? await verifySandboxMcpBrokerToken(token) : null
if (!session) {
return NextResponse.json({ ok: false, error: "MCP broker is unavailable for this sandbox." }, { status: 401 })
}
const allowedServers = await listAllowedBrokerServers(session)
const servers = await Promise.all(allowedServers.map(async (server) => {
try {
const tools = await listBrokerServerTools(server)
return {
id: server.id,
name: server.name,
transport: server.transport,
summary: server.summary,
available: true,
tools,
}
} catch (error) {
return {
id: server.id,
name: server.name,
transport: server.transport,
summary: server.summary,
available: false,
tools: [],
error: error instanceof Error ? error.message : "Failed to inspect MCP server",
}
}
}))
return NextResponse.json({
ok: true,
sandboxId: session.sandboxId,
servers,
})
} catch {
return NextResponse.json({ ok: false, error: "MCP broker is unavailable for this sandbox." }, { status: 500 })
}
}
export async function POST(request: Request) {
return GET(request)
}
+154
View File
@@ -0,0 +1,154 @@
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"
type RegistryArgument = {
value?: string
default?: string
name?: string
}
type RegistryKeyValue = {
name?: string
value?: string
default?: string
placeholder?: string
}
type RegistryPackage = {
registryType?: string
identifier?: string
version?: string
runtimeHint?: string
runtimeArguments?: RegistryArgument[]
packageArguments?: RegistryArgument[]
environmentVariables?: RegistryKeyValue[]
}
type RegistryRemote = {
type?: string
url?: string
headers?: RegistryKeyValue[]
}
type RegistryServer = {
name?: string
title?: string
description?: string
version?: string
repository?: {
url?: string
source?: string
}
packages?: RegistryPackage[]
remotes?: RegistryRemote[]
}
type RegistryEntry = {
server?: RegistryServer
}
function slugify(value: string) {
return value
.trim()
.toLowerCase()
.replace(/[^a-z0-9-]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 64)
}
function argumentValues(args?: RegistryArgument[] | null) {
return (args || [])
.map((arg) => arg.value || arg.default || "")
.filter(Boolean)
}
function keyValueMap(values?: RegistryKeyValue[] | null) {
return Object.fromEntries(
(values || [])
.map((item) => [item.name || "", item.value || item.default || item.placeholder || ""])
.filter(([name]) => Boolean(name)),
)
}
function packageInstall(server: RegistryServer, pkg: RegistryPackage): McpCatalogEntry | null {
if (!pkg.identifier) return null
const runtime = pkg.runtimeHint?.trim()
const registryType = pkg.registryType?.toLowerCase()
const command = runtime || (registryType === "pypi" ? "uvx" : registryType === "npm" ? "npx" : "")
if (!command) return null
const args = [
...argumentValues(pkg.runtimeArguments),
...(command === "npx" ? ["-y"] : []),
pkg.identifier,
...argumentValues(pkg.packageArguments),
]
return {
id: slugify(server.name || pkg.identifier),
name: server.title || server.name || pkg.identifier,
summary: server.description || `Install ${pkg.identifier} from the MCP registry.`,
transport: "stdio",
command,
args,
env: keyValueMap(pkg.environmentVariables),
tags: ["registry", registryType || "package", server.version || ""].filter(Boolean),
}
}
function remoteInstall(server: RegistryServer, remote: RegistryRemote): McpCatalogEntry | null {
if (!remote.url) return null
return {
id: slugify(server.name || remote.url),
name: server.title || server.name || remote.url,
summary: server.description || `Connect to ${remote.url}.`,
transport: "http",
command: remote.url,
args: [],
env: keyValueMap(remote.headers),
tags: ["registry", remote.type || "remote", server.version || ""].filter(Boolean),
}
}
function normalizeRegistryEntry(entry: RegistryEntry): McpCatalogEntry | null {
const server = entry.server
if (!server) return null
const packageCandidate = server.packages?.map((pkg) => packageInstall(server, pkg)).find(Boolean)
if (packageCandidate) return packageCandidate
return server.remotes?.map((remote) => remoteInstall(server, remote)).find(Boolean) || null
}
export async function GET(request: Request) {
try {
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)
registryUrl.searchParams.set("limit", String(limit))
registryUrl.searchParams.set("is_latest", "true")
if (search.trim()) registryUrl.searchParams.set("search", search.trim())
const response = await fetch(registryUrl, {
headers: { Accept: "application/json" },
next: { revalidate: 60 },
})
const data = await response.json()
if (!response.ok) throw new Error(data?.detail || data?.error || "MCP registry request failed")
const results = Array.isArray(data?.servers)
? data.servers.map(normalizeRegistryEntry).filter(Boolean)
: []
return NextResponse.json({
registryUrl: registryUrl.toString(),
results,
metadata: data?.metadata || null,
})
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to search MCP registry"
return NextResponse.json({ error: message }, { status: 502 })
}
}
+70
View File
@@ -0,0 +1,70 @@
import { NextResponse } from "next/server"
import {
installMcpServer,
listMcpServers,
setMcpServerEnabled,
updateMcpServerAccess,
uninstallMcpServer,
} from "@/app/lib/mcpServerStore"
export async function GET() {
try {
return NextResponse.json(await listMcpServers())
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to load MCP servers"
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 : "install"
if (action === "uninstall") {
const serverId = typeof body?.serverId === "string" ? body.serverId : ""
return NextResponse.json({ server: await uninstallMcpServer(serverId), ...(await listMcpServers()) })
}
if (action === "enable" || action === "disable") {
const serverId = typeof body?.serverId === "string" ? body.serverId : ""
return NextResponse.json({
server: await setMcpServerEnabled(serverId, action === "enable"),
...(await listMcpServers()),
})
}
if (action === "update-access") {
const serverId = typeof body?.serverId === "string" ? body.serverId : ""
return NextResponse.json({
server: await updateMcpServerAccess(serverId, {
enabled: typeof body?.enabled === "boolean" ? body.enabled : undefined,
accessMode: body?.accessMode,
allowedSandboxIds: Array.isArray(body?.allowedSandboxIds) ? body.allowedSandboxIds : undefined,
}),
...(await listMcpServers()),
})
}
const server = await installMcpServer({
id: body?.id,
name: body?.name,
summary: body?.summary,
websiteUrl: body?.websiteUrl,
transport: body?.transport,
command: body?.command,
args: body?.args,
env: body?.env,
tags: body?.tags,
source: body?.source,
enabled: body?.enabled,
accessMode: body?.accessMode,
allowedSandboxIds: body?.allowedSandboxIds,
})
return NextResponse.json({ server, ...(await listMcpServers()) })
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to update MCP servers"
return NextResponse.json({ error: message }, { status: 400 })
}
}
+67
View File
@@ -0,0 +1,67 @@
import { NextResponse } from "next/server"
import { syncSandboxMcpManifest } from "@/app/lib/sandboxMcpManifest"
function readSandboxName(request: Request) {
const requestUrl = new URL(request.url)
return requestUrl.searchParams.get("sandboxName") || null
}
function brokerBaseUrl(request: Request) {
const origin = new URL(request.url).origin
return process.env.OPENSHELL_CONTROL_MCP_BROKER_URL || `${origin}/api/mcp/broker`
}
export async function GET(
request: Request,
{ params }: { params: Promise<{ sandboxId: string }> },
) {
try {
const { sandboxId } = await params
const sandboxName = readSandboxName(request)
const brokerUrl = brokerBaseUrl(request)
return NextResponse.json({
ok: true,
sandboxId,
path: "/sandbox/openshell_control_mcp.md",
markdown: [
"# OpenShell Control MCP Broker",
"",
`Sandbox: ${sandboxName || sandboxId}`,
`Sandbox ID: ${sandboxId}`,
"",
"This preview omits the broker token. Use POST to issue and write a live broker config.",
"",
`- Capabilities: \`${brokerUrl}/capabilities\``,
`- Call: \`${brokerUrl}/call\``,
"",
].join("\n"),
})
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to build MCP broker handoff"
return NextResponse.json({ ok: false, error: message }, { status: 500 })
}
}
export async function POST(
request: Request,
{ params }: { params: Promise<{ sandboxId: string }> },
) {
try {
const { sandboxId } = await params
const body = await request.json().catch(() => ({}))
const sandboxName = typeof body?.sandboxName === "string" ? body.sandboxName : readSandboxName(request)
const synced = await syncSandboxMcpManifest(
{ id: sandboxId, name: sandboxName },
{ brokerBaseUrl: brokerBaseUrl(request) },
)
return NextResponse.json({
ok: true,
sandboxId,
synced,
note: `Issued MCP broker config at ${synced.path}.`,
})
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to issue MCP broker config"
return NextResponse.json({ ok: false, error: message }, { status: 500 })
}
}