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
+55 -1
View File
@@ -19,6 +19,8 @@ It is currently built for active development and lab use. It includes a simple p
- Approve or reject pending OpenShell network permission requests. - Approve or reject pending OpenShell network permission requests.
- Configure per-sandbox inference routes for Ollama, NIM, vLLM, and external endpoints. - Configure per-sandbox inference routes for Ollama, NIM, vLLM, and external endpoints.
- Poll Ollama for available models. - Poll Ollama for available models.
- Search the official MCP Registry, install MCP server definitions, and manage preconfigured/custom MCP servers.
- Enforce per-sandbox MCP access through a control-plane broker so sandboxes only see allowed capabilities.
- Upload files into sandboxes and download files back out. - Upload files into sandboxes and download files back out.
- Open an operator terminal for the selected sandbox. - Open an operator terminal for the selected sandbox.
- Simple local login, setup account, forgot password, and recovery token flow. - Simple local login, setup account, forgot password, and recovery token flow.
@@ -41,7 +43,7 @@ Minimum expected versions:
- Docker `24+` - Docker `24+`
- OpenShell CLI and gateway compatible with OpenShell `0.0.24` - OpenShell CLI and gateway compatible with OpenShell `0.0.24`
The app uses Next.js `14.2.15`, React `18.3.1`, TypeScript, Tailwind CSS, `ws`, and `node-pty`. The app uses Next.js `14.2.35`, React `18.3.1`, TypeScript, Tailwind CSS, `ws`, `node-pty`, and the official MCP TypeScript SDK.
## Prerequisites ## Prerequisites
@@ -54,6 +56,12 @@ docker ps
openshell --version openshell --version
``` ```
Optional, but useful for stdio MCP servers installed through the broker:
```bash
uvx --version
```
OpenShell must already be installed and able to reach its gateway. On this host the active gateway metadata lives under: OpenShell must already be installed and able to reach its gateway. On this host the active gateway metadata lives under:
```bash ```bash
@@ -77,6 +85,7 @@ The installer:
- runs a non-blocking `npm audit` summary; - runs a non-blocking `npm audit` summary;
- creates `.env.local` if needed; - creates `.env.local` if needed;
- generates a local dashboard password, signing secret, and recovery token if they are missing; - generates a local dashboard password, signing secret, and recovery token if they are missing;
- adds MCP broker defaults for token TTL and request timeout;
- runs `npm run build` as a verification step. - runs `npm run build` as a verification step.
It refuses to run as root unless `--allow-root` is supplied. It does not install or manage a systemd service. It refuses to run as root unless `--allow-root` is supplied. It does not install or manage a systemd service.
@@ -179,6 +188,47 @@ Supported provider categories in the UI:
- vLLM - vLLM
- external HTTP-compatible endpoints - external HTTP-compatible endpoints
## MCP Access Broker
OpenShell Control can install and broker MCP servers without disclosing the full MCP inventory to sandboxes.
The MCP page supports:
- registry search with paged results;
- preconfigured servers, including Blender MCP;
- custom stdio or HTTP MCP servers;
- global enable/disable state;
- per-sandbox `Disabled`, `Allow All`, and `Allow Only` access policy.
The sandbox page shows an MCP indicator on each sandbox card. A sandbox lights up when at least one MCP server is allowed by policy.
For sandbox handoff, OpenShell Control writes:
```text
/sandbox/openshell_control_mcp.md
```
That file contains only the MCP broker endpoints and a sandbox-scoped token. It does not list denied servers, launch commands, credentials, or registry metadata. The broker validates the token and enforces access policy on every capabilities and tool-call request.
Broker endpoints:
```text
/api/mcp/broker/capabilities
/api/mcp/broker/call
```
Broker configuration keys:
```bash
MCP_BROKER_TOKEN_TTL_HOURS=168
MCP_BROKER_REQUEST_TIMEOUT_MS=45000
OPENSHELL_CONTROL_MCP_BROKER_URL=http://localhost:3000/api/mcp/broker
```
`OPENSHELL_CONTROL_MCP_BROKER_URL` is optional. Set it when sandboxes need a routable URL that differs from the dashboard request origin.
Stdio MCP servers run on the control host. Make sure their launch commands, such as `uvx`, `npx`, `node`, or `python`, are available to the dashboard process.
## File Transfer ## File Transfer
The file transfer UI is scoped to safe sandbox paths: The file transfer UI is scoped to safe sandbox paths:
@@ -228,6 +278,8 @@ OPENSHELL_GATEWAY=nemoclaw
OPENSHELL_CONTROL_PASSWORD=change-this-password OPENSHELL_CONTROL_PASSWORD=change-this-password
OPENSHELL_CONTROL_AUTH_SECRET=change-this-random-secret OPENSHELL_CONTROL_AUTH_SECRET=change-this-random-secret
OPENSHELL_CONTROL_RECOVERY_TOKEN=change-this-recovery-token OPENSHELL_CONTROL_RECOVERY_TOKEN=change-this-recovery-token
MCP_BROKER_TOKEN_TTL_HOURS=168
MCP_BROKER_REQUEST_TIMEOUT_MS=45000
``` ```
## Security Limitations ## Security Limitations
@@ -243,6 +295,8 @@ Known limitations:
- no audit log persistence beyond process/container logs; - no audit log persistence beyond process/container logs;
- local recovery token can reset the password; - local recovery token can reset the password;
- assumes a trusted operator host and trusted local filesystem. - assumes a trusted operator host and trusted local filesystem.
- MCP stdio servers run as child processes on the control host; only install trusted MCP servers.
- MCP broker tokens grant sandbox-scoped access until expiry or rotation.
Before exposing this outside a trusted lab network, replace auth with a real identity provider, add role-based access control, add audit logging, use TLS, and review every shell-out path. Before exposing this outside a trusted lab network, replace auth with a real identity provider, add role-based access control, add audit logging, use TLS, and review every shell-out path.
+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 })
}
}
+563
View File
@@ -0,0 +1,563 @@
"use client"
import { useEffect, useMemo, useState } from "react"
type McpTransport = "stdio" | "http"
type McpCatalogEntry = {
id: string
name: string
summary: string
websiteUrl?: string
transport: McpTransport
command: string
args: string[]
env: Record<string, string>
tags: string[]
}
type McpServerInstall = McpCatalogEntry & {
installedAt: string
updatedAt: string
source: "catalog" | "custom" | "registry"
enabled: boolean
accessMode: "disabled" | "allow_all" | "allow_only"
allowedSandboxIds: string[]
}
type McpResponse = {
catalog: McpCatalogEntry[]
servers: McpServerInstall[]
config: Record<string, unknown>
error?: string
}
type McpSandbox = {
id: string
name: string
status: string
}
type McpConfigurationPanelProps = {
sandboxes?: McpSandbox[]
}
const REGISTRY_PAGE_SIZE = 4
function FieldLabel({ children }: { children: React.ReactNode }) {
return <label className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">{children}</label>
}
function parseLines(value: string) {
return value
.split(/\r?\n/)
.map((line) => line.trim())
.filter(Boolean)
}
function parseEnv(value: string) {
return Object.fromEntries(
parseLines(value)
.map((line) => {
const [key, ...rest] = line.split("=")
return [key?.trim() || "", rest.join("=").trim()]
})
.filter(([key]) => Boolean(key)),
)
}
export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurationPanelProps) {
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
const [message, setMessage] = useState("")
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 [customTransport, setCustomTransport] = useState<McpTransport>("stdio")
const [customCommand, setCustomCommand] = useState("npx")
const [customArgs, setCustomArgs] = useState("-y\n@modelcontextprotocol/server-memory")
const [customEnv, setCustomEnv] = useState("")
const [registrySearch, setRegistrySearch] = useState("github")
const [registryResults, setRegistryResults] = useState<McpCatalogEntry[]>([])
const [registryLoading, setRegistryLoading] = useState(false)
const [registryPage, setRegistryPage] = useState(1)
const [lastRegistrySearch, setLastRegistrySearch] = useState("")
const [catalogOpen, setCatalogOpen] = useState(false)
const [customOpen, setCustomOpen] = useState(false)
const installedIds = useMemo(() => new Set(servers.map((server) => server.id)), [servers])
const enabledCount = servers.filter((server) => server.enabled).length
const configText = JSON.stringify(config, null, 2)
const registryPageCount = Math.max(1, Math.ceil(registryResults.length / REGISTRY_PAGE_SIZE))
const pagedRegistryResults = registryResults.slice(
(registryPage - 1) * REGISTRY_PAGE_SIZE,
registryPage * REGISTRY_PAGE_SIZE,
)
async function load() {
try {
setLoading(true)
const response = await fetch("/api/mcp", { cache: "no-store" })
const data = await response.json() as McpResponse
if (!response.ok) throw new Error(data.error || "Failed to load MCP configuration")
setCatalog(Array.isArray(data.catalog) ? data.catalog : [])
setServers(Array.isArray(data.servers) ? data.servers : [])
setConfig(data.config || { mcpServers: {} })
setMessage("")
} catch (error) {
setMessage(error instanceof Error ? error.message : "Failed to load MCP configuration")
} finally {
setLoading(false)
}
}
async function postUpdate(body: Record<string, unknown>, success: string) {
try {
setSaving(true)
const response = await fetch("/api/mcp", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
})
const data = await response.json() as McpResponse
if (!response.ok) throw new Error(data.error || "Failed to update MCP configuration")
setCatalog(Array.isArray(data.catalog) ? data.catalog : catalog)
setServers(Array.isArray(data.servers) ? data.servers : [])
setConfig(data.config || { mcpServers: {} })
setMessage(success)
} catch (error) {
setMessage(error instanceof Error ? error.message : "Failed to update MCP configuration")
} finally {
setSaving(false)
}
}
function sandboxAllowed(server: McpServerInstall, sandbox: McpSandbox) {
return server.allowedSandboxIds.includes(sandbox.id) || server.allowedSandboxIds.includes(sandbox.name)
}
function toggleServerSandbox(server: McpServerInstall, sandbox: McpSandbox, allowed: boolean) {
const current = new Set(server.allowedSandboxIds)
current.delete(sandbox.id)
current.delete(sandbox.name)
if (allowed) current.add(sandbox.id)
return postUpdate({
action: "update-access",
serverId: server.id,
accessMode: "allow_only",
allowedSandboxIds: Array.from(current),
}, `${server.name} sandbox access updated.`)
}
async function searchRegistry() {
const query = registrySearch.trim()
try {
setRegistryLoading(true)
setRegistryResults([])
setRegistryPage(1)
setLastRegistrySearch(query)
const params = new URLSearchParams({ search: query, limit: "24" })
const response = await fetch(`/api/mcp/registry?${params}`, { cache: "no-store" })
const data = await response.json()
if (!response.ok) throw new Error(data.error || "Failed to search MCP registry")
const results = Array.isArray(data.results) ? data.results : []
setRegistryResults(results)
setMessage(results.length > 0 ? `Found ${results.length} registry server${results.length === 1 ? "" : "s"}.` : "No registry servers matched that search.")
} catch (error) {
setRegistryResults([])
setMessage(error instanceof Error ? error.message : "Failed to search MCP registry")
} finally {
setRegistryLoading(false)
}
}
useEffect(() => {
load()
}, [])
return (
<div className="space-y-6">
<div className="panel overflow-hidden">
<div className="panel-header flex items-start justify-between gap-6 p-6 max-md:flex-col">
<div>
<p className="font-mono text-[10px] uppercase tracking-wider text-[var(--nvidia-green)]">Model Context Protocol</p>
<h1 className="mt-1 text-xl font-semibold uppercase tracking-wider text-[var(--foreground)]">MCP CONFIGURATION</h1>
<p className="mt-2 max-w-3xl text-sm text-[var(--foreground-dim)]">
Install MCP server definitions for local tools, files, and remote context providers.
</p>
</div>
<button onClick={load} disabled={loading || saving} className="action-button px-4 py-2">
Refresh
</button>
</div>
<div className="grid grid-cols-1 gap-px bg-[var(--border-subtle)] sm:grid-cols-3">
<div className="bg-[var(--surface-raised)] p-4">
<p className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">Installed</p>
<p className="mt-1 font-mono text-sm text-[var(--foreground)]">{servers.length} servers</p>
</div>
<div className="bg-[var(--surface-raised)] p-4">
<p className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">Enabled</p>
<p className="mt-1 font-mono text-sm text-[var(--foreground)]">{enabledCount} active</p>
</div>
<div className="bg-[var(--surface-raised)] p-4">
<p className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">Catalog</p>
<p className="mt-1 font-mono text-sm text-[var(--foreground)]">{catalog.length} presets</p>
</div>
</div>
</div>
{message && (
<div className="panel p-4 text-xs text-[var(--foreground-dim)] whitespace-pre-wrap">
{message}
</div>
)}
{loading ? (
<div className="panel p-8 text-xs uppercase tracking-wider text-[var(--foreground-dim)]">Loading MCP servers...</div>
) : (
<div className="grid grid-cols-1 gap-6 xl:grid-cols-[minmax(0,1fr)_400px]">
<section className="space-y-6">
<div className="panel p-6">
<div className="border-b border-[var(--border-subtle)] pb-4">
<h2 className="text-sm font-semibold uppercase tracking-wider text-[var(--foreground)]">MCP Security</h2>
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Control which installed MCP servers are available to sandboxes.</p>
</div>
<div className="mt-5 space-y-4">
{servers.length === 0 ? (
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 text-xs text-[var(--foreground-dim)]">
Install an MCP server before configuring sandbox access.
</div>
) : servers.map((server) => (
<div key={server.id} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4">
<div className="flex items-start justify-between gap-4 max-lg:flex-col">
<div className="min-w-0">
<div className="flex items-center gap-2">
<h3 className="truncate text-sm font-mono font-semibold text-[var(--foreground)]">{server.name}</h3>
<span className={`status-chip px-2 py-1 ${server.enabled ? "bg-[var(--status-running-bg)] text-[var(--status-running)]" : "bg-[var(--status-pending-bg)] text-[var(--status-pending)]"}`}>
{server.enabled ? "enabled" : "disabled"}
</span>
</div>
<p className="mt-2 break-all font-mono text-[11px] text-[var(--foreground-dim)]">{server.command} {server.args.join(" ")}</p>
</div>
<div className="flex shrink-0 gap-2 max-sm:w-full max-sm:[&>button]:flex-1">
<button
onClick={() => postUpdate({ action: "update-access", serverId: server.id, enabled: true }, `${server.name} enabled.`)}
disabled={saving || server.enabled}
className="action-button px-3 py-2"
>
Enable
</button>
<button
onClick={() => postUpdate({ action: "update-access", serverId: server.id, enabled: false }, `${server.name} disabled.`)}
disabled={saving || !server.enabled}
className="action-button px-3 py-2"
>
Disable
</button>
</div>
</div>
<div className="mt-4 grid grid-cols-1 gap-3 lg:grid-cols-[240px_minmax(0,1fr)]">
<div className="space-y-2">
<FieldLabel>Availability</FieldLabel>
<select
value={server.accessMode}
onChange={(event) => postUpdate({
action: "update-access",
serverId: server.id,
accessMode: event.target.value,
}, `${server.name} availability updated.`)}
disabled={saving}
className="field-control w-full px-3 py-2 text-xs font-mono uppercase tracking-wider"
>
<option value="disabled">Disabled</option>
<option value="allow_all">Allow All</option>
<option value="allow_only">Allow Only</option>
</select>
</div>
<div className={server.accessMode === "allow_only" ? "space-y-2" : "opacity-50"}>
<FieldLabel>Allowed Sandboxes</FieldLabel>
{sandboxes.length === 0 ? (
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-3 text-xs text-[var(--foreground-dim)]">
No sandboxes detected.
</div>
) : (
<div className="grid grid-cols-1 gap-2 md:grid-cols-2">
{sandboxes.map((sandbox) => (
<label key={sandbox.id} className="flex items-center justify-between gap-3 rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-3 text-xs">
<span className="min-w-0">
<span className="block truncate font-mono text-[var(--foreground)]">{sandbox.name}</span>
<span className="mt-1 block truncate text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">{sandbox.status}</span>
</span>
<input
type="checkbox"
checked={sandboxAllowed(server, sandbox)}
disabled={saving || server.accessMode !== "allow_only"}
onChange={(event) => toggleServerSandbox(server, sandbox, event.target.checked)}
className="h-4 w-4 accent-[var(--nvidia-green)]"
/>
</label>
))}
</div>
)}
</div>
</div>
</div>
))}
</div>
</div>
<div className="panel p-6">
<div className="flex items-start justify-between gap-4 border-b border-[var(--border-subtle)] pb-4 max-md:flex-col">
<div>
<h2 className="text-sm font-semibold uppercase tracking-wider text-[var(--foreground)]">Registry Search</h2>
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Search the Official MCP Registry and install compatible stdio or remote HTTP servers.</p>
</div>
<a href="https://registry.modelcontextprotocol.io/" target="_blank" rel="noreferrer" className="action-button px-3 py-2">
Open Registry
</a>
</div>
<div className="mt-5 flex gap-3 max-sm:flex-col">
<input
value={registrySearch}
onChange={(event) => setRegistrySearch(event.target.value)}
onKeyDown={(event) => {
if (event.key === "Enter") searchRegistry()
}}
placeholder="Search GitHub, Slack, filesystem, Postgres..."
className="field-control min-w-0 flex-1 px-3 py-2 text-sm"
/>
<button onClick={searchRegistry} disabled={registryLoading || saving} className="rounded-sm bg-[var(--nvidia-green)] px-4 py-2 text-xs font-mono uppercase tracking-wider text-black disabled:opacity-50">
{registryLoading ? "Searching..." : "Search"}
</button>
</div>
{registryResults.length > 0 && (
<>
<div className="mt-5 flex items-center justify-between gap-3 border-t border-[var(--border-subtle)] pt-4 max-sm:flex-col max-sm:items-start">
<p className="text-xs text-[var(--foreground-dim)]">
Showing {((registryPage - 1) * REGISTRY_PAGE_SIZE) + 1}-{Math.min(registryPage * REGISTRY_PAGE_SIZE, registryResults.length)} of {registryResults.length}
{lastRegistrySearch ? ` for "${lastRegistrySearch}"` : ""}
</p>
<div className="flex items-center gap-2">
<button
onClick={() => setRegistryPage((page) => Math.max(1, page - 1))}
disabled={registryPage === 1}
className="action-button px-3 py-2"
>
Prev
</button>
<span className="min-w-16 text-center text-xs font-mono text-[var(--foreground-dim)]">
{registryPage} / {registryPageCount}
</span>
<button
onClick={() => setRegistryPage((page) => Math.min(registryPageCount, page + 1))}
disabled={registryPage === registryPageCount}
className="action-button px-3 py-2"
>
Next
</button>
</div>
</div>
<div className="mt-4 grid grid-cols-1 gap-3 md:grid-cols-2">
{pagedRegistryResults.map((entry) => {
const installed = installedIds.has(entry.id)
return (
<div key={`${entry.id}-${entry.command}`} className="metric flex min-h-44 flex-col p-4">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<h3 className="truncate text-sm font-semibold text-[var(--foreground)]">{entry.name}</h3>
<p className="mt-2 text-xs leading-5 text-[var(--foreground-dim)]">{entry.summary}</p>
</div>
<span className="status-chip bg-[var(--status-pending-bg)] px-2 py-1 text-[var(--status-pending)]">{entry.transport}</span>
</div>
<div className="mt-3 min-w-0 rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-2 font-mono text-[11px] text-[var(--foreground-dim)]">
<span className="text-[var(--foreground)]">{entry.command}</span> {entry.args.join(" ")}
</div>
<div className="mt-auto flex items-center justify-between gap-3 pt-4">
<p className="truncate text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">{entry.tags.join(" / ")}</p>
<button
onClick={() => postUpdate({ action: "install", ...entry, source: "registry" }, installed ? `${entry.name} refreshed from registry.` : `${entry.name} installed from registry.`)}
disabled={saving}
className={installed ? "action-button px-3 py-2" : "rounded-sm bg-[var(--nvidia-green)] px-3 py-2 text-xs font-mono uppercase tracking-wider text-black disabled:opacity-50"}
>
{installed ? "Refresh" : "Install"}
</button>
</div>
</div>
)
})}
</div>
</>
)}
</div>
<div className="panel p-6">
<button
type="button"
onClick={() => setCatalogOpen((open) => !open)}
className="flex w-full items-center justify-between gap-4 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--nvidia-green)]"
aria-expanded={catalogOpen}
>
<div>
<h2 className="text-sm font-semibold uppercase tracking-wider text-[var(--foreground)]">Preconfigured Servers</h2>
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Presets install as MCP command definitions; clients start them when needed.</p>
</div>
<span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] text-sm text-[var(--foreground)]">
{catalogOpen ? "-" : "+"}
</span>
</button>
{catalogOpen && (
<div className="mt-5 grid grid-cols-1 gap-3 border-t border-[var(--border-subtle)] pt-5 md:grid-cols-2">
{catalog.map((entry) => {
const installed = installedIds.has(entry.id)
return (
<div key={entry.id} className="metric flex min-h-44 flex-col p-4">
<div className="flex items-start justify-between gap-3">
<div>
<h3 className="text-sm font-semibold uppercase tracking-wider text-[var(--foreground)]">{entry.name}</h3>
<p className="mt-2 text-xs leading-5 text-[var(--foreground-dim)]">{entry.summary}</p>
{entry.websiteUrl && (
<a href={entry.websiteUrl} target="_blank" rel="noreferrer" className="mt-2 inline-block text-[11px] font-mono uppercase tracking-wider text-[var(--nvidia-green)] hover:underline">
Setup Guide
</a>
)}
</div>
<span className="status-chip bg-[var(--status-pending-bg)] px-2 py-1 text-[var(--status-pending)]">{entry.transport}</span>
</div>
<div className="mt-3 min-w-0 rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-2 font-mono text-[11px] text-[var(--foreground-dim)]">
<span className="text-[var(--foreground)]">{entry.command}</span> {entry.args.join(" ")}
</div>
<div className="mt-auto flex items-center justify-between gap-3 pt-4">
<p className="truncate text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">{entry.tags.join(" / ")}</p>
<button
onClick={() => postUpdate({ action: "install", id: entry.id }, installed ? `${entry.name} refreshed.` : `${entry.name} installed.`)}
disabled={saving}
className={installed ? "action-button px-3 py-2" : "rounded-sm bg-[var(--nvidia-green)] px-3 py-2 text-xs font-mono uppercase tracking-wider text-black disabled:opacity-50"}
>
{installed ? "Refresh" : "Install"}
</button>
</div>
</div>
)
})}
</div>
)}
</div>
<div className="panel p-6">
<button
type="button"
onClick={() => setCustomOpen((open) => !open)}
className="flex w-full items-center justify-between gap-4 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--nvidia-green)]"
aria-expanded={customOpen}
>
<div>
<h2 className="text-sm font-semibold uppercase tracking-wider text-[var(--foreground)]">Custom Server</h2>
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Add a server command that is not in the catalog.</p>
</div>
<span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] text-sm text-[var(--foreground)]">
{customOpen ? "-" : "+"}
</span>
</button>
{customOpen && (
<div className="mt-5 border-t border-[var(--border-subtle)] pt-5">
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
<div className="space-y-2">
<FieldLabel>Name</FieldLabel>
<input value={customName} onChange={(event) => setCustomName(event.target.value)} className="field-control w-full px-3 py-2 text-sm font-mono" />
</div>
<div className="space-y-2">
<FieldLabel>Transport</FieldLabel>
<select value={customTransport} onChange={(event) => setCustomTransport(event.target.value as McpTransport)} className="field-control w-full px-3 py-2 text-sm font-mono">
<option value="stdio">stdio</option>
<option value="http">http</option>
</select>
</div>
<div className="space-y-2 md:col-span-2">
<FieldLabel>Summary</FieldLabel>
<input value={customSummary} onChange={(event) => setCustomSummary(event.target.value)} className="field-control w-full px-3 py-2 text-sm" />
</div>
<div className="space-y-2 md:col-span-2">
<FieldLabel>{customTransport === "http" ? "URL" : "Command"}</FieldLabel>
<input value={customCommand} onChange={(event) => setCustomCommand(event.target.value)} placeholder={customTransport === "http" ? "https://mcp.example.com/mcp" : "npx, uvx, node, python"} className="field-control w-full px-3 py-2 text-sm font-mono" />
</div>
<div className="space-y-2">
<FieldLabel>Args</FieldLabel>
<textarea value={customArgs} onChange={(event) => setCustomArgs(event.target.value)} rows={6} className="field-control w-full resize-y px-3 py-2 text-sm font-mono" />
</div>
<div className="space-y-2">
<FieldLabel>{customTransport === "http" ? "Headers" : "Env"}</FieldLabel>
<textarea value={customEnv} onChange={(event) => setCustomEnv(event.target.value)} rows={6} placeholder={customTransport === "http" ? "Authorization=Bearer token" : "API_KEY=value\nBASE_URL=http://localhost:3000"} className="field-control w-full resize-y px-3 py-2 text-sm font-mono" />
</div>
</div>
<button
onClick={() => postUpdate({
action: "install",
id: customName,
name: customName,
summary: customSummary,
transport: customTransport,
command: customCommand,
args: parseLines(customArgs),
env: parseEnv(customEnv),
tags: ["custom"],
source: "custom",
}, `${customName} installed.`)}
disabled={saving}
className="mt-5 rounded-sm bg-[var(--nvidia-green)] px-4 py-2 text-xs font-mono uppercase tracking-wider text-black disabled:opacity-50"
>
Install Custom Server
</button>
</div>
)}
</div>
</section>
<aside className="space-y-6">
<div className="panel p-6">
<h2 className="text-sm font-semibold uppercase tracking-wider text-[var(--foreground)]">Installed Servers</h2>
<div className="mt-4 space-y-3">
{servers.length === 0 ? (
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 text-xs text-[var(--foreground-dim)]">
No MCP servers installed yet.
</div>
) : servers.map((server) => (
<div key={server.id} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<h3 className="truncate text-sm font-mono font-semibold text-[var(--foreground)]">{server.name}</h3>
<p className="mt-1 text-[11px] text-[var(--foreground-dim)]">{server.source} / {server.transport}</p>
</div>
<span className={`status-chip px-2 py-1 ${server.enabled ? "bg-[var(--status-running-bg)] text-[var(--status-running)]" : "bg-[var(--status-pending-bg)] text-[var(--status-pending)]"}`}>
{server.enabled ? "enabled" : "disabled"}
</span>
</div>
<p className="mt-3 break-all font-mono text-[11px] text-[var(--foreground-dim)]">{server.command} {server.args.join(" ")}</p>
<div className="mt-4 flex gap-2">
<button onClick={() => postUpdate({ action: server.enabled ? "disable" : "enable", serverId: server.id }, `${server.name} ${server.enabled ? "disabled" : "enabled"}.`)} disabled={saving} className="action-button flex-1 px-3 py-2">
{server.enabled ? "Disable" : "Enable"}
</button>
<button onClick={() => postUpdate({ action: "uninstall", serverId: server.id }, `${server.name} removed.`)} disabled={saving} className="action-button flex-1 px-3 py-2">
Remove
</button>
</div>
</div>
))}
</div>
</div>
<div className="panel p-6">
<h2 className="text-sm font-semibold uppercase tracking-wider text-[var(--foreground)]">Client JSON</h2>
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Enabled servers exported in common MCP client format.</p>
<pre className="mt-4 max-h-96 overflow-auto rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-4 text-[11px] leading-5 text-[var(--foreground-dim)]">
{configText}
</pre>
</div>
</aside>
</div>
)}
</div>
)
}
+238 -17
View File
@@ -27,7 +27,16 @@ interface SandboxListProps {
onInventoryRefresh: () => Promise<SandboxInventoryItem[]> onInventoryRefresh: () => Promise<SandboxInventoryItem[]>
} }
type DrawerKey = 'operations' | 'files' | 'inference' | 'policy' | 'archive' type DrawerKey = 'operations' | 'files' | 'inference' | 'policy' | 'archive' | 'mcp'
type McpServerAccess = {
id: string
name: string
command: string
args: string[]
enabled: boolean
accessMode: 'disabled' | 'allow_all' | 'allow_only'
allowedSandboxIds: string[]
}
type NetworkRuleRequest = { type NetworkRuleRequest = {
chunkId: string chunkId: string
status: string status: string
@@ -78,7 +87,7 @@ function DrawerSection({
type="button" type="button"
onClick={onToggle} onClick={onToggle}
aria-expanded={open} aria-expanded={open}
className="flex w-full items-center justify-between gap-4 p-5 text-left" className="flex w-full items-center justify-between gap-4 p-5 text-left transition-colors hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--nvidia-green)] max-sm:p-4"
> >
<div className="min-w-0"> <div className="min-w-0">
<h4 className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">{title}</h4> <h4 className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">{title}</h4>
@@ -95,7 +104,7 @@ function DrawerSection({
</svg> </svg>
</button> </button>
{open && ( {open && (
<div className="border-t border-[var(--border-subtle)] p-6"> <div className="border-t border-[var(--border-subtle)] p-6 max-sm:p-4">
{children} {children}
</div> </div>
)} )}
@@ -117,12 +126,17 @@ export default function SandboxList({
const [permissionMessage, setPermissionMessage] = useState('') const [permissionMessage, setPermissionMessage] = useState('')
const [permissionFeeds, setPermissionFeeds] = useState<Record<string, PermissionFeed>>({}) const [permissionFeeds, setPermissionFeeds] = useState<Record<string, PermissionFeed>>({})
const [grantingSandboxId, setGrantingSandboxId] = useState<string | null>(null) const [grantingSandboxId, setGrantingSandboxId] = useState<string | null>(null)
const [mcpServers, setMcpServers] = useState<McpServerAccess[]>([])
const [mcpMessage, setMcpMessage] = useState('')
const [mcpUpdatingServerId, setMcpUpdatingServerId] = useState<string | null>(null)
const [mcpSyncing, setMcpSyncing] = useState(false)
const [openDrawers, setOpenDrawers] = useState<Record<DrawerKey, boolean>>({ const [openDrawers, setOpenDrawers] = useState<Record<DrawerKey, boolean>>({
operations: true, operations: true,
files: false, files: false,
inference: false, inference: false,
policy: false, policy: false,
archive: false, archive: false,
mcp: false,
}) })
const [telemetry, setTelemetry] = useState<TelemetryData>({ const [telemetry, setTelemetry] = useState<TelemetryData>({
cpu: 0, memory: 0, disk: 0, timestamp: new Date().toISOString() cpu: 0, memory: 0, disk: 0, timestamp: new Date().toISOString()
@@ -164,6 +178,30 @@ export default function SandboxList({
} }
}, [sandboxes]) }, [sandboxes])
useEffect(() => {
let active = true
const loadMcpAccess = async () => {
try {
const response = await fetch('/api/mcp', { cache: 'no-store' })
const data = await response.json()
if (!response.ok) throw new Error(data.error || 'Failed to load MCP access')
if (active) setMcpServers(Array.isArray(data.servers) ? data.servers : [])
} catch (error) {
if (active) {
setMcpServers([])
setMcpMessage(error instanceof Error ? error.message : 'Failed to load MCP access')
}
}
}
loadMcpAccess()
const interval = window.setInterval(loadMcpAccess, 12000)
return () => {
active = false
window.clearInterval(interval)
}
}, [])
const fetchTelemetry = async () => { const fetchTelemetry = async () => {
try { try {
const response = await fetch('/api/telemetry/combined') const response = await fetch('/api/telemetry/combined')
@@ -197,6 +235,84 @@ export default function SandboxList({
setOpenDrawers((current) => ({ ...current, [key]: !current[key] })) setOpenDrawers((current) => ({ ...current, [key]: !current[key] }))
} }
const sandboxCanAccessMcpServer = (sandbox: SandboxInventoryItem, server: McpServerAccess) => {
if (!server.enabled || server.accessMode === 'disabled') return false
if (server.accessMode === 'allow_all') return true
return server.allowedSandboxIds.includes(sandbox.id) || server.allowedSandboxIds.includes(sandbox.name)
}
const allowedMcpServersForSandbox = (sandbox: SandboxInventoryItem) => (
mcpServers.filter((server) => sandboxCanAccessMcpServer(sandbox, server))
)
const updateMcpServerAccess = async (
server: McpServerAccess,
body: Partial<Pick<McpServerAccess, 'enabled' | 'accessMode' | 'allowedSandboxIds'>>,
success: string,
) => {
try {
setMcpUpdatingServerId(server.id)
setMcpMessage('')
const response = await fetch('/api/mcp', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'update-access', serverId: server.id, ...body }),
})
const data = await response.json()
if (!response.ok) throw new Error(data.error || 'Failed to update MCP access')
setMcpServers(Array.isArray(data.servers) ? data.servers : [])
setMcpMessage(success)
} catch (error) {
setMcpMessage(error instanceof Error ? error.message : 'Failed to update MCP access')
} finally {
setMcpUpdatingServerId(null)
}
}
const syncMcpManifest = async (sandbox: SandboxInventoryItem) => {
try {
setMcpSyncing(true)
setMcpMessage(`Issuing MCP broker config for ${sandbox.name}...`)
const response = await fetch(`/api/sandbox/${encodeURIComponent(sandbox.id)}/mcp`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sandboxName: sandbox.name }),
})
const data = await response.json()
if (!response.ok) throw new Error(data.error || 'Failed to issue MCP broker config')
setMcpMessage(data.note || 'MCP broker config issued.')
} catch (error) {
setMcpMessage(error instanceof Error ? error.message : 'Failed to issue MCP broker config')
} finally {
setMcpSyncing(false)
}
}
const enableMcpForSandbox = (sandbox: SandboxInventoryItem, server: McpServerAccess) => {
const current = new Set(server.allowedSandboxIds)
current.add(sandbox.id)
return updateMcpServerAccess(server, {
enabled: true,
accessMode: server.accessMode === 'allow_all' ? 'allow_all' : 'allow_only',
allowedSandboxIds: Array.from(current),
}, `${server.name} enabled for ${sandbox.name}.`).then(() => syncMcpManifest(sandbox))
}
const revokeMcpForSandbox = (sandbox: SandboxInventoryItem, server: McpServerAccess) => {
const current = new Set(server.allowedSandboxIds)
current.delete(sandbox.id)
current.delete(sandbox.name)
if (server.accessMode === 'allow_all') {
for (const item of sandboxes) {
if (item.id !== sandbox.id) current.add(item.id)
}
}
return updateMcpServerAccess(server, {
accessMode: 'allow_only',
allowedSandboxIds: Array.from(current),
}, `${server.name} revoked from ${sandbox.name}.`).then(() => syncMcpManifest(sandbox))
}
const resolvePermissionRequest = async (sandbox: SandboxInventoryItem, action: 'approve' | 'reject', chunkId: string) => { const resolvePermissionRequest = async (sandbox: SandboxInventoryItem, action: 'approve' | 'reject', chunkId: string) => {
if (!chunkId) return if (!chunkId) return
try { try {
@@ -234,7 +350,7 @@ export default function SandboxList({
</div> </div>
) : ( ) : (
<> <>
<div className="flex items-end justify-between gap-4"> <div className="flex items-end justify-between gap-4 max-sm:flex-col max-sm:items-start">
<div> <div>
<p className="text-[10px] font-mono uppercase tracking-wider text-[var(--nvidia-green)]"> <p className="text-[10px] font-mono uppercase tracking-wider text-[var(--nvidia-green)]">
Inventory Inventory
@@ -252,16 +368,21 @@ export default function SandboxList({
{sandboxes.map((sandbox) => ( {sandboxes.map((sandbox) => (
<div <div
key={sandbox.id} key={sandbox.id}
className={`group overflow-hidden rounded border text-left transition-all ${ className={`group overflow-hidden rounded border text-left transition-all duration-150 ${
isDestroyMode isDestroyMode
? 'border-[var(--status-stopped)] bg-[var(--status-stopped-bg)] hover:shadow-[0_18px_60px_rgba(220,38,38,0.16)]' ? 'border-[var(--status-stopped)] bg-[var(--status-stopped-bg)] hover:shadow-[0_18px_60px_rgba(220,38,38,0.16)]'
: selectedSandboxId === sandbox.id : selectedSandboxId === sandbox.id
? 'border-[var(--nvidia-green)] bg-[var(--surface-hover)] shadow-[var(--shadow-glow)]' ? 'border-[var(--nvidia-green)] bg-[var(--surface-hover)] shadow-[var(--shadow-glow)]'
: 'border-[var(--border-subtle)] bg-[var(--surface-raised)] shadow-[var(--shadow-soft)] hover:border-[var(--nvidia-green)] hover:bg-[var(--surface-hover)]' : 'border-[var(--border-subtle)] bg-[var(--surface-raised)] shadow-[var(--shadow-soft)] hover:-translate-y-0.5 hover:border-[var(--nvidia-green)] hover:bg-[var(--surface-hover)]'
}`} }`}
> >
<button type="button" onClick={() => onSandboxSelect(sandbox.id)} className="w-full p-4 text-left"> <button
<div className="flex items-center justify-between gap-3 mb-3"> type="button"
onClick={() => onSandboxSelect(sandbox.id)}
className="w-full p-4 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--nvidia-green)]"
aria-pressed={selectedSandboxId === sandbox.id}
>
<div className="mb-3 flex items-start justify-between gap-3">
<div className="flex items-center gap-2 min-w-0"> <div className="flex items-center gap-2 min-w-0">
{(() => { {(() => {
const feed = permissionFeeds[sandbox.id] const feed = permissionFeeds[sandbox.id]
@@ -276,7 +397,7 @@ export default function SandboxList({
<span className="h-2.5 w-2.5 rounded-full bg-[var(--status-running)]" title={`Policy status: ${feed?.latest?.status || 'ok'}`} /> <span className="h-2.5 w-2.5 rounded-full bg-[var(--status-running)]" title={`Policy status: ${feed?.latest?.status || 'ok'}`} />
) )
})()} })()}
<span className={`text-sm font-mono font-semibold truncate ${ <span className={`truncate font-mono text-sm font-semibold ${
isDestroyMode ? 'text-[var(--status-stopped)]' : 'text-[var(--foreground)]' isDestroyMode ? 'text-[var(--status-stopped)]' : 'text-[var(--foreground)]'
}`}> }`}>
{sandbox.name} {sandbox.name}
@@ -284,6 +405,24 @@ export default function SandboxList({
{sandbox.isDefault ? ( {sandbox.isDefault ? (
<span className="rounded-full border border-[var(--border-subtle)] px-1.5 py-0.5 text-[9px] uppercase tracking-wider text-[var(--foreground-dim)]">default</span> <span className="rounded-full border border-[var(--border-subtle)] px-1.5 py-0.5 text-[9px] uppercase tracking-wider text-[var(--foreground-dim)]">default</span>
) : null} ) : null}
{(() => {
const hasMcpAccess = allowedMcpServersForSandbox(sandbox).length > 0
return (
<span
className={`inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-sm border ${
hasMcpAccess
? 'border-[var(--nvidia-green)] bg-[var(--status-running-bg)] text-[var(--nvidia-green)]'
: 'border-[var(--border-subtle)] bg-[var(--background-tertiary)] text-[var(--foreground-dim)] opacity-55'
}`}
title={hasMcpAccess ? 'MCP access allowed' : 'No MCP access allowed'}
aria-label={hasMcpAccess ? 'MCP access allowed' : 'No MCP access allowed'}
>
<svg className="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M7 8h10M7 16h10M9 4h6a2 2 0 012 2v12a2 2 0 01-2 2H9a2 2 0 01-2-2V6a2 2 0 012-2z" />
</svg>
</span>
)
})()}
</div> </div>
<div className={`status-chip shrink-0 px-2.5 py-1 ${ <div className={`status-chip shrink-0 px-2.5 py-1 ${
isDestroyMode isDestroyMode
@@ -300,15 +439,15 @@ export default function SandboxList({
</div> </div>
</div> </div>
<div className="space-y-1"> <div className="space-y-1.5">
{([ {([
['Attach Target', sandbox.ip, '180px'], ['Attach Target', sandbox.ip, '180px'],
['Namespace', sandbox.namespace, '120px'], ['Namespace', sandbox.namespace, '120px'],
['Host Alias', sandbox.sshHostAlias || 'N/A', '140px'], ['Host Alias', sandbox.sshHostAlias || 'N/A', '140px'],
['Sandbox ID', sandbox.id, '140px'], ['Sandbox ID', sandbox.id, '140px'],
] as Array<[string, string, string]>).map(([label, value, width]) => ( ] as Array<[string, string, string]>).map(([label, value, width]) => (
<div key={label} className="flex items-center justify-between gap-3"> <div key={label} className="grid grid-cols-[6.5rem_minmax(0,1fr)] items-center gap-3">
<span className="text-[10px] uppercase text-[var(--foreground-dim)]">{label}</span> <span className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">{label}</span>
<span className="text-xs font-mono truncate text-[var(--foreground)]" style={{ maxWidth: width }} title={value}>{value}</span> <span className="text-xs font-mono truncate text-[var(--foreground)]" style={{ maxWidth: width }} title={value}>{value}</span>
</div> </div>
))} ))}
@@ -324,7 +463,7 @@ export default function SandboxList({
event.currentTarget.value = '' event.currentTarget.value = ''
resolvePermissionRequest(sandbox, 'approve', value) resolvePermissionRequest(sandbox, 'approve', value)
}} }}
className="w-full rounded border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-xs font-mono uppercase tracking-wider text-[var(--foreground)] focus:outline-none focus:ring-1 focus:ring-[var(--nvidia-green)]" className="field-control w-full px-3 py-2 font-mono text-xs uppercase tracking-wider"
> >
<option value=""> <option value="">
{grantingSandboxId === sandbox.id {grantingSandboxId === sandbox.id
@@ -359,7 +498,7 @@ export default function SandboxList({
onToggle={() => toggleDrawer('operations')} onToggle={() => toggleDrawer('operations')}
> >
<div className="space-y-6"> <div className="space-y-6">
<div className="flex items-center gap-3 flex-wrap"> <div className="flex flex-wrap items-center gap-3 max-sm:[&>button]:w-full">
<button <button
onClick={async () => { onClick={async () => {
try { try {
@@ -410,7 +549,7 @@ export default function SandboxList({
</div> </div>
)} )}
<div className="grid grid-cols-2 md:grid-cols-4 gap-4"> <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
<div className="metric p-4"> <div className="metric p-4">
<p className="text-[10px] text-[var(--foreground-dim)] uppercase tracking-wider">CPU</p> <p className="text-[10px] text-[var(--foreground-dim)] uppercase tracking-wider">CPU</p>
<p className="text-xl font-mono text-[var(--nvidia-green)] mt-1">{telemetry.cpu.toFixed(1)}%</p> <p className="text-xl font-mono text-[var(--nvidia-green)] mt-1">{telemetry.cpu.toFixed(1)}%</p>
@@ -449,6 +588,88 @@ export default function SandboxList({
<SandboxInferencePanel sandbox={selectedSandbox} embedded showHeader={false} /> <SandboxInferencePanel sandbox={selectedSandbox} embedded showHeader={false} />
</DrawerSection> </DrawerSection>
<DrawerSection
title="Allowed MCP Server Access"
summary="Enable, disable, or revoke MCP servers for this sandbox."
open={openDrawers.mcp}
onToggle={() => toggleDrawer('mcp')}
>
<div className="space-y-4">
<div className="flex items-center justify-between gap-4 rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 max-sm:flex-col max-sm:items-start">
<div>
<h4 className="text-xs font-semibold uppercase tracking-wider text-[var(--foreground)]">Sandbox Manifest</h4>
<p className="mt-1 text-xs text-[var(--foreground-dim)]">
Writes <span className="font-mono text-[var(--foreground)]">/sandbox/openshell_control_mcp.md</span> with broker URL and sandbox token only.
</p>
</div>
<button
type="button"
disabled={mcpSyncing}
onClick={() => syncMcpManifest(selectedSandbox)}
className="action-button px-3 py-2 max-sm:w-full"
>
{mcpSyncing ? 'Issuing...' : 'Issue Broker Config'}
</button>
</div>
{mcpMessage && (
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-3 text-xs text-[var(--foreground-dim)]">
{mcpMessage}
</div>
)}
{mcpServers.length === 0 ? (
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 text-xs text-[var(--foreground-dim)]">
No MCP servers are installed yet.
</div>
) : (
<div className="grid grid-cols-1 gap-3 lg:grid-cols-2">
{mcpServers.map((server) => {
const hasAccess = sandboxCanAccessMcpServer(selectedSandbox, server)
const updating = mcpUpdatingServerId === server.id
return (
<div key={server.id} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<h4 className="truncate text-sm font-mono font-semibold text-[var(--foreground)]">{server.name}</h4>
<p className="mt-1 break-all font-mono text-[11px] text-[var(--foreground-dim)]">{server.command} {server.args.join(' ')}</p>
</div>
<span className={`status-chip px-2 py-1 ${hasAccess ? 'bg-[var(--status-running-bg)] text-[var(--status-running)]' : 'bg-[var(--status-pending-bg)] text-[var(--status-pending)]'}`}>
{hasAccess ? 'allowed' : 'blocked'}
</span>
</div>
<div className="mt-4 flex gap-2 max-sm:flex-col">
<button
type="button"
disabled={updating || hasAccess}
onClick={() => enableMcpForSandbox(selectedSandbox, server)}
className="action-button flex-1 px-3 py-2"
>
Enable
</button>
<button
type="button"
disabled={updating || !server.enabled}
onClick={() => updateMcpServerAccess(server, { enabled: false }, `${server.name} disabled globally.`)}
className="action-button flex-1 px-3 py-2"
>
Disable
</button>
<button
type="button"
disabled={updating || !hasAccess}
onClick={() => revokeMcpForSandbox(selectedSandbox, server)}
className="action-button flex-1 px-3 py-2"
>
Revoke
</button>
</div>
</div>
)
})}
</div>
)}
</div>
</DrawerSection>
<DrawerSection <DrawerSection
title="Sandbox Policy" title="Sandbox Policy"
summary="Approve or reject network requests raised by the sandbox." summary="Approve or reject network requests raised by the sandbox."
@@ -469,7 +690,7 @@ export default function SandboxList({
return pending.map((request) => ( return pending.map((request) => (
<div key={request.chunkId} className="rounded-sm border border-amber-400/60 bg-amber-400/10 p-4"> <div key={request.chunkId} className="rounded-sm border border-amber-400/60 bg-amber-400/10 p-4">
<div className="flex items-start justify-between gap-4"> <div className="flex items-start justify-between gap-4 max-md:flex-col">
<div className="min-w-0 space-y-2"> <div className="min-w-0 space-y-2">
<div className="flex items-center gap-2 flex-wrap"> <div className="flex items-center gap-2 flex-wrap">
<span className="text-xs font-mono font-semibold text-[var(--foreground)]"> <span className="text-xs font-mono font-semibold text-[var(--foreground)]">
@@ -486,7 +707,7 @@ export default function SandboxList({
{request.binary || request.binaries.join(', ') || 'unknown binary'} / {request.chunkId} {request.binary || request.binaries.join(', ') || 'unknown binary'} / {request.chunkId}
</p> </p>
</div> </div>
<div className="flex shrink-0 items-center gap-2"> <div className="flex shrink-0 items-center gap-2 max-md:w-full max-md:[&>button]:flex-1">
<button <button
type="button" type="button"
disabled={grantingSandboxId === selectedSandbox.id} disabled={grantingSandboxId === selectedSandbox.id}
+36 -16
View File
@@ -3,7 +3,7 @@
interface SidebarProps { interface SidebarProps {
sandboxesRunning: number sandboxesRunning: number
sandboxesTotal: number sandboxesTotal: number
activeView: 'settings' | 'sandboxes' | 'help' | 'wizards' activeView: 'settings' | 'sandboxes' | 'help' | 'wizards' | 'mcp'
isCreateMode: boolean isCreateMode: boolean
isDestroyMode: boolean isDestroyMode: boolean
onSandboxesClick: () => void onSandboxesClick: () => void
@@ -11,6 +11,7 @@ interface SidebarProps {
onDestroyClick: () => void onDestroyClick: () => void
onTerminalClick: () => void onTerminalClick: () => void
onSettingsClick: () => void onSettingsClick: () => void
onMcpClick: () => void
onWizardsClick: () => void onWizardsClick: () => void
onHelpClick: () => void onHelpClick: () => void
onExitMode: () => void onExitMode: () => void
@@ -29,18 +30,19 @@ export default function Sidebar({
onDestroyClick, onDestroyClick,
onTerminalClick, onTerminalClick,
onSettingsClick, onSettingsClick,
onMcpClick,
onWizardsClick, onWizardsClick,
onHelpClick, onHelpClick,
onExitMode, onExitMode,
onLogout, onLogout,
terminalDisabled = false, terminalDisabled = false,
}: SidebarProps) { }: SidebarProps) {
const navItemClass = (active = false, danger = false) => `w-full flex items-center gap-3 px-3 py-2.5 rounded transition-colors ${ const navItemClass = (active = false, danger = false) => `w-full flex items-center gap-3 rounded px-3 py-2.5 text-left transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--nvidia-green)] max-lg:min-w-24 max-lg:flex-col max-lg:justify-center max-lg:gap-1 max-lg:px-2 max-lg:py-2 ${
active active
? danger ? danger
? 'bg-[var(--status-stopped)] text-white shadow-[0_10px_28px_rgba(220,38,38,0.18)]' ? 'bg-[var(--status-stopped)] text-white shadow-[0_10px_28px_rgba(220,38,38,0.18)]'
: 'bg-[var(--nvidia-green)] text-black shadow-[0_10px_28px_rgba(118,185,0,0.18)]' : 'bg-[var(--nvidia-green)] text-black shadow-[0_10px_28px_rgba(118,185,0,0.18)]'
: 'hover:bg-[var(--background-tertiary)] text-[var(--foreground-dim)] hover:text-[var(--foreground)]' : 'text-[var(--foreground-dim)] hover:bg-[var(--background-tertiary)] hover:text-[var(--foreground)]'
}` }`
return ( return (
@@ -62,98 +64,116 @@ export default function Sidebar({
</div> </div>
</div> </div>
<nav className="flex-1 p-2 max-lg:grid max-lg:grid-cols-4 max-lg:gap-1 max-lg:overflow-x-auto"> <nav className="flex-1 p-2 max-lg:flex max-lg:gap-1 max-lg:overflow-x-auto max-lg:[scrollbar-width:none]">
<button <button
onClick={onSandboxesClick} onClick={onSandboxesClick}
className={navItemClass(activeView === 'sandboxes' && !isCreateMode && !isDestroyMode)} className={navItemClass(activeView === 'sandboxes' && !isCreateMode && !isDestroyMode)}
aria-current={activeView === 'sandboxes' && !isCreateMode && !isDestroyMode ? 'page' : undefined}
> >
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" /> <path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
</svg> </svg>
<span className="text-sm">Sandboxes</span> <span className="text-sm max-lg:text-[11px]">Sandboxes</span>
</button> </button>
<button <button
onClick={onCreateClick} onClick={onCreateClick}
className={`mt-1 max-lg:mt-0 ${navItemClass(isCreateMode)}`} className={`mt-1 max-lg:mt-0 ${navItemClass(isCreateMode)}`}
aria-pressed={isCreateMode}
> >
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M12 4v16m8-8H4" /> <path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M12 4v16m8-8H4" />
</svg> </svg>
<span className="text-sm">Create Sandbox</span> <span className="text-sm max-lg:text-[11px] max-lg:leading-tight">Create</span>
</button> </button>
<button <button
onClick={onDestroyClick} onClick={onDestroyClick}
className={`mt-1 max-lg:mt-0 ${navItemClass(isDestroyMode, true)}`} className={`mt-1 max-lg:mt-0 ${navItemClass(isDestroyMode, true)}`}
aria-pressed={isDestroyMode}
> >
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6M4 7h16" /> <path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6M4 7h16" />
</svg> </svg>
<span className="text-sm">Destroy Sandbox</span> <span className="text-sm max-lg:text-[11px] max-lg:leading-tight">Destroy</span>
</button> </button>
<button <button
onClick={onTerminalClick} onClick={onTerminalClick}
disabled={terminalDisabled} disabled={terminalDisabled}
className="mt-1 max-lg:mt-0 w-full flex items-center gap-3 px-3 py-2.5 rounded transition-colors hover:bg-[var(--background-tertiary)] text-[var(--foreground-dim)] hover:text-[var(--foreground)] disabled:opacity-40 disabled:cursor-not-allowed" title={terminalDisabled ? 'Select a sandbox to open the operator terminal' : 'Open operator terminal'}
className="mt-1 flex w-full items-center gap-3 rounded px-3 py-2.5 text-[var(--foreground-dim)] transition-all hover:bg-[var(--background-tertiary)] hover:text-[var(--foreground)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--nvidia-green)] disabled:cursor-not-allowed disabled:opacity-40 max-lg:mt-0 max-lg:min-w-24 max-lg:flex-col max-lg:justify-center max-lg:gap-1 max-lg:px-2 max-lg:py-2"
> >
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M4 17l6-6-6-6m8 14h8" /> <path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M4 17l6-6-6-6m8 14h8" />
</svg> </svg>
<span className="text-sm">Operator Terminal</span> <span className="text-sm max-lg:text-[11px] max-lg:leading-tight">Terminal</span>
</button> </button>
{(isCreateMode || isDestroyMode) && ( {(isCreateMode || isDestroyMode) && (
<button <button
onClick={onExitMode} onClick={onExitMode}
className="mt-1 w-full flex items-center gap-3 px-3 py-2.5 rounded bg-[var(--background-tertiary)] text-[var(--foreground-dim)] hover:bg-[var(--background-panel)] transition-colors max-lg:col-span-2" className="mt-1 flex w-full items-center gap-3 rounded bg-[var(--background-tertiary)] px-3 py-2.5 text-[var(--foreground-dim)] transition-colors hover:bg-[var(--background-panel)] max-lg:mt-0 max-lg:min-w-24 max-lg:flex-col max-lg:justify-center max-lg:gap-1 max-lg:px-2 max-lg:py-2"
> >
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M6 18L18 6M6 6l12 12" /> <path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg> </svg>
<span className="text-sm">Cancel</span> <span className="text-sm max-lg:text-[11px]">Cancel</span>
</button> </button>
)} )}
<button <button
onClick={onSettingsClick} onClick={onSettingsClick}
className={`mt-4 max-lg:mt-0 ${navItemClass(activeView === 'settings')}`} className={`mt-4 max-lg:mt-0 ${navItemClass(activeView === 'settings')}`}
aria-current={activeView === 'settings' ? 'page' : undefined}
> >
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M12 6v6l4 2m5-2a9 9 0 11-18 0 9 9 0 0118 0z" /> <path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M12 6v6l4 2m5-2a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg> </svg>
<span className="text-sm">Inference Endpoints</span> <span className="text-sm max-lg:text-[11px] max-lg:leading-tight">Inference</span>
</button> </button>
<button <button
onClick={onWizardsClick} onClick={onWizardsClick}
className={`mt-1 max-lg:mt-0 ${navItemClass(activeView === 'wizards')}`} className={`mt-1 max-lg:mt-0 ${navItemClass(activeView === 'wizards')}`}
aria-current={activeView === 'wizards' ? 'page' : undefined}
> >
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"> <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M12 3l2.2 4.8L19 10l-4.8 2.2L12 17l-2.2-4.8L5 10l4.8-2.2L12 3zm6 12l.9 2.1L21 18l-2.1.9L18 21l-.9-2.1L15 18l2.1-.9L18 15z" /> <path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M12 3l2.2 4.8L19 10l-4.8 2.2L12 17l-2.2-4.8L5 10l4.8-2.2L12 3zm6 12l.9 2.1L21 18l-2.1.9L18 21l-.9-2.1L15 18l2.1-.9L18 15z" />
</svg> </svg>
<span className="text-sm">Wizards</span> <span className="text-sm max-lg:text-[11px]">Wizards</span>
</button>
<button
onClick={onMcpClick}
className={`mt-1 max-lg:mt-0 ${navItemClass(activeView === 'mcp')}`}
aria-current={activeView === 'mcp' ? 'page' : undefined}
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M7 8h10M7 16h10M9 4h6a2 2 0 012 2v12a2 2 0 01-2 2H9a2 2 0 01-2-2V6a2 2 0 012-2z" />
</svg>
<span className="text-sm max-lg:text-[11px]">MCP</span>
</button> </button>
<button <button
onClick={onHelpClick} onClick={onHelpClick}
className={`mt-1 max-lg:mt-0 ${navItemClass(activeView === 'help')}`} className={`mt-1 max-lg:mt-0 ${navItemClass(activeView === 'help')}`}
aria-current={activeView === 'help' ? 'page' : undefined}
> >
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"> <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M9.09 9a3 3 0 115.82 1c-.64.85-1.91 1.26-2.41 2.32V13m-.5 4h.01M12 3a9 9 0 100 18 9 9 0 000-18z" /> <path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M9.09 9a3 3 0 115.82 1c-.64.85-1.91 1.26-2.41 2.32V13m-.5 4h.01M12 3a9 9 0 100 18 9 9 0 000-18z" />
</svg> </svg>
<span className="text-sm">Help</span> <span className="text-sm max-lg:text-[11px]">Help</span>
</button> </button>
<a <a
href="/setup-account" href="/setup-account"
className="mt-1 max-lg:mt-0 w-full flex items-center gap-3 px-3 py-2.5 rounded transition-colors hover:bg-[var(--background-tertiary)] text-[var(--foreground-dim)] hover:text-[var(--foreground)]" className="mt-1 flex w-full items-center gap-3 rounded px-3 py-2.5 text-[var(--foreground-dim)] transition-colors hover:bg-[var(--background-tertiary)] hover:text-[var(--foreground)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--nvidia-green)] max-lg:mt-0 max-lg:min-w-24 max-lg:flex-col max-lg:justify-center max-lg:gap-1 max-lg:px-2 max-lg:py-2"
> >
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"> <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M12 12a4 4 0 100-8 4 4 0 000 8zm-7 9a7 7 0 0114 0" /> <path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M12 12a4 4 0 100-8 4 4 0 000 8zm-7 9a7 7 0 0114 0" />
</svg> </svg>
<span className="text-sm">Setup Account</span> <span className="text-sm max-lg:text-[11px] max-lg:leading-tight">Account</span>
</a> </a>
</nav> </nav>
+83
View File
@@ -0,0 +1,83 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js"
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"
import type { McpServerInstall } from "./mcpServerStore"
const MCP_BROKER_REQUEST_TIMEOUT_MS = Number.parseInt(process.env.MCP_BROKER_REQUEST_TIMEOUT_MS || "45000", 10)
function cleanEnv(env: Record<string, string>) {
return Object.fromEntries(
Object.entries(env).filter(([, value]) => typeof value === "string" && value.length > 0),
)
}
function inheritedEnv() {
return Object.fromEntries(
Object.entries(process.env).filter((entry): entry is [string, string] => typeof entry[1] === "string"),
)
}
function transportForServer(server: McpServerInstall) {
if (server.transport === "http") {
return new StreamableHTTPClientTransport(new URL(server.command), {
requestInit: {
headers: cleanEnv(server.env),
},
})
}
return new StdioClientTransport({
command: server.command,
args: server.args,
env: {
...inheritedEnv(),
...cleanEnv(server.env),
},
stderr: "pipe",
})
}
async function withMcpClient<T>(server: McpServerInstall, fn: (client: Client) => Promise<T>) {
const client = new Client({
name: "openshell-control-mcp-broker",
version: "0.1.0",
})
const transport = transportForServer(server)
try {
await client.connect(transport, { timeout: MCP_BROKER_REQUEST_TIMEOUT_MS })
return await fn(client)
} finally {
await client.close().catch(() => null)
}
}
export async function listBrokerServerTools(server: McpServerInstall) {
return withMcpClient(server, async (client) => {
const result = await client.listTools({}, { timeout: MCP_BROKER_REQUEST_TIMEOUT_MS })
return result.tools.map((tool) => ({
name: tool.name,
title: tool.title,
description: tool.description,
inputSchema: tool.inputSchema,
annotations: tool.annotations,
}))
})
}
export async function callBrokerServerTool(
server: McpServerInstall,
toolName: string,
toolArguments: Record<string, unknown>,
) {
return withMcpClient(server, async (client) => (
client.callTool(
{
name: toolName,
arguments: toolArguments,
},
undefined,
{ timeout: MCP_BROKER_REQUEST_TIMEOUT_MS },
)
))
}
+98
View File
@@ -0,0 +1,98 @@
import { createHash, randomBytes, timingSafeEqual } from "node:crypto"
import { mkdir, readFile, writeFile } from "node:fs/promises"
import path from "node:path"
import { listMcpServers, sandboxCanAccessMcpServer } from "./mcpServerStore"
export type SandboxMcpBrokerSession = {
sandboxId: string
sandboxName: string | null
tokenHash: string
enabled: boolean
createdAt: string
rotatedAt: string
expiresAt: string | null
}
type StoreShape = {
sessions: Record<string, SandboxMcpBrokerSession>
}
const HOME = process.env.HOME || "/tmp"
const STORE_DIR = process.env.NEMOCLAW_DASHBOARD_STATE_DIR || path.join(HOME, ".nemoclaw-dashboard")
const STORE_PATH = path.join(STORE_DIR, "mcp-broker-sessions.json")
const DEFAULT_TOKEN_TTL_HOURS = Number.parseInt(process.env.MCP_BROKER_TOKEN_TTL_HOURS || "168", 10)
function emptyStore(): StoreShape {
return { sessions: {} }
}
async function readStore(): Promise<StoreShape> {
try {
const raw = await readFile(STORE_PATH, "utf8")
const parsed = JSON.parse(raw)
return parsed && typeof parsed === "object" && parsed.sessions && typeof parsed.sessions === "object"
? parsed
: emptyStore()
} catch {
return emptyStore()
}
}
async function writeStore(store: StoreShape) {
await mkdir(STORE_DIR, { recursive: true, mode: 0o700 })
await writeFile(STORE_PATH, JSON.stringify(store, null, 2), { mode: 0o600 })
}
function tokenHash(token: string) {
return createHash("sha256").update(token).digest("hex")
}
function safeEqual(left: string, right: string) {
const leftBuffer = Buffer.from(left)
const rightBuffer = Buffer.from(right)
return leftBuffer.length === rightBuffer.length && timingSafeEqual(leftBuffer, rightBuffer)
}
function expiryFromNow() {
if (!Number.isFinite(DEFAULT_TOKEN_TTL_HOURS) || DEFAULT_TOKEN_TTL_HOURS <= 0) return null
return new Date(Date.now() + DEFAULT_TOKEN_TTL_HOURS * 60 * 60 * 1000).toISOString()
}
export async function rotateSandboxMcpBrokerSession(sandboxId: string, sandboxName?: string | null) {
const store = await readStore()
const token = `osmcp_${randomBytes(32).toString("base64url")}`
const now = new Date().toISOString()
const existing = store.sessions[sandboxId]
const session: SandboxMcpBrokerSession = {
sandboxId,
sandboxName: sandboxName || existing?.sandboxName || null,
tokenHash: tokenHash(token),
enabled: true,
createdAt: existing?.createdAt || now,
rotatedAt: now,
expiresAt: expiryFromNow(),
}
store.sessions[sandboxId] = session
await writeStore(store)
return { session, token }
}
export async function verifySandboxMcpBrokerToken(token: string) {
const store = await readStore()
const hash = tokenHash(token)
const session = Object.values(store.sessions).find((candidate) => safeEqual(candidate.tokenHash, hash))
if (!session || !session.enabled) return null
if (session.expiresAt && Date.parse(session.expiresAt) <= Date.now()) return null
return session
}
export async function listAllowedBrokerServers(session: SandboxMcpBrokerSession) {
const inventory = await listMcpServers()
return inventory.servers.filter((server) => sandboxCanAccessMcpServer(server, session.sandboxId, session.sandboxName))
}
export function readBrokerToken(request: Request) {
const authorization = request.headers.get("authorization") || ""
const bearer = authorization.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()
return bearer || request.headers.get("x-openshell-mcp-token")?.trim() || ""
}
+263
View File
@@ -0,0 +1,263 @@
import { mkdir, readFile, writeFile } from "node:fs/promises"
import path from "node:path"
export type McpTransport = "stdio" | "http"
export type McpCatalogEntry = {
id: string
name: string
summary: string
websiteUrl?: string
transport: McpTransport
command: string
args: string[]
env: Record<string, string>
tags: string[]
}
export type McpServerInstall = McpCatalogEntry & {
installedAt: string
updatedAt: string
source: "catalog" | "custom" | "registry"
enabled: boolean
accessMode: "disabled" | "allow_all" | "allow_only"
allowedSandboxIds: string[]
}
type StoreShape = {
servers: Record<string, McpServerInstall>
}
const HOME = process.env.HOME || "/tmp"
const STORE_DIR = process.env.NEMOCLAW_DASHBOARD_STATE_DIR || path.join(HOME, ".nemoclaw-dashboard")
const STORE_PATH = path.join(STORE_DIR, "mcp-servers.json")
export const MCP_SERVER_CATALOG: McpCatalogEntry[] = [
{
id: "blender-mcp",
name: "Blender MCP",
summary: "Connect AI clients to Blender for natural-language 3D scene inspection, creation, and editing. Requires the Blender MCP add-on in Blender.",
websiteUrl: "https://blendermcp.org/",
transport: "stdio",
command: "uvx",
args: ["blender-mcp"],
env: {},
tags: ["blender", "3d", "creative"],
},
{
id: "filesystem",
name: "Filesystem",
summary: "Expose selected local directories to MCP clients through a stdio server.",
transport: "stdio",
command: "npx",
args: ["-y", "@modelcontextprotocol/server-filesystem", "/sandbox"],
env: {},
tags: ["files", "local"],
},
{
id: "memory",
name: "Memory",
summary: "Provide a local knowledge graph for persistent notes and relationships.",
transport: "stdio",
command: "npx",
args: ["-y", "@modelcontextprotocol/server-memory"],
env: {},
tags: ["state", "local"],
},
{
id: "git",
name: "Git",
summary: "Inspect and operate on a local git repository from an MCP client.",
transport: "stdio",
command: "uvx",
args: ["mcp-server-git", "--repository", process.cwd()],
env: {},
tags: ["repo", "developer"],
},
{
id: "fetch",
name: "Fetch",
summary: "Retrieve web content for MCP clients that need URL context.",
transport: "stdio",
command: "uvx",
args: ["mcp-server-fetch"],
env: {},
tags: ["web", "utility"],
},
]
function emptyStore(): StoreShape {
return { servers: {} }
}
function slugify(value: string) {
return value
.trim()
.toLowerCase()
.replace(/[^a-z0-9-]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 64)
}
function normalizeStringArray(value: unknown) {
if (!Array.isArray(value)) return []
return value.map((item) => String(item ?? "").trim()).filter(Boolean)
}
function normalizeEnv(value: unknown) {
if (!value || typeof value !== "object" || Array.isArray(value)) return {}
return Object.fromEntries(
Object.entries(value)
.map(([key, envValue]) => [key.trim(), String(envValue ?? "").trim()])
.filter(([key]) => Boolean(key)),
)
}
function normalizeTransport(value: unknown): McpTransport {
return value === "http" ? "http" : "stdio"
}
function normalizeInstall(input: Partial<McpServerInstall>, existing?: McpServerInstall | null): McpServerInstall {
const name = typeof input.name === "string" && input.name.trim() ? input.name.trim() : existing?.name || "MCP Server"
const id = slugify(typeof input.id === "string" && input.id.trim() ? input.id : existing?.id || name)
if (!id) throw new Error("server id is required")
const command = typeof input.command === "string" ? input.command.trim() : existing?.command || ""
if (!command) throw new Error("server command is required")
const now = new Date().toISOString()
return {
id,
name,
summary: typeof input.summary === "string" ? input.summary.trim() : existing?.summary || "",
websiteUrl: typeof input.websiteUrl === "string" ? input.websiteUrl.trim() : existing?.websiteUrl,
transport: normalizeTransport(input.transport ?? existing?.transport),
command,
args: normalizeStringArray(input.args ?? existing?.args),
env: normalizeEnv(input.env ?? existing?.env),
tags: normalizeStringArray(input.tags ?? existing?.tags),
installedAt: existing?.installedAt || now,
updatedAt: now,
source: input.source === "custom" || input.source === "registry" ? input.source : existing?.source || "catalog",
enabled: input.enabled ?? existing?.enabled ?? true,
accessMode: input.accessMode === "allow_all" || input.accessMode === "allow_only" || input.accessMode === "disabled"
? input.accessMode
: existing?.accessMode || "disabled",
allowedSandboxIds: normalizeStringArray(input.allowedSandboxIds ?? existing?.allowedSandboxIds),
}
}
async function readStore(): Promise<StoreShape> {
try {
const raw = await readFile(STORE_PATH, "utf8")
const parsed = JSON.parse(raw)
return parsed && typeof parsed === "object" && parsed.servers && typeof parsed.servers === "object"
? parsed
: emptyStore()
} catch {
return emptyStore()
}
}
async function writeStore(store: StoreShape) {
await mkdir(STORE_DIR, { recursive: true, mode: 0o700 })
await writeFile(STORE_PATH, JSON.stringify(store, null, 2), { mode: 0o600 })
}
export function buildMcpClientConfig(servers: McpServerInstall[]) {
return {
mcpServers: Object.fromEntries(
servers
.filter((server) => server.enabled)
.map((server) => [
server.id,
server.transport === "http"
? {
url: server.command,
...(Object.keys(server.env).length > 0 ? { headers: server.env } : {}),
}
: {
command: server.command,
args: server.args,
...(Object.keys(server.env).length > 0 ? { env: server.env } : {}),
},
]),
),
}
}
export function sandboxCanAccessMcpServer(server: McpServerInstall, sandboxId: string, sandboxName?: string | null) {
if (!server.enabled || server.accessMode === "disabled") return false
if (server.accessMode === "allow_all") return true
const allowed = new Set(server.allowedSandboxIds)
return allowed.has(sandboxId) || Boolean(sandboxName && allowed.has(sandboxName))
}
export async function listMcpServers() {
const store = await readStore()
const servers = Object.values(store.servers).sort((a, b) => a.name.localeCompare(b.name))
return {
catalog: MCP_SERVER_CATALOG,
servers,
config: buildMcpClientConfig(servers),
}
}
export async function installMcpServer(input: Partial<McpServerInstall>) {
const store = await readStore()
const fromCatalog = typeof input.id === "string"
? MCP_SERVER_CATALOG.find((entry) => entry.id === input.id)
: null
const next = normalizeInstall(
{
...fromCatalog,
...input,
source: input.source || (fromCatalog ? "catalog" : "custom"),
},
typeof input.id === "string" ? store.servers[slugify(input.id)] : null,
)
store.servers[next.id] = next
await writeStore(store)
return next
}
export async function setMcpServerEnabled(serverId: string, enabled: boolean) {
const store = await readStore()
const id = slugify(serverId)
const existing = store.servers[id]
if (!existing) throw new Error("MCP server is not installed")
store.servers[id] = normalizeInstall({ ...existing, enabled }, existing)
await writeStore(store)
return store.servers[id]
}
export async function updateMcpServerAccess(
serverId: string,
input: {
enabled?: boolean
accessMode?: McpServerInstall["accessMode"]
allowedSandboxIds?: string[]
},
) {
const store = await readStore()
const id = slugify(serverId)
const existing = store.servers[id]
if (!existing) throw new Error("MCP server is not installed")
store.servers[id] = normalizeInstall({
...existing,
enabled: input.enabled ?? existing.enabled,
accessMode: input.accessMode ?? existing.accessMode,
allowedSandboxIds: input.allowedSandboxIds ?? existing.allowedSandboxIds,
}, existing)
await writeStore(store)
return store.servers[id]
}
export async function uninstallMcpServer(serverId: string) {
const store = await readStore()
const id = slugify(serverId)
if (!store.servers[id]) throw new Error("MCP server is not installed")
delete store.servers[id]
await writeStore(store)
return { id }
}
+89
View File
@@ -0,0 +1,89 @@
import { rotateSandboxMcpBrokerSession } from "./mcpBrokerStore"
import { uploadSandboxFile } from "./sandboxFiles"
export const SANDBOX_MCP_MANIFEST_PATH = "/sandbox/openshell_control_mcp.md"
type SandboxRef = {
id: string
name?: string | null
}
type BrokerHandoffOptions = {
brokerBaseUrl: string
rotateToken?: boolean
}
function normalizeBrokerBaseUrl(value: string) {
return value.replace(/\/+$/, "")
}
export async function buildSandboxMcpBrokerHandoff(
sandbox: SandboxRef,
options: BrokerHandoffOptions,
) {
const { session, token } = await rotateSandboxMcpBrokerSession(sandbox.id, sandbox.name)
const brokerBaseUrl = normalizeBrokerBaseUrl(options.brokerBaseUrl)
const now = new Date().toISOString()
return {
session,
token,
markdown: [
"# OpenShell Control MCP Broker",
"",
`Generated: ${now}`,
`Sandbox: ${sandbox.name || sandbox.id}`,
`Sandbox ID: ${sandbox.id}`,
"",
"This sandbox does not receive a list of MCP servers. MCP access is brokered by OpenShell Control, and the control plane enforces which tools are available on every request.",
"",
"## Broker Endpoints",
"",
`- Capabilities: \`${brokerBaseUrl}/capabilities\``,
`- Call: \`${brokerBaseUrl}/call\``,
"",
"## Authentication",
"",
"Send this token as an Authorization bearer token or x-openshell-mcp-token header:",
"",
"```",
token,
"```",
"",
"## Rules",
"",
"- Do not assume any MCP server exists unless the broker returns it as available.",
"- Do not attempt to connect directly to MCP servers.",
"- Do not invent credentials. The broker owns server credentials and launch details.",
"- If access changes, ask the operator to issue a new broker config.",
"",
].join("\n"),
}
}
export async function syncSandboxMcpManifest(
sandbox: SandboxRef,
options: BrokerHandoffOptions,
) {
const handoff = await buildSandboxMcpBrokerHandoff(sandbox, options)
const uploaded = await uploadSandboxFile(
sandbox.id,
SANDBOX_MCP_MANIFEST_PATH,
"openshell_control_mcp.md",
Buffer.from(handoff.markdown, "utf8"),
)
return {
path: uploaded.path,
sandboxName: uploaded.sandboxName,
bytes: uploaded.bytes,
brokerSession: {
sandboxId: handoff.session.sandboxId,
sandboxName: handoff.session.sandboxName,
enabled: handoff.session.enabled,
rotatedAt: handoff.session.rotatedAt,
expiresAt: handoff.session.expiresAt,
},
markdown: handoff.markdown,
}
}
+55 -19
View File
@@ -6,6 +6,7 @@ import ConfigurationPanel from './components/ConfigurationPanel'
import InferenceEndpointPanel from './components/InferenceEndpointPanel' import InferenceEndpointPanel from './components/InferenceEndpointPanel'
import HelpPanel from './components/HelpPanel' import HelpPanel from './components/HelpPanel'
import WizardPanel from './components/WizardPanel' import WizardPanel from './components/WizardPanel'
import McpConfigurationPanel from './components/McpConfigurationPanel'
import { useSandboxInventory } from './hooks/useSandboxInventory' import { useSandboxInventory } from './hooks/useSandboxInventory'
import { import {
createHydrationSafeDashboardSessionState, createHydrationSafeDashboardSessionState,
@@ -20,12 +21,12 @@ export default function Dashboard() {
const [dashboardSession, setDashboardSession] = useState(() => createHydrationSafeDashboardSessionState()) const [dashboardSession, setDashboardSession] = useState(() => createHydrationSafeDashboardSessionState())
const [isCreateMode, setIsCreateMode] = useState(false) const [isCreateMode, setIsCreateMode] = useState(false)
const [isDestroyMode, setIsDestroyMode] = useState(false) const [isDestroyMode, setIsDestroyMode] = useState(false)
const [activeView, setActiveView] = useState<'settings' | 'sandboxes' | 'help' | 'wizards'>('sandboxes') const [activeView, setActiveView] = useState<'settings' | 'sandboxes' | 'help' | 'wizards' | 'mcp'>('sandboxes')
const [deletingSandboxId, setDeletingSandboxId] = useState<string | null>(null) const [deletingSandboxId, setDeletingSandboxId] = useState<string | null>(null)
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false) const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
const [lifecycleMessage, setLifecycleMessage] = useState<string | null>(null) const [lifecycleMessage, setLifecycleMessage] = useState<string | null>(null)
const [deleteInProgress, setDeleteInProgress] = useState(false) const [deleteInProgress, setDeleteInProgress] = useState(false)
const inventoryEnabled = activeView === 'sandboxes' || activeView === 'wizards' || activeView === 'help' || isCreateMode || isDestroyMode const inventoryEnabled = activeView === 'sandboxes' || activeView === 'wizards' || activeView === 'help' || activeView === 'mcp' || isCreateMode || isDestroyMode
const { sandboxes, nemoclaw, loading, error, refresh } = useSandboxInventory({ const { sandboxes, nemoclaw, loading, error, refresh } = useSandboxInventory({
enabled: inventoryEnabled, enabled: inventoryEnabled,
}) })
@@ -204,6 +205,12 @@ export default function Dashboard() {
setIsDestroyMode(false) setIsDestroyMode(false)
clearSelection() clearSelection()
}} }}
onMcpClick={() => {
setActiveView('mcp')
setIsCreateMode(false)
setIsDestroyMode(false)
clearSelection()
}}
onWizardsClick={() => { onWizardsClick={() => {
setActiveView('wizards') setActiveView('wizards')
setIsCreateMode(false) setIsCreateMode(false)
@@ -255,6 +262,8 @@ export default function Dashboard() {
</div> </div>
) : activeView === 'help' ? ( ) : activeView === 'help' ? (
<HelpPanel sandboxes={sandboxes} /> <HelpPanel sandboxes={sandboxes} />
) : activeView === 'mcp' ? (
<McpConfigurationPanel sandboxes={sandboxes} />
) : activeView === 'wizards' ? ( ) : activeView === 'wizards' ? (
<WizardPanel sandboxes={sandboxes} onInventoryRefresh={refresh} /> <WizardPanel sandboxes={sandboxes} onInventoryRefresh={refresh} />
) : isCreateMode ? ( ) : isCreateMode ? (
@@ -322,24 +331,51 @@ export default function Dashboard() {
</div> </div>
) : ( ) : (
<> <>
<div className="mb-8 flex items-center justify-between gap-4 rounded border border-[var(--border-subtle)] bg-[var(--surface-raised)]/70 p-5 shadow-[var(--shadow-soft)] backdrop-blur max-sm:flex-col max-sm:items-start"> <div className="panel mb-8 overflow-hidden">
<div className="min-w-0"> <div className="panel-header flex items-center justify-between gap-4 p-5 max-md:flex-col max-md:items-start">
<p className="text-[10px] font-mono uppercase tracking-wider text-[var(--nvidia-green)]"> <div className="min-w-0">
{sandboxes.filter((sandbox) => sandbox.status === 'running').length} online / {sandboxes.length} total <p className="font-mono text-[10px] uppercase tracking-wider text-[var(--nvidia-green)]">
</p> {sandboxes.filter((sandbox) => sandbox.status === 'running').length} online / {sandboxes.length} total
<h1 className="mt-1 text-xl font-semibold text-[var(--foreground)] uppercase tracking-wider"> </p>
OPENSHELL CONTROL <h1 className="mt-1 text-xl font-semibold uppercase tracking-wider text-[var(--foreground)]">
</h1> OPENSHELL CONTROL
<p className="text-xs text-[var(--foreground-dim)] mt-1"> </h1>
Manage local OpenShell sandboxes and operator access. <p className="mt-1 text-xs text-[var(--foreground-dim)]">
</p> Manage local OpenShell sandboxes and operator access.
</p>
</div>
<div className="flex items-center gap-2 max-sm:w-full">
<button
onClick={async () => {
await refresh({ force: true })
}}
className="action-button px-4 py-2 max-sm:flex-1"
>
REFRESH
</button>
<button
onClick={toggleTheme}
className="action-button px-4 py-2 max-sm:flex-1"
aria-label={`Switch to ${theme === 'dark' ? 'light' : 'dark'} theme`}
>
{theme === 'dark' ? 'LIGHT' : 'DARK'}
</button>
</div>
</div>
<div className="grid grid-cols-1 gap-px bg-[var(--border-subtle)] sm:grid-cols-3">
<div className="bg-[var(--surface-raised)] p-4">
<p className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">Selected</p>
<p className="mt-1 truncate font-mono text-sm text-[var(--foreground)]">{selectedSandbox?.name ?? 'none'}</p>
</div>
<div className="bg-[var(--surface-raised)] p-4">
<p className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">Ready</p>
<p className="mt-1 font-mono text-sm text-[var(--foreground)]">{sandboxes.filter((sandbox) => sandbox.ready).length} sandboxes</p>
</div>
<div className="bg-[var(--surface-raised)] p-4">
<p className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">Gateway</p>
<p className="mt-1 font-mono text-sm text-[var(--foreground)]">{nemoclaw?.available ? 'available' : 'not detected'}</p>
</div>
</div> </div>
<button
onClick={toggleTheme}
className="action-button px-4 py-2"
>
{theme === 'dark' ? 'LIGHT' : 'DARK'}
</button>
</div> </div>
{lifecycleMessage && ( {lifecycleMessage && (
+11
View File
@@ -92,6 +92,14 @@ require_command() {
command -v "$1" >/dev/null 2>&1 || fail "$1 is required but was not found." command -v "$1" >/dev/null 2>&1 || fail "$1 is required but was not found."
} }
optional_command() {
if command -v "$1" >/dev/null 2>&1; then
log "$2: $(command -v "$1")"
else
warn "$2 was not found. Related MCP servers can still be configured, but broker calls will fail until it is installed."
fi
}
port_owner() { port_owner() {
local port="$1" local port="$1"
if command -v lsof >/dev/null 2>&1; then if command -v lsof >/dev/null 2>&1; then
@@ -162,6 +170,7 @@ if [[ "$NODE_MAJOR" -lt "$MIN_NODE_MAJOR" ]]; then
fi fi
log "Node $(node -v), npm $(npm -v)" log "Node $(node -v), npm $(npm -v)"
optional_command uvx "uvx MCP package runner"
if ! docker ps >/dev/null 2>&1; then if ! docker ps >/dev/null 2>&1; then
fail "Docker is not reachable. Start Docker and rerun the installer." fail "Docker is not reachable. Start Docker and rerun the installer."
@@ -231,6 +240,8 @@ upsert_env "OPENSHELL_GATEWAY" "nemoclaw"
upsert_env "OPENSHELL_CONTROL_PASSWORD" "$(random_token 18)" upsert_env "OPENSHELL_CONTROL_PASSWORD" "$(random_token 18)"
upsert_env "OPENSHELL_CONTROL_AUTH_SECRET" "$(random_token 32)" upsert_env "OPENSHELL_CONTROL_AUTH_SECRET" "$(random_token 32)"
upsert_env "OPENSHELL_CONTROL_RECOVERY_TOKEN" "$(random_token 18)" upsert_env "OPENSHELL_CONTROL_RECOVERY_TOKEN" "$(random_token 18)"
upsert_env "MCP_BROKER_TOKEN_TTL_HOURS" "168"
upsert_env "MCP_BROKER_REQUEST_TIMEOUT_MS" "45000"
chmod 600 "$ENV_FILE" || true chmod 600 "$ENV_FILE" || true
+852 -20
View File
File diff suppressed because it is too large Load Diff
+2
View File
@@ -11,6 +11,7 @@
"terminal-server": "node terminal-server.mjs" "terminal-server": "node terminal-server.mjs"
}, },
"dependencies": { "dependencies": {
"@modelcontextprotocol/sdk": "^1.29.0",
"axios": "^1.15.2", "axios": "^1.15.2",
"next": "14.2.35", "next": "14.2.35",
"node-pty": "^1.1.0", "node-pty": "^1.1.0",
@@ -20,6 +21,7 @@
"ws": "^8.20.0", "ws": "^8.20.0",
"xterm": "^5.3.0", "xterm": "^5.3.0",
"xterm-addon-fit": "^0.8.0", "xterm-addon-fit": "^0.8.0",
"zod": "^4.3.6",
"zustand": "^4.5.5" "zustand": "^4.5.5"
}, },
"devDependencies": { "devDependencies": {
+98
View File
@@ -0,0 +1,98 @@
import assert from 'node:assert/strict'
import path from 'node:path'
import { readFile } from 'node:fs/promises'
const root = process.cwd()
const storePath = path.join(root, 'app/lib/mcpServerStore.ts')
const brokerStorePath = path.join(root, 'app/lib/mcpBrokerStore.ts')
const brokerClientPath = path.join(root, 'app/lib/mcpBrokerClient.ts')
const manifestPath = path.join(root, 'app/lib/sandboxMcpManifest.ts')
const routePath = path.join(root, 'app/api/mcp/route.ts')
const registryRoutePath = path.join(root, 'app/api/mcp/registry/route.ts')
const brokerCapabilitiesRoutePath = path.join(root, 'app/api/mcp/broker/capabilities/route.ts')
const brokerCallRoutePath = path.join(root, 'app/api/mcp/broker/call/route.ts')
const sandboxMcpRoutePath = path.join(root, 'app/api/sandbox/[sandboxId]/mcp/route.ts')
const panelPath = path.join(root, 'app/components/McpConfigurationPanel.tsx')
const sidebarPath = path.join(root, 'app/components/Sidebar.tsx')
const sandboxListPath = path.join(root, 'app/components/SandboxList.tsx')
const pagePath = path.join(root, 'app/page.tsx')
const [storeSource, brokerStoreSource, brokerClientSource, manifestSource, routeSource, registryRouteSource, brokerCapabilitiesRouteSource, brokerCallRouteSource, sandboxMcpRouteSource, panelSource, sidebarSource, sandboxListSource, pageSource] = await Promise.all([
readFile(storePath, 'utf8'),
readFile(brokerStorePath, 'utf8'),
readFile(brokerClientPath, 'utf8'),
readFile(manifestPath, 'utf8'),
readFile(routePath, 'utf8'),
readFile(registryRoutePath, 'utf8'),
readFile(brokerCapabilitiesRoutePath, 'utf8'),
readFile(brokerCallRoutePath, 'utf8'),
readFile(sandboxMcpRoutePath, 'utf8'),
readFile(panelPath, 'utf8'),
readFile(sidebarPath, 'utf8'),
readFile(sandboxListPath, 'utf8'),
readFile(pagePath, 'utf8'),
])
assert.match(storeSource, /export const MCP_SERVER_CATALOG/, 'MCP store must expose an install catalog')
assert.match(storeSource, /blendermcp\.org/, 'MCP catalog must include the requested BlenderMCP site')
assert.match(storeSource, /args:\s*\["blender-mcp"\]/, 'MCP catalog must install BlenderMCP via uvx blender-mcp')
assert.match(storeSource, /mcp-servers\.json/, 'MCP installs must persist to dashboard state')
assert.match(storeSource, /accessMode/, 'MCP installs must persist sandbox access mode')
assert.match(storeSource, /allowedSandboxIds/, 'MCP installs must persist allowed sandbox lists')
assert.match(storeSource, /existing\?\.accessMode \|\| "disabled"/, 'MCP server access should default to disabled for sandboxes')
assert.match(storeSource, /export function buildMcpClientConfig/, 'MCP store must export client config JSON')
assert.match(storeSource, /mcpServers/, 'MCP client config must use the common mcpServers shape')
assert.match(brokerStoreSource, /mcp-broker-sessions\.json/, 'MCP broker sessions must persist server-side')
assert.match(brokerStoreSource, /verifySandboxMcpBrokerToken/, 'MCP broker must verify sandbox tokens server-side')
assert.match(brokerStoreSource, /listAllowedBrokerServers/, 'MCP broker must filter servers by access policy')
assert.match(brokerClientSource, /@modelcontextprotocol\/sdk\/client\/index\.js/, 'MCP broker must use the official SDK client')
assert.match(brokerClientSource, /StdioClientTransport/, 'MCP broker must support stdio servers')
assert.match(brokerClientSource, /StreamableHTTPClientTransport/, 'MCP broker must support streamable HTTP servers')
assert.match(brokerClientSource, /callBrokerServerTool/, 'MCP broker must forward allowed tool calls')
assert.match(manifestSource, /openshell_control_mcp\.md/, 'MCP sandbox manifest must use the requested filename')
assert.match(manifestSource, /syncSandboxMcpManifest/, 'MCP sandbox manifest must be syncable into a sandbox')
assert.doesNotMatch(manifestSource, /allowedServers|renderServer|commandLine/, 'MCP sandbox handoff must not disclose server inventory or launch specs')
assert.match(manifestSource, /control plane enforces/, 'MCP sandbox handoff must explain broker-side enforcement')
assert.match(brokerCapabilitiesRouteSource, /listAllowedBrokerServers/, 'MCP broker capabilities must only list allowed servers')
assert.match(brokerCapabilitiesRouteSource, /listBrokerServerTools/, 'MCP broker capabilities must inspect allowed server tools')
assert.match(brokerCallRouteSource, /Requested MCP capability is unavailable/, 'MCP broker denied calls must not disclose blocked server names')
assert.match(brokerCallRouteSource, /callBrokerServerTool/, 'MCP broker call route must forward allowed calls')
assert.match(sandboxMcpRouteSource, /export async function POST/, 'Sandbox MCP route must write the broker handoff')
assert.match(sandboxMcpRouteSource, /export async function GET/, 'Sandbox MCP route must preview the broker handoff')
assert.match(routeSource, /export async function GET/, 'MCP API must list server configuration')
assert.match(routeSource, /export async function POST/, 'MCP API must install and update server configuration')
assert.match(routeSource, /installMcpServer/, 'MCP API must support installing servers')
assert.match(routeSource, /uninstallMcpServer/, 'MCP API must support removing servers')
assert.match(routeSource, /updateMcpServerAccess/, 'MCP API must support access policy updates')
assert.match(registryRouteSource, /registry\.modelcontextprotocol\.io/, 'MCP registry search should default to the official registry')
assert.match(registryRouteSource, /\/v0\/servers/, 'MCP registry search should call the registry server list endpoint')
assert.match(registryRouteSource, /normalizeRegistryEntry/, 'MCP registry search should normalize results into installable entries')
assert.match(registryRouteSource, /packageInstall/, 'MCP registry search should support package-backed stdio installs')
assert.match(registryRouteSource, /remoteInstall/, 'MCP registry search should support remote HTTP installs')
assert.match(panelSource, /Install Custom Server/, 'MCP page must expose a custom server install action')
assert.match(panelSource, /Registry Search/, 'MCP page must expose official registry search')
assert.match(panelSource, /\/api\/mcp\/registry/, 'MCP page must query the registry search API')
assert.match(panelSource, /const REGISTRY_PAGE_SIZE = 4/, 'MCP registry search should page results four at a time')
assert.match(panelSource, /setRegistryResults\(\[\]\)/, 'MCP registry search should clear stale results before a new search')
assert.match(panelSource, /pagedRegistryResults/, 'MCP registry search should render paged results instead of the full result set')
assert.match(panelSource, /Preconfigured Servers/, 'MCP page should label catalog presets as preconfigured servers')
assert.match(panelSource, /aria-expanded=\{catalogOpen\}/, 'MCP preconfigured servers should render as an accordion')
assert.match(panelSource, /aria-expanded=\{customOpen\}/, 'MCP custom server form should render as an accordion')
assert.match(panelSource, /MCP Security/, 'MCP page must expose sandbox access controls')
assert.match(panelSource, /Allow All/, 'MCP security must support allow-all access')
assert.match(panelSource, /Allow Only/, 'MCP security must support allow-list access')
assert.match(panelSource, /Setup Guide/, 'MCP catalog cards should link out to app setup guides')
assert.match(panelSource, /Client JSON/, 'MCP page must surface generated client JSON')
assert.match(sandboxListSource, /Allowed MCP Server Access/, 'Sandbox page must expose allowed MCP server access accordion')
assert.match(sandboxListSource, /Issue Broker Config/, 'Sandbox MCP access controls must issue broker config')
assert.match(sandboxListSource, /\/sandbox\/openshell_control_mcp\.md/, 'Sandbox MCP access controls must name the manifest path')
assert.match(sandboxListSource, /sandboxCanAccessMcpServer/, 'Sandbox page must derive MCP access per sandbox')
assert.match(sandboxListSource, /MCP access allowed/, 'Sandbox cards must show a lit MCP access indicator')
assert.match(sandboxListSource, /Revoke/, 'Sandbox MCP access controls must include revoke')
assert.match(sidebarSource, /onMcpClick/, 'Sidebar must include MCP navigation callback')
assert.match(sidebarSource, /activeView === 'mcp'/, 'Sidebar must mark MCP view active')
assert.match(pageSource, /McpConfigurationPanel/, 'Dashboard must render MCP configuration panel')
assert.match(pageSource, /setActiveView\('mcp'\)/, 'Dashboard must switch to MCP view')
console.log('mcp-configuration-page-check: PASS MCP dashboard assertions')