Harden MCP broker sandbox handoff

This commit is contained in:
Codex
2026-04-27 21:33:05 +00:00
parent fdb18300eb
commit fd0959d994
18 changed files with 634 additions and 101 deletions
+4 -2
View File
@@ -59,6 +59,7 @@ openshell --version
Optional, but useful for stdio MCP servers installed through the broker: Optional, but useful for stdio MCP servers installed through the broker:
```bash ```bash
npx --version
uvx --version uvx --version
``` ```
@@ -81,6 +82,7 @@ From the repository root:
The installer: The installer:
- checks Node, npm, Docker, OpenShell CLI availability, sandbox inventory reachability, and default port occupancy; - checks Node, npm, Docker, OpenShell CLI availability, sandbox inventory reachability, and default port occupancy;
- installs or verifies the MCP package runners used by bundled stdio servers: `npx` and `uvx`;
- installs npm dependencies with `npm ci` when `package-lock.json` exists; - installs npm dependencies with `npm ci` when `package-lock.json` exists;
- runs a non-blocking `npm audit` summary; - runs a non-blocking `npm audit` summary;
- creates `.env.local` if needed; - creates `.env.local` if needed;
@@ -225,9 +227,9 @@ MCP_BROKER_REQUEST_TIMEOUT_MS=45000
OPENSHELL_CONTROL_MCP_BROKER_URL=http://localhost:3000/api/mcp/broker 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. `OPENSHELL_CONTROL_MCP_BROKER_URL` is optional. Set it only when you need to override discovery. By default the dashboard discovers the active OpenShell Docker gateway and the selected sandbox's proxy environment before writing `/sandbox/openshell_control_mcp.md`.
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. Stdio MCP servers run on the control host. The installer verifies `npx` and installs `uvx` into `~/.local/bin` when it is missing. Custom MCP server launch commands, such as `node` or `python`, must also be available to the dashboard process.
## File Transfer ## File Transfer
+13 -7
View File
@@ -19,10 +19,11 @@ function stripAnsi(value: string) {
return value.replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, "") return value.replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, "")
} }
async function runOpenShell(args: string[]) { async function runOpenShell(args: string[], extraEnv: Record<string, string> = {}) {
const { stdout, stderr } = await execFileAsync(OPENSHELL_BIN, args, { const { stdout, stderr } = await execFileAsync(OPENSHELL_BIN, args, {
env: { env: {
...process.env, ...process.env,
...extraEnv,
PATH: HOST_PATH, PATH: HOST_PATH,
OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY || "nemoclaw", OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY || "nemoclaw",
NO_COLOR: "1", NO_COLOR: "1",
@@ -105,8 +106,12 @@ function optionalString(value: unknown) {
return typeof value === "string" ? value.trim() : "" return typeof value === "string" ? value.trim() : ""
} }
function providerCredentialArg(credentialKey: string, apiKey: string) { function redactSecretOutput(value: string, secrets: string[] = []) {
return apiKey ? `${credentialKey}=${apiKey}` : credentialKey let redacted = value
for (const secret of secrets) {
if (secret) redacted = redacted.split(secret).join("[redacted]")
}
return redacted.replace(/([A-Z_][A-Z0-9_]*=)([^\s]+)/g, "$1[redacted]")
} }
export async function GET() { export async function GET() {
@@ -151,11 +156,12 @@ export async function POST(request: Request) {
? ["provider", "update", name] ? ["provider", "update", name]
: ["provider", "create", "--name", name, "--type", type] : ["provider", "create", "--name", name, "--type", type]
const providerEnv = apiKey ? { [credentialKey]: apiKey } : {}
if (!existingNames.includes(name) && !apiKey) providerArgs.push("--from-existing") if (!existingNames.includes(name) && !apiKey) providerArgs.push("--from-existing")
if (apiKey) providerArgs.push("--credential", providerCredentialArg(credentialKey, apiKey)) if (apiKey) providerArgs.push("--credential", credentialKey)
if (baseUrl) providerArgs.push("--config", `OPENAI_BASE_URL=${baseUrl}`) if (baseUrl) providerArgs.push("--config", `OPENAI_BASE_URL=${baseUrl}`)
const providerResult = await runOpenShell(providerArgs) const providerResult = await runOpenShell(providerArgs, providerEnv)
let inferenceResult = null let inferenceResult = null
if (makeActive) { if (makeActive) {
const routeArgs = ["inference", "set", "--provider", name, "--model", model] const routeArgs = ["inference", "set", "--provider", name, "--model", model]
@@ -172,8 +178,8 @@ export async function POST(request: Request) {
active: makeActive, active: makeActive,
gateway: parseRoute(refreshed.stdout, "Gateway inference"), gateway: parseRoute(refreshed.stdout, "Gateway inference"),
system: parseRoute(refreshed.stdout, "System inference"), system: parseRoute(refreshed.stdout, "System inference"),
stdout: [providerResult.stdout, inferenceResult?.stdout].filter(Boolean).join("\n\n"), stdout: redactSecretOutput([providerResult.stdout, inferenceResult?.stdout].filter(Boolean).join("\n\n"), [apiKey]),
stderr: [providerResult.stderr, inferenceResult?.stderr].filter(Boolean).join("\n\n"), stderr: redactSecretOutput([providerResult.stderr, inferenceResult?.stderr].filter(Boolean).join("\n\n"), [apiKey]),
}) })
} catch (error) { } catch (error) {
const message = error instanceof Error ? error.message : "Failed to save inference endpoint" const message = error instanceof Error ? error.message : "Failed to save inference endpoint"
@@ -1,5 +1,5 @@
import { NextResponse } from "next/server" import { NextResponse } from "next/server"
import { downloadSandboxFile } from "@/app/lib/sandboxFiles" import { downloadSandboxPath } from "@/app/lib/sandboxFiles"
function contentDisposition(fileName: string) { function contentDisposition(fileName: string) {
const fallback = fileName.replace(/[^\w.-]/g, "_") || "download.bin" const fallback = fileName.replace(/[^\w.-]/g, "_") || "download.bin"
@@ -14,7 +14,7 @@ export async function GET(
const { sandboxId } = await params const { sandboxId } = await params
const requestUrl = new URL(request.url) const requestUrl = new URL(request.url)
const sourcePath = requestUrl.searchParams.get("path") || "" const sourcePath = requestUrl.searchParams.get("path") || ""
const downloaded = await downloadSandboxFile(sandboxId, sourcePath) const downloaded = await downloadSandboxPath(sandboxId, sourcePath)
return new NextResponse(new Uint8Array(downloaded.bytes), { return new NextResponse(new Uint8Array(downloaded.bytes), {
status: 200, status: 200,
@@ -22,7 +22,7 @@ export async function GET(
"cache-control": "no-store", "cache-control": "no-store",
"content-disposition": contentDisposition(downloaded.fileName), "content-disposition": contentDisposition(downloaded.fileName),
"content-length": String(downloaded.bytes.byteLength), "content-length": String(downloaded.bytes.byteLength),
"content-type": "application/octet-stream", "content-type": downloaded.archive ? "application/gzip" : "application/octet-stream",
"x-sandbox-name": downloaded.sandboxName, "x-sandbox-name": downloaded.sandboxName,
"x-sandbox-path": downloaded.path, "x-sandbox-path": downloaded.path,
}, },
@@ -1,5 +1,5 @@
import { NextResponse } from "next/server" import { NextResponse } from "next/server"
import { assertRequestContentLength, uploadSandboxFile } from "@/app/lib/sandboxFiles" import { assertRequestContentLength, uploadSandboxFile, uploadSandboxFiles } from "@/app/lib/sandboxFiles"
export async function POST( export async function POST(
request: Request, request: Request,
@@ -10,13 +10,37 @@ export async function POST(
assertRequestContentLength(request) assertRequestContentLength(request)
const form = await request.formData() const form = await request.formData()
const file = form.get("file") const file = form.get("file")
const files = form.getAll("files")
const rawPath = form.get("path") const rawPath = form.get("path")
if (!(file instanceof File)) throw new Error("file is required") const rawRelativePaths = form.get("relativePaths")
const destinationPath = typeof rawPath === "string" && rawPath.trim() const destinationPath = typeof rawPath === "string" && rawPath.trim()
? rawPath.trim() ? rawPath.trim()
: `/sandbox/${file.name}` : "/sandbox/"
if (files.length > 0) {
const relativePaths = typeof rawRelativePaths === "string" ? JSON.parse(rawRelativePaths) : []
if (!Array.isArray(relativePaths)) throw new Error("relative paths are required for directory upload")
const payloads = await Promise.all(files.map(async (item, index) => {
if (!(item instanceof File)) throw new Error("files must contain only file uploads")
return {
fileName: item.name,
relativePath: typeof relativePaths[index] === "string" && relativePaths[index] ? relativePaths[index] : item.name,
payload: Buffer.from(await item.arrayBuffer()),
}
}))
const uploaded = await uploadSandboxFiles(sandboxId, destinationPath, payloads)
return NextResponse.json({
ok: true,
uploaded,
note: `Uploaded ${uploaded.files.length} file${uploaded.files.length === 1 ? "" : "s"} to ${destinationPath}.`,
})
}
if (!(file instanceof File)) throw new Error("file is required")
const targetPath = destinationPath.endsWith("/") ? destinationPath : rawPath ? destinationPath : `/sandbox/${file.name}`
const payload = Buffer.from(await file.arrayBuffer()) const payload = Buffer.from(await file.arrayBuffer())
const uploaded = await uploadSandboxFile(sandboxId, destinationPath, file.name, payload) const uploaded = await uploadSandboxFile(sandboxId, targetPath, file.name, payload)
return NextResponse.json({ return NextResponse.json({
ok: true, ok: true,
+27 -11
View File
@@ -1,16 +1,13 @@
import { NextResponse } from "next/server" import { NextResponse } from "next/server"
import { syncSandboxMcpManifest } from "@/app/lib/sandboxMcpManifest" import { brokerBaseUrlForSandbox } from "@/app/lib/mcpBrokerUrl"
import { revokeSandboxMcpManifest, syncSandboxMcpManifest } from "@/app/lib/sandboxMcpManifest"
import { revokeBrokerNetworkAccess, syncBrokerNetworkAccess } from "@/app/lib/sandboxPermissions"
function readSandboxName(request: Request) { function readSandboxName(request: Request) {
const requestUrl = new URL(request.url) const requestUrl = new URL(request.url)
return requestUrl.searchParams.get("sandboxName") || null 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( export async function GET(
request: Request, request: Request,
{ params }: { params: Promise<{ sandboxId: string }> }, { params }: { params: Promise<{ sandboxId: string }> },
@@ -18,7 +15,7 @@ export async function GET(
try { try {
const { sandboxId } = await params const { sandboxId } = await params
const sandboxName = readSandboxName(request) const sandboxName = readSandboxName(request)
const brokerUrl = brokerBaseUrl(request) const brokerUrl = await brokerBaseUrlForSandbox(request, { id: sandboxId, name: sandboxName })
return NextResponse.json({ return NextResponse.json({
ok: true, ok: true,
sandboxId, sandboxId,
@@ -50,14 +47,33 @@ export async function POST(
const { sandboxId } = await params const { sandboxId } = await params
const body = await request.json().catch(() => ({})) const body = await request.json().catch(() => ({}))
const sandboxName = typeof body?.sandboxName === "string" ? body.sandboxName : readSandboxName(request) const sandboxName = typeof body?.sandboxName === "string" ? body.sandboxName : readSandboxName(request)
const synced = await syncSandboxMcpManifest( const action = typeof body?.action === "string" ? body.action : "sync"
{ id: sandboxId, name: sandboxName }, const brokerUrl = await brokerBaseUrlForSandbox(request, { id: sandboxId, name: sandboxName })
{ brokerBaseUrl: brokerBaseUrl(request) },
) if (action === "revoke") {
const [synced, network] = await Promise.all([
revokeSandboxMcpManifest({ id: sandboxId, name: sandboxName }),
revokeBrokerNetworkAccess(sandboxId, brokerUrl),
])
return NextResponse.json({ return NextResponse.json({
ok: true, ok: true,
sandboxId, sandboxId,
synced, synced,
network,
note: `Revoked MCP broker config for ${synced.sandboxName}.`,
})
}
const synced = await syncSandboxMcpManifest(
{ id: sandboxId, name: sandboxName },
{ brokerBaseUrl: brokerUrl },
)
const network = await syncBrokerNetworkAccess(sandboxId, brokerUrl)
return NextResponse.json({
ok: true,
sandboxId,
synced,
network,
note: `Issued MCP broker config at ${synced.path}.`, note: `Issued MCP broker config at ${synced.path}.`,
}) })
} catch (error) { } catch (error) {
+2 -2
View File
@@ -361,10 +361,10 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
</div> </div>
</div> </div>
<div className="mt-4 grid grid-cols-1 gap-3 md:grid-cols-2"> <div className="mt-4 grid grid-cols-1 gap-3 md:grid-cols-2">
{pagedRegistryResults.map((entry) => { {pagedRegistryResults.map((entry, index) => {
const installed = installedIds.has(entry.id) const installed = installedIds.has(entry.id)
return ( return (
<div key={`${entry.id}-${entry.command}`} className="metric flex min-h-44 flex-col p-4"> <div key={`${entry.id}-${entry.command}-${entry.args.join("|")}-${index}`} className="metric flex min-h-44 flex-col p-4">
<div className="flex items-start justify-between gap-3"> <div className="flex items-start justify-between gap-3">
<div className="min-w-0"> <div className="min-w-0">
<h3 className="truncate text-sm font-semibold text-[var(--foreground)]">{entry.name}</h3> <h3 className="truncate text-sm font-semibold text-[var(--foreground)]">{entry.name}</h3>
+43 -11
View File
@@ -47,6 +47,8 @@ export default function SandboxFilesPanel({
showHeader?: boolean showHeader?: boolean
}) { }) {
const [selectedFile, setSelectedFile] = useState<File | null>(null) const [selectedFile, setSelectedFile] = useState<File | null>(null)
const [selectedDirectoryFiles, setSelectedDirectoryFiles] = useState<File[]>([])
const [uploadMode, setUploadMode] = useState<"file" | "directory">("file")
const [uploadPath, setUploadPath] = useState("/sandbox/") const [uploadPath, setUploadPath] = useState("/sandbox/")
const [downloadPath, setDownloadPath] = useState("/sandbox/") const [downloadPath, setDownloadPath] = useState("/sandbox/")
const [busy, setBusy] = useState<"upload" | "download" | null>(null) const [busy, setBusy] = useState<"upload" | "download" | null>(null)
@@ -59,6 +61,7 @@ export default function SandboxFilesPanel({
if (!selectedFile) return uploadPath if (!selectedFile) return uploadPath
return uploadPath.endsWith("/") ? `${uploadPath}${selectedFile.name}` : uploadPath return uploadPath.endsWith("/") ? `${uploadPath}${selectedFile.name}` : uploadPath
}, [selectedFile, uploadPath]) }, [selectedFile, uploadPath])
const uploadCount = uploadMode === "directory" ? selectedDirectoryFiles.length : selectedFile ? 1 : 0
const sortedEntries = useMemo(() => { const sortedEntries = useMemo(() => {
return [...(listing?.entries || [])].sort((left, right) => { return [...(listing?.entries || [])].sort((left, right) => {
@@ -99,21 +102,32 @@ export default function SandboxFilesPanel({
}, [sandbox.id]) }, [sandbox.id])
async function uploadFile() { async function uploadFile() {
if (!selectedFile || busy) return if (uploadCount === 0 || busy) return
try { try {
setBusy("upload") setBusy("upload")
setMessage("") setMessage("")
const form = new FormData() const form = new FormData()
form.set("file", selectedFile)
form.set("path", uploadPath) form.set("path", uploadPath)
if (uploadMode === "directory") {
form.set("relativePaths", JSON.stringify(selectedDirectoryFiles.map((file) => file.webkitRelativePath || file.name)))
for (const file of selectedDirectoryFiles) {
form.append("files", file, file.name)
}
} else if (selectedFile) {
form.set("file", selectedFile)
}
const response = await fetch(`/api/sandbox/${encodeURIComponent(sandbox.id)}/files/upload`, { const response = await fetch(`/api/sandbox/${encodeURIComponent(sandbox.id)}/files/upload`, {
method: "POST", method: "POST",
body: form, body: form,
}) })
const data = await response.json() const data = await response.json()
if (!response.ok) throw new Error(data.error || "Failed to upload file") if (!response.ok) throw new Error(data.error || "Failed to upload file")
setMessage(data.note || `Uploaded to ${data.uploaded?.path || suggestedUploadPath}.`) setMessage(data.note || "Upload complete.")
if (uploadMode === "directory") {
setDownloadPath(uploadPath)
} else {
setDownloadPath(data.uploaded?.path || suggestedUploadPath) setDownloadPath(data.uploaded?.path || suggestedUploadPath)
}
await loadFileList(listPath) await loadFileList(listPath)
} catch (error) { } catch (error) {
setMessage(error instanceof Error ? error.message : "Failed to upload file") setMessage(error instanceof Error ? error.message : "Failed to upload file")
@@ -188,7 +202,22 @@ export default function SandboxFilesPanel({
</div> </div>
<input <input
type="file" type="file"
onChange={(event) => setSelectedFile(event.target.files?.[0] || null)} onChange={(event) => {
setUploadMode("file")
setSelectedFile(event.target.files?.[0] || null)
setSelectedDirectoryFiles([])
}}
className="block w-full text-xs text-[var(--foreground-dim)] file:mr-3 file:rounded-sm file:border file:border-[var(--border-subtle)] file:bg-[var(--background)] file:px-3 file:py-2 file:text-xs file:font-mono file:uppercase file:text-[var(--foreground)]"
/>
<input
type="file"
multiple
{...({ webkitdirectory: "", directory: "" } as Record<string, string>)}
onChange={(event) => {
setUploadMode("directory")
setSelectedDirectoryFiles(Array.from(event.target.files || []))
setSelectedFile(null)
}}
className="block w-full text-xs text-[var(--foreground-dim)] file:mr-3 file:rounded-sm file:border file:border-[var(--border-subtle)] file:bg-[var(--background)] file:px-3 file:py-2 file:text-xs file:font-mono file:uppercase file:text-[var(--foreground)]" className="block w-full text-xs text-[var(--foreground-dim)] file:mr-3 file:rounded-sm file:border file:border-[var(--border-subtle)] file:bg-[var(--background)] file:px-3 file:py-2 file:text-xs file:font-mono file:uppercase file:text-[var(--foreground)]"
/> />
<div className="space-y-2"> <div className="space-y-2">
@@ -202,20 +231,25 @@ export default function SandboxFilesPanel({
{selectedFile && ( {selectedFile && (
<p className="text-[11px] font-mono text-[var(--foreground-dim)]">Target: {suggestedUploadPath}</p> <p className="text-[11px] font-mono text-[var(--foreground-dim)]">Target: {suggestedUploadPath}</p>
)} )}
{uploadMode === "directory" && selectedDirectoryFiles.length > 0 && (
<p className="text-[11px] font-mono text-[var(--foreground-dim)]">
Directory upload: {selectedDirectoryFiles.length} file{selectedDirectoryFiles.length === 1 ? "" : "s"} into {uploadPath}
</p>
)}
</div> </div>
<button <button
onClick={uploadFile} onClick={uploadFile}
disabled={!selectedFile || busy !== null} disabled={uploadCount === 0 || busy !== null}
className="rounded-sm bg-[var(--nvidia-green)] px-4 py-2 text-xs font-mono uppercase tracking-wider text-black disabled:opacity-50" className="rounded-sm bg-[var(--nvidia-green)] px-4 py-2 text-xs font-mono uppercase tracking-wider text-black disabled:opacity-50"
> >
{busy === "upload" ? "Uploading..." : "Upload File"} {busy === "upload" ? "Uploading..." : uploadMode === "directory" ? "Upload Directory" : "Upload File"}
</button> </button>
</section> </section>
<section className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 space-y-4"> <section className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 space-y-4">
<div> <div>
<h5 className="text-xs font-semibold uppercase tracking-wider text-[var(--foreground)]">Download</h5> <h5 className="text-xs font-semibold uppercase tracking-wider text-[var(--foreground)]">Download</h5>
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Browse sandbox files or enter a regular file path under /sandbox or /tmp.</p> <p className="mt-1 text-xs text-[var(--foreground-dim)]">Browse sandbox files or enter a file or directory path under /sandbox or /tmp.</p>
</div> </div>
<div className="grid grid-cols-1 gap-2 md:grid-cols-[1fr_auto_auto]"> <div className="grid grid-cols-1 gap-2 md:grid-cols-[1fr_auto_auto]">
<input <input
@@ -282,11 +316,9 @@ export default function SandboxFilesPanel({
type="button" type="button"
onClick={() => { onClick={() => {
setDownloadPath(entry.path) setDownloadPath(entry.path)
if (entry.type !== "directory") {
downloadFile(entry.path) downloadFile(entry.path)
}
}} }}
disabled={entry.type === "directory" || busy !== null} disabled={(entry.type !== "file" && entry.type !== "directory") || busy !== null}
className="action-button px-2 py-1 text-right disabled:opacity-30" className="action-button px-2 py-1 text-right disabled:opacity-30"
> >
Get Get
@@ -315,7 +347,7 @@ export default function SandboxFilesPanel({
disabled={!downloadPath.trim() || busy !== null} disabled={!downloadPath.trim() || busy !== null}
className="action-button px-4 py-2" className="action-button px-4 py-2"
> >
{busy === "download" ? "Downloading..." : "Download File"} {busy === "download" ? "Downloading..." : "Download Path"}
</button> </button>
</section> </section>
</div> </div>
+68 -11
View File
@@ -274,20 +274,25 @@ export default function SandboxList({
} }
} }
const syncMcpManifest = async (sandbox: SandboxInventoryItem) => { const syncMcpManifest = async (sandbox: SandboxInventoryItem, action: 'sync' | 'revoke' = 'sync') => {
try { try {
setMcpSyncing(true) setMcpSyncing(true)
setMcpMessage(`Issuing MCP broker config for ${sandbox.name}...`) setMcpMessage(action === 'revoke' ? `Revoking MCP broker config for ${sandbox.name}...` : `Issuing MCP broker config for ${sandbox.name}...`)
const response = await fetch(`/api/sandbox/${encodeURIComponent(sandbox.id)}/mcp`, { const response = await fetch(`/api/sandbox/${encodeURIComponent(sandbox.id)}/mcp`, {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sandboxName: sandbox.name }), body: JSON.stringify({ sandboxName: sandbox.name, action }),
}) })
const data = await response.json() const data = await response.json()
if (!response.ok) throw new Error(data.error || 'Failed to issue MCP broker config') if (!response.ok) throw new Error(data.error || 'Failed to update MCP broker config')
setMcpMessage(data.note || 'MCP broker config issued.') const networkNote = data.network?.approved?.length
? ` Approved ${data.network.approved.length} broker network rule${data.network.approved.length === 1 ? '' : 's'}.`
: data.network?.rejected?.length
? ` Removed ${data.network.rejected.length} broker network rule${data.network.rejected.length === 1 ? '' : 's'}.`
: ''
setMcpMessage(`${data.note || 'MCP broker config updated.'}${networkNote}`)
} catch (error) { } catch (error) {
setMcpMessage(error instanceof Error ? error.message : 'Failed to issue MCP broker config') setMcpMessage(error instanceof Error ? error.message : 'Failed to update MCP broker config')
} finally { } finally {
setMcpSyncing(false) setMcpSyncing(false)
} }
@@ -304,6 +309,7 @@ export default function SandboxList({
} }
const revokeMcpForSandbox = (sandbox: SandboxInventoryItem, server: McpServerAccess) => { const revokeMcpForSandbox = (sandbox: SandboxInventoryItem, server: McpServerAccess) => {
const hasOtherMcpAccess = mcpServers.some((candidate) => candidate.id !== server.id && sandboxCanAccessMcpServer(sandbox, candidate))
const current = new Set(server.allowedSandboxIds) const current = new Set(server.allowedSandboxIds)
current.delete(sandbox.id) current.delete(sandbox.id)
current.delete(sandbox.name) current.delete(sandbox.name)
@@ -315,7 +321,7 @@ export default function SandboxList({
return updateMcpServerAccess(server, { return updateMcpServerAccess(server, {
accessMode: 'allow_only', accessMode: 'allow_only',
allowedSandboxIds: Array.from(current), allowedSandboxIds: Array.from(current),
}, `${server.name} revoked from ${sandbox.name}.`).then(() => syncMcpManifest(sandbox)) }, `${server.name} revoked from ${sandbox.name}.`).then(() => syncMcpManifest(sandbox, hasOtherMcpAccess ? 'sync' : 'revoke'))
} }
const resolvePermissionRequest = async (sandbox: SandboxInventoryItem, action: 'approve' | 'reject', chunkId: string) => { const resolvePermissionRequest = async (sandbox: SandboxInventoryItem, action: 'approve' | 'reject', chunkId: string) => {
@@ -613,10 +619,10 @@ export default function SandboxList({
<button <button
type="button" type="button"
disabled={mcpSyncing} disabled={mcpSyncing}
onClick={() => syncMcpManifest(selectedSandbox)} onClick={() => syncMcpManifest(selectedSandbox, allowedMcpServersForSandbox(selectedSandbox).length > 0 ? 'sync' : 'revoke')}
className="action-button px-3 py-2 max-sm:w-full" className="action-button px-3 py-2 max-sm:w-full"
> >
{mcpSyncing ? 'Issuing...' : 'Issue Broker Config'} {mcpSyncing ? 'Updating...' : 'Sync Broker Config'}
</button> </button>
</div> </div>
{mcpMessage && ( {mcpMessage && (
@@ -702,15 +708,63 @@ export default function SandboxList({
{(() => { {(() => {
const feed = permissionFeeds[selectedSandbox.id] const feed = permissionFeeds[selectedSandbox.id]
const pending = feed?.pending || [] const pending = feed?.pending || []
const recent = feed?.recent || []
const recentRules = recent.filter((request) => !pending.some((pendingRequest) => pendingRequest.chunkId === request.chunkId))
const renderRecentRules = () => recentRules.length > 0 && (
<div className="space-y-3">
<h4 className="text-[10px] font-semibold uppercase tracking-wider text-[var(--foreground-dim)]">Recent Network Rules</h4>
<div className="max-h-[26rem] space-y-3 overflow-y-auto pr-1">
{recentRules.map((request) => {
const approved = /approved/i.test(request.status)
const rejected = /rejected/i.test(request.status)
return (
<div key={`${request.status}-${request.chunkId}`} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4">
<div className="flex items-start justify-between gap-4 max-md:flex-col">
<div className="min-w-0 space-y-2">
<div className="flex flex-wrap items-center gap-2">
<span className="break-all text-xs font-mono font-semibold text-[var(--foreground)]">
{request.endpoints.join(', ') || request.rule}
</span>
<span className={`status-chip px-2 py-1 ${approved ? 'bg-[var(--status-running-bg)] text-[var(--status-running)]' : rejected ? 'bg-[var(--status-stopped)] text-white' : 'bg-[var(--status-pending-bg)] text-[var(--status-pending)]'}`}>
{request.status || 'unknown'}
</span>
</div>
<p className="text-xs text-[var(--foreground-dim)]">{request.rationale || 'Sandbox network rule.'}</p>
<p className="text-[10px] font-mono text-[var(--foreground-dim)]">
{request.binary || request.binaries.join(', ') || 'unknown binary'} / {request.chunkId}
</p>
</div>
{(approved || rejected) && (
<button
type="button"
disabled={grantingSandboxId === selectedSandbox.id}
onClick={() => resolvePermissionRequest(selectedSandbox, approved ? 'reject' : 'approve', request.chunkId)}
className={`${rejected ? 'rounded-sm border border-[var(--nvidia-green)] bg-[var(--nvidia-green)] text-black' : 'rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] text-[var(--foreground)]'} px-3 py-2 text-xs font-mono uppercase tracking-wider disabled:opacity-50 max-md:w-full`}
>
{approved ? 'Revoke' : 'Approve'}
</button>
)}
</div>
</div>
)
})}
</div>
</div>
)
if (pending.length === 0) { if (pending.length === 0) {
return ( return (
<>
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 text-xs text-[var(--foreground-dim)]"> <div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 text-xs text-[var(--foreground-dim)]">
No pending network permission requests for this sandbox. No pending network permission requests for this sandbox.
</div> </div>
{renderRecentRules()}
</>
) )
} }
return pending.map((request) => ( return (
<div className="space-y-3">
{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 max-md:flex-col"> <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">
@@ -749,7 +803,10 @@ export default function SandboxList({
</div> </div>
</div> </div>
</div> </div>
)) ))}
{renderRecentRules()}
</div>
)
})()} })()}
<ConfigurationPanel sandboxId={selectedSandbox.id} mode="existing" embedded showHeader={false} /> <ConfigurationPanel sandboxId={selectedSandbox.id} mode="existing" embedded showHeader={false} />
</div> </div>
+14
View File
@@ -86,6 +86,20 @@ export async function verifySandboxMcpBrokerToken(token: string) {
return session return session
} }
export async function revokeSandboxMcpBrokerSession(sandboxId: string) {
const store = await readStore()
const existing = store.sessions[sandboxId]
if (!existing) return null
store.sessions[sandboxId] = {
...existing,
enabled: false,
rotatedAt: new Date().toISOString(),
expiresAt: new Date().toISOString(),
}
await writeStore(store)
return store.sessions[sandboxId]
}
export async function listAllowedBrokerServers(session: SandboxMcpBrokerSession) { export async function listAllowedBrokerServers(session: SandboxMcpBrokerSession) {
const inventory = await listMcpServers() const inventory = await listMcpServers()
return inventory.servers.filter((server) => sandboxCanAccessMcpServer(server, session.sandboxId, session.sandboxName)) return inventory.servers.filter((server) => sandboxCanAccessMcpServer(server, session.sandboxId, session.sandboxName))
+82
View File
@@ -0,0 +1,82 @@
import { execFile } from "node:child_process"
import { promisify } from "node:util"
import { HOST_PATH, OPENSHELL_BIN } from "./hostCommands"
import { resolveSandboxRef } from "./openshellHost"
const execFileAsync = promisify(execFile)
const LOCAL_HOSTNAMES = new Set(["localhost", "127.0.0.1", "0.0.0.0", "host.docker.internal", "host.openshell.internal"])
const FALLBACK_SANDBOX_PROXY_ORIGIN = "http://10.200.0.1:3128"
async function discoverOpenShellDockerGateway() {
const container = process.env.OPEN_SHELL_CONTAINER || "openshell-cluster-nemoclaw"
const { stdout } = await execFileAsync("docker", ["inspect", container], {
env: { ...process.env, PATH: HOST_PATH },
timeout: 5000,
maxBuffer: 1024 * 1024,
})
const [inspect] = JSON.parse(String(stdout)) as Array<{
NetworkSettings?: {
Networks?: Record<string, { Gateway?: string }>
}
}>
const networks = inspect?.NetworkSettings?.Networks || {}
return Object.values(networks).map((network) => network.Gateway).find(Boolean) || null
}
function normalizeProxyOrigin(value: string) {
try {
const proxy = new URL(value)
if (proxy.protocol !== "http:" && proxy.protocol !== "https:") return null
return proxy.toString().replace(/\/+$/, "")
} catch {
return null
}
}
async function runOpenShell(args: string[]) {
const { stdout } = await execFileAsync(OPENSHELL_BIN, args, {
env: {
...process.env,
PATH: HOST_PATH,
OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY || "nemoclaw",
NO_COLOR: "1",
CLICOLOR: "0",
CLICOLOR_FORCE: "0",
TERM: "dumb",
},
timeout: 15000,
maxBuffer: 1024 * 1024,
})
return String(stdout)
}
async function discoverSandboxProxyOrigin(sandboxId: string, sandboxName?: string | null) {
const resolvedName = sandboxName || (await resolveSandboxRef(sandboxId)).name
const script = "printf '%s\\n' \"${HTTP_PROXY:-${http_proxy:-${HTTPS_PROXY:-${https_proxy:-}}}}\""
const output = await runOpenShell(["sandbox", "exec", "-n", resolvedName, "--", "sh", "-lc", script])
return normalizeProxyOrigin(output.trim())
}
export async function brokerBaseUrlForSandbox(
request: Request,
sandbox?: { id: string, name?: string | null },
) {
if (process.env.OPENSHELL_CONTROL_MCP_BROKER_URL) return process.env.OPENSHELL_CONTROL_MCP_BROKER_URL
const origin = new URL(request.url).origin
const publicOrigin = new URL(origin)
if (LOCAL_HOSTNAMES.has(publicOrigin.hostname)) {
const gateway = await discoverOpenShellDockerGateway().catch(() => null)
publicOrigin.hostname = gateway || "host.docker.internal"
}
const hostBrokerUrl = `${publicOrigin.toString().replace(/\/+$/, "")}/api/mcp/broker`
const proxyOrigin = sandbox
? await discoverSandboxProxyOrigin(sandbox.id, sandbox.name).catch(() => null)
: null
if (proxyOrigin) return `${proxyOrigin}/${hostBrokerUrl}`
if (LOCAL_HOSTNAMES.has(new URL(origin).hostname)) return `${FALLBACK_SANDBOX_PROXY_ORIGIN}/${hostBrokerUrl}`
return hostBrokerUrl
}
+19
View File
@@ -85,6 +85,7 @@ export const MCP_SERVER_CATALOG: McpCatalogEntry[] = [
tags: ["web", "utility"], tags: ["web", "utility"],
}, },
] ]
const BASELINE_MCP_SERVER_IDS = ["memory"]
function emptyStore(): StoreShape { function emptyStore(): StoreShape {
return { servers: {} } return { servers: {} }
@@ -164,6 +165,23 @@ async function writeStore(store: StoreShape) {
await writeFile(STORE_PATH, JSON.stringify(store, null, 2), { mode: 0o600 }) await writeFile(STORE_PATH, JSON.stringify(store, null, 2), { mode: 0o600 })
} }
async function ensureBaselineMcpServers(store: StoreShape) {
let changed = false
for (const id of BASELINE_MCP_SERVER_IDS) {
const entry = MCP_SERVER_CATALOG.find((candidate) => candidate.id === id)
if (!entry || store.servers[id]) continue
store.servers[id] = normalizeInstall({
...entry,
source: "catalog",
enabled: true,
accessMode: "disabled",
allowedSandboxIds: [],
})
changed = true
}
if (changed) await writeStore(store)
}
export function buildMcpClientConfig(servers: McpServerInstall[]) { export function buildMcpClientConfig(servers: McpServerInstall[]) {
return { return {
mcpServers: Object.fromEntries( mcpServers: Object.fromEntries(
@@ -195,6 +213,7 @@ export function sandboxCanAccessMcpServer(server: McpServerInstall, sandboxId: s
export async function listMcpServers() { export async function listMcpServers() {
const store = await readStore() const store = await readStore()
await ensureBaselineMcpServers(store)
const servers = Object.values(store.servers).sort((a, b) => a.name.localeCompare(b.name)) const servers = Object.values(store.servers).sort((a, b) => a.name.localeCompare(b.name))
return { return {
catalog: MCP_SERVER_CATALOG, catalog: MCP_SERVER_CATALOG,
+65
View File
@@ -21,6 +21,16 @@ function sanitizeArchiveStem(value: string) {
return value.trim().replace(/[^\w.@:+-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "") || "sandbox" return value.trim().replace(/[^\w.@:+-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "") || "sandbox"
} }
function normalizeRelativeArchivePath(input: string, fallbackFileName: string) {
const raw = input.trim() || fallbackFileName
if (!raw || raw.includes("\0")) throw new Error("relative file path contains unsupported characters")
const normalized = path.posix.normalize(raw).replace(/^\/+/, "")
if (!normalized || normalized === "." || normalized.startsWith("../") || normalized.includes("/../")) {
throw new Error("relative file path must stay inside the uploaded directory")
}
return normalized
}
export function normalizeSandboxPath(input: string, fallbackFileName?: string) { export function normalizeSandboxPath(input: string, fallbackFileName?: string) {
const raw = input.trim() const raw = input.trim()
if (!raw) throw new Error("sandbox path is required") if (!raw) throw new Error("sandbox path is required")
@@ -106,6 +116,31 @@ export async function uploadSandboxFile(sandboxId: string, destinationPath: stri
} }
} }
export async function uploadSandboxFiles(
sandboxId: string,
destinationDirectory: string,
files: Array<{ fileName: string; relativePath: string; payload: Buffer }>
) {
if (files.length === 0) throw new Error("at least one file is required")
const totalBytes = files.reduce((sum, file) => sum + file.payload.byteLength, 0)
if (totalBytes > MAX_FILE_BYTES) {
throw new Error(`directory upload is too large; max transfer size is ${Math.floor(MAX_FILE_BYTES / 1024 / 1024)} MiB`)
}
const uploaded = []
for (const file of files) {
const relativePath = normalizeRelativeArchivePath(file.relativePath, file.fileName)
const targetPath = path.posix.join(destinationDirectory, relativePath)
uploaded.push(await uploadSandboxFile(sandboxId, targetPath, file.fileName, file.payload))
}
return {
sandboxName: uploaded[0]?.sandboxName || await resolveSandboxName(sandboxId),
files: uploaded,
bytes: totalBytes,
}
}
export async function downloadSandboxFile(sandboxId: string, sourcePath: string) { export async function downloadSandboxFile(sandboxId: string, sourcePath: string) {
const sandboxName = await resolveSandboxName(sandboxId) const sandboxName = await resolveSandboxName(sandboxId)
const targetPath = normalizeSandboxPath(sourcePath) const targetPath = normalizeSandboxPath(sourcePath)
@@ -128,6 +163,36 @@ export async function downloadSandboxFile(sandboxId: string, sourcePath: string)
} }
} }
export async function downloadSandboxPath(sandboxId: string, sourcePath: string) {
const sandboxName = await resolveSandboxName(sandboxId)
const targetPath = normalizeSandboxPath(sourcePath)
const typeScript = `if [ -f ${shellQuote(targetPath)} ]; then echo file; elif [ -d ${shellQuote(targetPath)} ]; then echo directory; else exit 1; fi`
const typeResult = await runSandboxExec(sandboxName, typeScript, undefined, 30000)
if (typeResult.code !== 0) throw new Error("sandbox path does not exist or is not readable")
const type = typeResult.stdout.toString("utf8").trim()
if (type === "file") {
return { ...(await downloadSandboxFile(sandboxId, targetPath)), archive: false }
}
const parent = path.posix.dirname(targetPath)
const base = path.posix.basename(targetPath) || "sandbox"
const archiveName = `${sanitizeArchiveStem(base)}.tar.gz`
const result = await runSandboxExec(sandboxName, `tar -C ${shellQuote(parent)} -czf - ${shellQuote(base)}`, undefined, 120000)
if (result.code !== 0) throw new Error(result.stderr || "failed to archive sandbox directory")
if (result.stdout.byteLength > MAX_FILE_BYTES) {
throw new Error(`directory archive is too large; max transfer size is ${Math.floor(MAX_FILE_BYTES / 1024 / 1024)} MiB`)
}
return {
sandboxName,
path: targetPath,
fileName: archiveName,
bytes: result.stdout,
archive: true,
}
}
export type SandboxFileListEntry = { export type SandboxFileListEntry = {
name: string name: string
path: string path: string
+38 -1
View File
@@ -1,4 +1,4 @@
import { rotateSandboxMcpBrokerSession } from "./mcpBrokerStore" import { revokeSandboxMcpBrokerSession, rotateSandboxMcpBrokerSession } from "./mcpBrokerStore"
import { uploadSandboxFile } from "./sandboxFiles" import { uploadSandboxFile } from "./sandboxFiles"
export const SANDBOX_MCP_MANIFEST_PATH = "/sandbox/openshell_control_mcp.md" export const SANDBOX_MCP_MANIFEST_PATH = "/sandbox/openshell_control_mcp.md"
@@ -87,3 +87,40 @@ export async function syncSandboxMcpManifest(
markdown: handoff.markdown, markdown: handoff.markdown,
} }
} }
export async function revokeSandboxMcpManifest(sandbox: SandboxRef) {
const session = await revokeSandboxMcpBrokerSession(sandbox.id)
const now = new Date().toISOString()
const markdown = [
"# OpenShell Control MCP Broker",
"",
`Generated: ${now}`,
`Sandbox: ${sandbox.name || sandbox.id}`,
`Sandbox ID: ${sandbox.id}`,
"",
"MCP access is currently disabled for this sandbox.",
"",
"The previous broker token has been revoked. Ask the operator to enable an MCP server and issue a new broker config if MCP access is needed.",
"",
].join("\n")
const uploaded = await uploadSandboxFile(
sandbox.id,
SANDBOX_MCP_MANIFEST_PATH,
"openshell_control_mcp.md",
Buffer.from(markdown, "utf8"),
)
return {
path: uploaded.path,
sandboxName: uploaded.sandboxName,
bytes: uploaded.bytes,
brokerSession: session ? {
sandboxId: session.sandboxId,
sandboxName: session.sandboxName,
enabled: session.enabled,
rotatedAt: session.rotatedAt,
expiresAt: session.expiresAt,
} : null,
markdown,
}
}
+88
View File
@@ -16,6 +16,13 @@ export type SandboxNetworkRule = {
binaries: string[] binaries: string[]
} }
type BrokerNetworkAction = {
action: "approve" | "reject"
chunkId: string
endpoint: string
status: string
}
function runOpenShell(args: string[], timeout = 60000) { function runOpenShell(args: string[], timeout = 60000) {
return execFileAsync(OPENSHELL_BIN, args, { return execFileAsync(OPENSHELL_BIN, args, {
env: { env: {
@@ -73,6 +80,21 @@ function parseNetworkRules(output: string): SandboxNetworkRule[] {
.filter((rule) => rule.chunkId) .filter((rule) => rule.chunkId)
} }
function brokerEndpointCandidates(brokerBaseUrl: string) {
const parsed = new URL(brokerBaseUrl)
const port = parsed.port || (parsed.protocol === "https:" ? "443" : "80")
const hostPort = `${parsed.hostname}:${port}`
const candidates = new Set([hostPort])
if (parsed.hostname === "host.docker.internal") candidates.add(`0.0.0.0:${port}`)
return candidates
}
function ruleMatchesEndpoints(rule: SandboxNetworkRule, candidates: Set<string>) {
return rule.endpoints.some((endpoint) => candidates.has(endpoint))
|| Array.from(candidates).some((endpoint) => rule.rule.includes(endpoint.replace(/[^a-zA-Z0-9]/g, "_")))
|| Array.from(candidates).some((endpoint) => rule.rationale.includes(endpoint))
}
async function listRulesForStatus(sandboxName: string, status: "pending" | "approved" | "rejected") { async function listRulesForStatus(sandboxName: string, status: "pending" | "approved" | "rejected") {
const { stdout } = await runOpenShell(["rule", "get", "--status", status, sandboxName], 30000) const { stdout } = await runOpenShell(["rule", "get", "--status", status, sandboxName], 30000)
return parseNetworkRules(String(stdout)) return parseNetworkRules(String(stdout))
@@ -121,3 +143,69 @@ export async function resolveSandboxNetworkRule(sandboxId: string, action: strin
feed, feed,
} }
} }
async function probeBrokerEndpoint(sandboxName: string, brokerBaseUrl: string) {
const capabilitiesUrl = `${brokerBaseUrl.replace(/\/+$/, "")}/capabilities`
const script = `curl --noproxy '*' -sS --max-time 5 ${JSON.stringify(capabilitiesUrl)} >/dev/null || true`
await runOpenShell(["sandbox", "exec", "-n", sandboxName, "--", "sh", "-lc", script], 15000).catch(() => null)
}
export async function syncBrokerNetworkAccess(sandboxId: string, brokerBaseUrl: string) {
const resolved = await resolveSandboxRef(sandboxId)
const candidates = brokerEndpointCandidates(brokerBaseUrl)
await probeBrokerEndpoint(resolved.name, brokerBaseUrl)
const pending = await listRulesForStatus(resolved.name, "pending").catch(() => [] as SandboxNetworkRule[])
const matchingPending = pending.filter((rule) => ruleMatchesEndpoints(rule, candidates))
const approved: BrokerNetworkAction[] = []
for (const rule of matchingPending) {
await resolveSandboxNetworkRule(resolved.name, "approve", rule.chunkId)
approved.push({
action: "approve",
chunkId: rule.chunkId,
endpoint: rule.endpoints.find((endpoint) => candidates.has(endpoint)) || Array.from(candidates)[0] || "",
status: rule.status,
})
}
const currentlyApproved = await listRulesForStatus(resolved.name, "approved").catch(() => [] as SandboxNetworkRule[])
return {
sandboxId,
sandboxName: resolved.name,
brokerBaseUrl,
approved,
alreadyApproved: currentlyApproved.filter((rule) => ruleMatchesEndpoints(rule, candidates)).map((rule) => ({
chunkId: rule.chunkId,
endpoints: rule.endpoints,
status: rule.status,
})),
}
}
export async function revokeBrokerNetworkAccess(sandboxId: string, brokerBaseUrl: string) {
const resolved = await resolveSandboxRef(sandboxId)
const candidates = brokerEndpointCandidates(brokerBaseUrl)
const [pending, approved] = await Promise.all([
listRulesForStatus(resolved.name, "pending").catch(() => [] as SandboxNetworkRule[]),
listRulesForStatus(resolved.name, "approved").catch(() => [] as SandboxNetworkRule[]),
])
const matching = [...pending, ...approved].filter((rule) => ruleMatchesEndpoints(rule, candidates))
const rejected: BrokerNetworkAction[] = []
for (const rule of matching) {
await resolveSandboxNetworkRule(resolved.name, "reject", rule.chunkId, "MCP broker access revoked")
rejected.push({
action: "reject",
chunkId: rule.chunkId,
endpoint: rule.endpoints.find((endpoint) => candidates.has(endpoint)) || Array.from(candidates)[0] || "",
status: rule.status,
})
}
return {
sandboxId,
sandboxName: resolved.name,
brokerBaseUrl,
rejected,
}
}
+52 -1
View File
@@ -100,6 +100,55 @@ optional_command() {
fi fi
} }
prepend_user_bin() {
if [[ -n "${HOME:-}" && ":$PATH:" != *":$HOME/.local/bin:"* ]]; then
export PATH="$HOME/.local/bin:$PATH"
fi
}
ensure_npx() {
if command -v npx >/dev/null 2>&1; then
log "npx MCP package runner: $(command -v npx)"
return
fi
log "Installing npx MCP package runner with npm"
npm install -g npx
command -v npx >/dev/null 2>&1 || fail "npx installation completed, but npx is still not on PATH."
log "npx MCP package runner: $(command -v npx)"
}
ensure_uvx() {
prepend_user_bin
if command -v uvx >/dev/null 2>&1; then
log "uvx MCP package runner: $(command -v uvx)"
return
fi
log "Installing uvx MCP package runner"
local installed=0
if command -v python3 >/dev/null 2>&1 && python3 -m pip --version >/dev/null 2>&1; then
if python3 -m pip install --user --upgrade uv; then
installed=1
else
warn "Python pip could not install uv for this user; trying the standalone uv installer."
fi
fi
if [[ "$installed" -ne 1 ]] && command -v curl >/dev/null 2>&1; then
curl -LsSf https://astral.sh/uv/install.sh | sh
installed=1
fi
if [[ "$installed" -ne 1 ]]; then
fail "uvx is required for uvx-based MCP servers. Install Python pip or curl, then rerun the installer."
fi
prepend_user_bin
command -v uvx >/dev/null 2>&1 || fail "uvx installation completed, but uvx is still not on PATH."
log "uvx MCP package runner: $(command -v uvx)"
}
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
@@ -255,6 +304,7 @@ fi
require_command node require_command node
require_command npm require_command npm
require_command docker require_command docker
prepend_user_bin
NODE_MAJOR="$(node_major)" NODE_MAJOR="$(node_major)"
if [[ "$NODE_MAJOR" -lt "$MIN_NODE_MAJOR" ]]; then if [[ "$NODE_MAJOR" -lt "$MIN_NODE_MAJOR" ]]; then
@@ -262,7 +312,8 @@ 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" ensure_npx
ensure_uvx
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."
+11
View File
@@ -13,11 +13,18 @@ const PUBLIC_PATHS = [
"/favicon.svg", "/favicon.svg",
"/favicon-32.png", "/favicon-32.png",
] ]
const BROKER_PATHS = [
"/api/mcp/broker",
]
function isPublicPath(pathname: string) { function isPublicPath(pathname: string) {
return PUBLIC_PATHS.some((path) => pathname === path || pathname.startsWith(`${path}/`)) return PUBLIC_PATHS.some((path) => pathname === path || pathname.startsWith(`${path}/`))
} }
function isBrokerPath(pathname: string) {
return BROKER_PATHS.some((path) => pathname === path || pathname.startsWith(`${path}/`))
}
function isAssetPath(pathname: string) { function isAssetPath(pathname: string) {
return pathname.startsWith("/_next/") || pathname.startsWith("/public/") return pathname.startsWith("/_next/") || pathname.startsWith("/public/")
} }
@@ -97,6 +104,10 @@ export async function middleware(request: NextRequest) {
return withSecurityHeaders(NextResponse.next()) return withSecurityHeaders(NextResponse.next())
} }
if (isBrokerPath(pathname)) {
return withSecurityHeaders(NextResponse.next())
}
if (isPublicPath(pathname)) { if (isPublicPath(pathname)) {
if (pathname === "/login" && await verifySessionCookieValue(request.cookies.get(settings.cookieName)?.value)) { if (pathname === "/login" && await verifySessionCookieValue(request.cookies.get(settings.cookieName)?.value)) {
return withSecurityHeaders(NextResponse.redirect(new URL("/", request.url))) return withSecurityHeaders(NextResponse.redirect(new URL("/", request.url)))
+19 -2
View File
@@ -13,12 +13,14 @@ const registryRoutePath = path.join(root, 'app/api/mcp/registry/route.ts')
const brokerCapabilitiesRoutePath = path.join(root, 'app/api/mcp/broker/capabilities/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 brokerCallRoutePath = path.join(root, 'app/api/mcp/broker/call/route.ts')
const sandboxMcpRoutePath = path.join(root, 'app/api/sandbox/[sandboxId]/mcp/route.ts') const sandboxMcpRoutePath = path.join(root, 'app/api/sandbox/[sandboxId]/mcp/route.ts')
const brokerUrlPath = path.join(root, 'app/lib/mcpBrokerUrl.ts')
const middlewarePath = path.join(root, 'middleware.ts')
const panelPath = path.join(root, 'app/components/McpConfigurationPanel.tsx') const panelPath = path.join(root, 'app/components/McpConfigurationPanel.tsx')
const sidebarPath = path.join(root, 'app/components/Sidebar.tsx') const sidebarPath = path.join(root, 'app/components/Sidebar.tsx')
const sandboxListPath = path.join(root, 'app/components/SandboxList.tsx') const sandboxListPath = path.join(root, 'app/components/SandboxList.tsx')
const pagePath = path.join(root, 'app/page.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([ const [storeSource, brokerStoreSource, brokerClientSource, manifestSource, routeSource, registryRouteSource, brokerCapabilitiesRouteSource, brokerCallRouteSource, sandboxMcpRouteSource, brokerUrlSource, middlewareSource, panelSource, sidebarSource, sandboxListSource, pageSource] = await Promise.all([
readFile(storePath, 'utf8'), readFile(storePath, 'utf8'),
readFile(brokerStorePath, 'utf8'), readFile(brokerStorePath, 'utf8'),
readFile(brokerClientPath, 'utf8'), readFile(brokerClientPath, 'utf8'),
@@ -28,6 +30,8 @@ const [storeSource, brokerStoreSource, brokerClientSource, manifestSource, route
readFile(brokerCapabilitiesRoutePath, 'utf8'), readFile(brokerCapabilitiesRoutePath, 'utf8'),
readFile(brokerCallRoutePath, 'utf8'), readFile(brokerCallRoutePath, 'utf8'),
readFile(sandboxMcpRoutePath, 'utf8'), readFile(sandboxMcpRoutePath, 'utf8'),
readFile(brokerUrlPath, 'utf8'),
readFile(middlewarePath, 'utf8'),
readFile(panelPath, 'utf8'), readFile(panelPath, 'utf8'),
readFile(sidebarPath, 'utf8'), readFile(sidebarPath, 'utf8'),
readFile(sandboxListPath, 'utf8'), readFile(sandboxListPath, 'utf8'),
@@ -37,6 +41,8 @@ const [storeSource, brokerStoreSource, brokerClientSource, manifestSource, route
assert.match(storeSource, /export const MCP_SERVER_CATALOG/, 'MCP store must expose an install catalog') 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, /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, /args:\s*\["blender-mcp"\]/, 'MCP catalog must install BlenderMCP via uvx blender-mcp')
assert.match(storeSource, /BASELINE_MCP_SERVER_IDS = \["memory"\]/, 'MCP dashboard should install Memory as the baseline test server')
assert.match(storeSource, /ensureBaselineMcpServers/, 'MCP store must seed baseline servers into dashboard state')
assert.match(storeSource, /mcp-servers\.json/, 'MCP installs must persist to dashboard state') 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, /accessMode/, 'MCP installs must persist sandbox access mode')
assert.match(storeSource, /allowedSandboxIds/, 'MCP installs must persist allowed sandbox lists') assert.match(storeSource, /allowedSandboxIds/, 'MCP installs must persist allowed sandbox lists')
@@ -59,7 +65,17 @@ assert.match(brokerCapabilitiesRouteSource, /listBrokerServerTools/, 'MCP broker
assert.match(brokerCallRouteSource, /Requested MCP capability is unavailable/, 'MCP broker denied calls must not disclose blocked server names') 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(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 POST/, 'Sandbox MCP route must write the broker handoff')
assert.match(sandboxMcpRouteSource, /action === "revoke"/, 'Sandbox MCP route must revoke broker handoff when MCP access is removed')
assert.match(sandboxMcpRouteSource, /syncBrokerNetworkAccess/, 'Sandbox MCP route must synchronize broker network access when MCP is enabled')
assert.match(sandboxMcpRouteSource, /revokeBrokerNetworkAccess/, 'Sandbox MCP route must remove broker network access when MCP is revoked')
assert.match(sandboxMcpRouteSource, /export async function GET/, 'Sandbox MCP route must preview the broker handoff') assert.match(sandboxMcpRouteSource, /export async function GET/, 'Sandbox MCP route must preview the broker handoff')
assert.match(sandboxMcpRouteSource, /brokerBaseUrlForSandbox/, 'Sandbox MCP broker handoff must build a sandbox-routable broker URL')
assert.match(brokerUrlSource, /discoverOpenShellDockerGateway/, 'Sandbox MCP broker handoff must discover the active OpenShell network gateway')
assert.match(brokerUrlSource, /LOCAL_HOSTNAMES/, 'Sandbox MCP broker handoff must rewrite local-only browser origins')
assert.match(brokerUrlSource, /discoverSandboxProxyOrigin/, 'Sandbox MCP broker handoff must discover each sandbox proxy endpoint')
assert.match(brokerUrlSource, /HTTP_PROXY/, 'Sandbox MCP broker handoff must derive the proxy endpoint from sandbox environment')
assert.match(brokerUrlSource, /FALLBACK_SANDBOX_PROXY_ORIGIN/, 'Sandbox MCP broker handoff may keep a fallback for older OpenShell layouts')
assert.match(middlewareSource, /\/api\/mcp\/broker/, 'MCP broker endpoints must bypass dashboard cookie auth and rely on broker token auth')
assert.match(routeSource, /export async function GET/, 'MCP API must list server configuration') 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, /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, /installMcpServer/, 'MCP API must support installing servers')
@@ -85,7 +101,8 @@ assert.match(panelSource, /Allow Only/, 'MCP security must support allow-list ac
assert.match(panelSource, /Setup Guide/, 'MCP catalog cards should link out to app setup guides') 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(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, /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, /Sync Broker Config/, 'Sandbox MCP access controls must sync broker config')
assert.match(sandboxListSource, /hasOtherMcpAccess/, 'Sandbox MCP access controls must revoke broker config when no MCP servers remain')
assert.match(sandboxListSource, /\/sandbox\/openshell_control_mcp\.md/, 'Sandbox MCP access controls must name the manifest path') 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, /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, /MCP access allowed/, 'Sandbox cards must show a lit MCP access indicator')
+12
View File
@@ -15,6 +15,7 @@ const [
sandboxPermissionsSource, sandboxPermissionsSource,
inferenceSource, inferenceSource,
supportBundleSource, supportBundleSource,
mcpBrokerUrlSource,
] = await Promise.all([ ] = await Promise.all([
readFile(path.join(root, 'install.sh'), 'utf8'), readFile(path.join(root, 'install.sh'), 'utf8'),
readFile(path.join(root, 'app/lib/hostCommands.ts'), 'utf8'), readFile(path.join(root, 'app/lib/hostCommands.ts'), 'utf8'),
@@ -26,6 +27,7 @@ const [
readFile(path.join(root, 'app/lib/sandboxPermissions.ts'), 'utf8'), readFile(path.join(root, 'app/lib/sandboxPermissions.ts'), 'utf8'),
readFile(path.join(root, 'app/api/inference/route.ts'), 'utf8'), readFile(path.join(root, 'app/api/inference/route.ts'), 'utf8'),
readFile(path.join(root, 'app/api/support-bundle/route.ts'), 'utf8'), readFile(path.join(root, 'app/api/support-bundle/route.ts'), 'utf8'),
readFile(path.join(root, 'app/lib/mcpBrokerUrl.ts'), 'utf8'),
]) ])
assert.match(installSource, /find_nemoclaw_bin\(\)/, 'installer must discover NemoClaw CLI') assert.match(installSource, /find_nemoclaw_bin\(\)/, 'installer must discover NemoClaw CLI')
@@ -37,6 +39,11 @@ assert.match(installSource, /set_env "NEMOCLAW_SETUP"/, 'installer must persist
assert.match(installSource, /set_env "NEMOCLAW_BIN"/, 'installer must persist discovered NemoClaw CLI path') assert.match(installSource, /set_env "NEMOCLAW_BIN"/, 'installer must persist discovered NemoClaw CLI path')
assert.match(installSource, /set_env "OPENSHELL_BIN"/, 'installer must persist discovered OpenShell path') assert.match(installSource, /set_env "OPENSHELL_BIN"/, 'installer must persist discovered OpenShell path')
assert.match(installSource, /upsert_env "TERMINAL_SERVER_AUTOSTART" "true"/, 'installer must enable terminal bridge autostart by default') assert.match(installSource, /upsert_env "TERMINAL_SERVER_AUTOSTART" "true"/, 'installer must enable terminal bridge autostart by default')
assert.match(installSource, /ensure_npx\(\)/, 'installer must install or verify npx for stdio MCP servers')
assert.match(installSource, /ensure_uvx\(\)/, 'installer must install or verify uvx for stdio MCP servers')
assert.match(installSource, /python3 -m pip install --user --upgrade uv/, 'installer must support user-scoped uvx installation')
assert.match(installSource, /standalone uv installer/, 'installer must fall back when Python blocks user-scoped uv installs')
assert.match(installSource, /prepend_user_bin\(\)/, 'installer must put ~/.local/bin on PATH for user-scoped MCP runners')
assert.match(hostCommandsSource, /export const HOST_PATH/, 'host command resolution must centralize PATH construction') assert.match(hostCommandsSource, /export const HOST_PATH/, 'host command resolution must centralize PATH construction')
assert.match(hostCommandsSource, /\.nemoclaw\/source\/bin\/nemoclaw\.js/, 'host command resolution must support standard ~/.nemoclaw installs') assert.match(hostCommandsSource, /\.nemoclaw\/source\/bin\/nemoclaw\.js/, 'host command resolution must support standard ~/.nemoclaw installs')
@@ -45,6 +52,11 @@ assert.match(hostCommandsSource, /discoverHomeFiles\("scripts\/setup\.sh"\)/, 'r
assert.match(hostCommandsSource, /discoverHomeFiles\("bin\/nemoclaw\.js"\)/, 'runtime command resolution must scan user home directories for nemoclaw.js') assert.match(hostCommandsSource, /discoverHomeFiles\("bin\/nemoclaw\.js"\)/, 'runtime command resolution must scan user home directories for nemoclaw.js')
assert.match(hostCommandsSource, /export const NEMOCLAW_SETUP_CANDIDATES/, 'runtime command resolution must expose searched setup candidates') assert.match(hostCommandsSource, /export const NEMOCLAW_SETUP_CANDIDATES/, 'runtime command resolution must expose searched setup candidates')
assert.doesNotMatch(hostCommandsSource, /\/Users\/markmckeen|\/home\/nvidia/, 'host command resolution must not bake in developer machine paths') assert.doesNotMatch(hostCommandsSource, /\/Users\/markmckeen|\/home\/nvidia/, 'host command resolution must not bake in developer machine paths')
assert.match(mcpBrokerUrlSource, /discoverOpenShellDockerGateway/, 'MCP broker URL generation must discover the active OpenShell Docker gateway')
assert.match(mcpBrokerUrlSource, /OPEN_SHELL_CONTAINER/, 'MCP broker URL generation must respect the configured cluster container')
assert.match(mcpBrokerUrlSource, /host\.docker\.internal/, 'MCP broker URL generation must keep a fallback for hosts without Docker inspect')
assert.match(mcpBrokerUrlSource, /discoverSandboxProxyOrigin/, 'MCP broker URL generation must discover each sandbox proxy endpoint')
assert.match(mcpBrokerUrlSource, /HTTP_PROXY/, 'MCP broker URL generation must use the sandbox proxy environment when available')
assert.match(createRouteSource, /buildNemoClawCreateCommand\(\)/, 'NemoClaw blueprint create must resolve a current CLI command') assert.match(createRouteSource, /buildNemoClawCreateCommand\(\)/, 'NemoClaw blueprint create must resolve a current CLI command')
assert.match(createRouteSource, /"onboard", "--non-interactive"/, 'NemoClaw blueprint create must use the supported onboard CLI flow') assert.match(createRouteSource, /"onboard", "--non-interactive"/, 'NemoClaw blueprint create must use the supported onboard CLI flow')