Configure sandbox MCP broker access
This commit is contained in:
@@ -5,16 +5,38 @@ import {
|
||||
verifySandboxMcpBrokerToken,
|
||||
} from "@/app/lib/mcpBrokerStore"
|
||||
import { callBrokerServerTool } from "@/app/lib/mcpBrokerClient"
|
||||
import {
|
||||
brokerMcpUnauthorizedError,
|
||||
handleBrokerMcpJsonRpcBody,
|
||||
isBrokerMcpJsonRpcBody,
|
||||
} from "@/app/lib/mcpBrokerProtocol"
|
||||
|
||||
function jsonRpcResponse(payload: unknown, status = 200) {
|
||||
return NextResponse.json(payload, {
|
||||
status,
|
||||
headers: { "Cache-Control": "no-store" },
|
||||
})
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const body = await request.json().catch(() => ({}))
|
||||
const token = readBrokerToken(request)
|
||||
const session = token ? await verifySandboxMcpBrokerToken(token) : null
|
||||
const isMcpJsonRpc = isBrokerMcpJsonRpcBody(body)
|
||||
if (!session) {
|
||||
if (isMcpJsonRpc) return jsonRpcResponse(brokerMcpUnauthorizedError(), 401)
|
||||
return NextResponse.json({ ok: false, error: "MCP broker is unavailable for this sandbox." }, { status: 401 })
|
||||
}
|
||||
|
||||
const body = await request.json().catch(() => ({}))
|
||||
if (isMcpJsonRpc) {
|
||||
const response = await handleBrokerMcpJsonRpcBody(session, body)
|
||||
if (response.body === null) {
|
||||
return new Response(null, { status: response.status, headers: { "Cache-Control": "no-store" } })
|
||||
}
|
||||
return jsonRpcResponse(response.body, response.status)
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import {
|
||||
readBrokerToken,
|
||||
verifySandboxMcpBrokerToken,
|
||||
} from "@/app/lib/mcpBrokerStore"
|
||||
import {
|
||||
brokerMcpUnauthorizedError,
|
||||
handleBrokerMcpJsonRpcBody,
|
||||
MCP_PROTOCOL_VERSION,
|
||||
} from "@/app/lib/mcpBrokerProtocol"
|
||||
|
||||
function jsonRpcResponse(payload: unknown, status = 200) {
|
||||
return NextResponse.json(payload, {
|
||||
status,
|
||||
headers: { "Cache-Control": "no-store" },
|
||||
})
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const parsedBody = await request.json().catch(() => null)
|
||||
const token = readBrokerToken(request)
|
||||
const session = token ? await verifySandboxMcpBrokerToken(token) : null
|
||||
if (!session) {
|
||||
return jsonRpcResponse(brokerMcpUnauthorizedError(), 401)
|
||||
}
|
||||
|
||||
const response = await handleBrokerMcpJsonRpcBody(session, parsedBody)
|
||||
if (response.body === null) {
|
||||
return new Response(null, { status: response.status, headers: { "Cache-Control": "no-store" } })
|
||||
}
|
||||
|
||||
return jsonRpcResponse(response.body, response.status)
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const token = readBrokerToken(request)
|
||||
const session = token ? await verifySandboxMcpBrokerToken(token) : null
|
||||
if (!session) {
|
||||
return jsonRpcResponse(brokerMcpUnauthorizedError(), 401)
|
||||
}
|
||||
return jsonRpcResponse({
|
||||
ok: true,
|
||||
endpoint: "mcp",
|
||||
protocol: MCP_PROTOCOL_VERSION,
|
||||
note: "POST MCP JSON-RPC messages to this endpoint.",
|
||||
})
|
||||
}
|
||||
+28
-10
@@ -6,6 +6,7 @@ import {
|
||||
updateMcpServerAccess,
|
||||
uninstallMcpServer,
|
||||
} from "@/app/lib/mcpServerStore"
|
||||
import { autoSyncSandboxMcpAccess } from "@/app/lib/mcpSandboxAutoSync"
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
@@ -23,29 +24,44 @@ export async function POST(request: Request) {
|
||||
|
||||
if (action === "uninstall") {
|
||||
const serverId = typeof body?.serverId === "string" ? body.serverId : ""
|
||||
return NextResponse.json({ server: await uninstallMcpServer(serverId), ...(await listMcpServers()) })
|
||||
const before = await listMcpServers()
|
||||
const server = await uninstallMcpServer(serverId)
|
||||
const after = await listMcpServers()
|
||||
const sandboxSync = await autoSyncSandboxMcpAccess(request, before.servers, after.servers, [server.id])
|
||||
return NextResponse.json({ server, ...after, sandboxSync })
|
||||
}
|
||||
|
||||
if (action === "enable" || action === "disable") {
|
||||
const serverId = typeof body?.serverId === "string" ? body.serverId : ""
|
||||
const before = await listMcpServers()
|
||||
const server = await setMcpServerEnabled(serverId, action === "enable")
|
||||
const after = await listMcpServers()
|
||||
const sandboxSync = await autoSyncSandboxMcpAccess(request, before.servers, after.servers, [server.id])
|
||||
return NextResponse.json({
|
||||
server: await setMcpServerEnabled(serverId, action === "enable"),
|
||||
...(await listMcpServers()),
|
||||
server,
|
||||
...after,
|
||||
sandboxSync,
|
||||
})
|
||||
}
|
||||
|
||||
if (action === "update-access") {
|
||||
const serverId = typeof body?.serverId === "string" ? body.serverId : ""
|
||||
const before = await listMcpServers()
|
||||
const server = await updateMcpServerAccess(serverId, {
|
||||
enabled: typeof body?.enabled === "boolean" ? body.enabled : undefined,
|
||||
accessMode: body?.accessMode,
|
||||
allowedSandboxIds: Array.isArray(body?.allowedSandboxIds) ? body.allowedSandboxIds : undefined,
|
||||
})
|
||||
const after = await listMcpServers()
|
||||
const sandboxSync = await autoSyncSandboxMcpAccess(request, before.servers, after.servers, [server.id])
|
||||
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()),
|
||||
server,
|
||||
...after,
|
||||
sandboxSync,
|
||||
})
|
||||
}
|
||||
|
||||
const before = await listMcpServers()
|
||||
const server = await installMcpServer({
|
||||
id: body?.id,
|
||||
name: body?.name,
|
||||
@@ -61,8 +77,10 @@ export async function POST(request: Request) {
|
||||
accessMode: body?.accessMode,
|
||||
allowedSandboxIds: body?.allowedSandboxIds,
|
||||
})
|
||||
const after = await listMcpServers()
|
||||
const sandboxSync = await autoSyncSandboxMcpAccess(request, before.servers, after.servers, [server.id])
|
||||
|
||||
return NextResponse.json({ server, ...(await listMcpServers()) })
|
||||
return NextResponse.json({ server, ...after, sandboxSync })
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Failed to update MCP servers"
|
||||
return NextResponse.json({ error: message }, { status: 400 })
|
||||
|
||||
@@ -28,9 +28,12 @@ export async function GET(
|
||||
"",
|
||||
"This preview omits the broker token. Use POST to issue and write a live broker config.",
|
||||
"",
|
||||
`- MCP: \`${brokerUrl}/mcp\``,
|
||||
`- Capabilities: \`${brokerUrl}/capabilities\``,
|
||||
`- Call: \`${brokerUrl}/call\``,
|
||||
"",
|
||||
"OpenClaw will receive an `openshell-control` MCP server entry that uses the MCP endpoint.",
|
||||
"",
|
||||
].join("\n"),
|
||||
})
|
||||
} catch (error) {
|
||||
@@ -74,7 +77,7 @@ export async function POST(
|
||||
sandboxId,
|
||||
synced,
|
||||
network,
|
||||
note: `Issued MCP broker config at ${synced.path}.`,
|
||||
note: `Issued MCP broker config at ${synced.path} and ${synced.openClaw.path}.`,
|
||||
})
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Failed to issue MCP broker config"
|
||||
|
||||
@@ -402,34 +402,12 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
|
||||
current.delete(sandbox.id)
|
||||
current.delete(sandbox.name)
|
||||
if (allowed) current.add(sandbox.id)
|
||||
const hasOtherMcpAccess = servers.some((candidate) => candidate.id !== server.id && sandboxAllowed(candidate, sandbox))
|
||||
return postUpdate({
|
||||
action: "update-access",
|
||||
serverId: server.id,
|
||||
accessMode: "allow_only",
|
||||
allowedSandboxIds: Array.from(current),
|
||||
}, `${server.name} sandbox access updated.`).then((updated) => {
|
||||
if (!updated) return
|
||||
return syncSandboxBrokerConfig(sandbox, allowed || hasOtherMcpAccess ? "sync" : "revoke")
|
||||
})
|
||||
}
|
||||
|
||||
async function syncSandboxBrokerConfig(sandbox: McpSandbox, action: "sync" | "revoke" = "sync") {
|
||||
try {
|
||||
setSaving(true)
|
||||
const response = await fetch(`/api/sandbox/${encodeURIComponent(sandbox.id)}/mcp`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ sandboxName: sandbox.name, action }),
|
||||
})
|
||||
const data = await response.json()
|
||||
if (!response.ok) throw new Error(data.error || "Failed to sync MCP broker config")
|
||||
setMessage(data.note || (action === "revoke" ? `${sandbox.name} MCP broker config revoked.` : `${sandbox.name} MCP broker config synced.`))
|
||||
} catch (error) {
|
||||
setMessage(error instanceof Error ? error.message : "Failed to sync MCP broker config")
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}, `${server.name} sandbox access updated.`)
|
||||
}
|
||||
|
||||
async function syncAccessModeChange(server: McpServerInstall, accessMode: string) {
|
||||
@@ -439,20 +417,6 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
|
||||
accessMode,
|
||||
}, `${server.name} availability updated.`)
|
||||
if (!updated) return
|
||||
|
||||
if (accessMode === "allow_all") {
|
||||
await Promise.all(sandboxes.map((sandbox) => syncSandboxBrokerConfig(sandbox)))
|
||||
return
|
||||
}
|
||||
|
||||
if (accessMode === "disabled") {
|
||||
await Promise.all(sandboxes
|
||||
.filter((sandbox) => sandboxAllowed(server, sandbox))
|
||||
.map((sandbox) => {
|
||||
const hasOtherMcpAccess = servers.some((candidate) => candidate.id !== server.id && sandboxAllowed(candidate, sandbox))
|
||||
return syncSandboxBrokerConfig(sandbox, hasOtherMcpAccess ? "sync" : "revoke")
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
async function setServerEnabled(server: McpServerInstall, enabled: boolean) {
|
||||
@@ -462,12 +426,6 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
|
||||
enabled,
|
||||
}, `${server.name} ${enabled ? "enabled" : "disabled"}.`)
|
||||
if (!updated) return
|
||||
|
||||
const affectedSandboxes = sandboxes.filter((sandbox) => sandboxAllowed(server, sandbox))
|
||||
await Promise.all(affectedSandboxes.map((sandbox) => {
|
||||
const hasOtherMcpAccess = servers.some((candidate) => candidate.id !== server.id && sandboxAllowed(candidate, sandbox))
|
||||
return syncSandboxBrokerConfig(sandbox, enabled || hasOtherMcpAccess ? "sync" : "revoke")
|
||||
}))
|
||||
}
|
||||
|
||||
function editableServerJson(server: McpServerInstall) {
|
||||
|
||||
@@ -305,11 +305,10 @@ export default function SandboxList({
|
||||
enabled: true,
|
||||
accessMode: server.accessMode === 'allow_all' ? 'allow_all' : 'allow_only',
|
||||
allowedSandboxIds: Array.from(current),
|
||||
}, `${server.name} enabled for ${sandbox.name}.`).then(() => syncMcpManifest(sandbox))
|
||||
}, `${server.name} enabled for ${sandbox.name}.`)
|
||||
}
|
||||
|
||||
const revokeMcpForSandbox = (sandbox: SandboxInventoryItem, server: McpServerAccess) => {
|
||||
const hasOtherMcpAccess = mcpServers.some((candidate) => candidate.id !== server.id && sandboxCanAccessMcpServer(sandbox, candidate))
|
||||
const current = new Set(server.allowedSandboxIds)
|
||||
current.delete(sandbox.id)
|
||||
current.delete(sandbox.name)
|
||||
@@ -321,7 +320,7 @@ export default function SandboxList({
|
||||
return updateMcpServerAccess(server, {
|
||||
accessMode: 'allow_only',
|
||||
allowedSandboxIds: Array.from(current),
|
||||
}, `${server.name} revoked from ${sandbox.name}.`).then(() => syncMcpManifest(sandbox, hasOtherMcpAccess ? 'sync' : 'revoke'))
|
||||
}, `${server.name} revoked from ${sandbox.name}.`)
|
||||
}
|
||||
|
||||
const resolvePermissionRequest = async (sandbox: SandboxInventoryItem, action: 'approve' | 'reject', chunkId: string) => {
|
||||
@@ -613,7 +612,7 @@ export default function SandboxList({
|
||||
<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.
|
||||
Writes <span className="font-mono text-[var(--foreground)]">/sandbox/openshell_control_mcp.md</span> and configures OpenClaw to use the broker MCP endpoint.
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
import { callBrokerServerTool, listBrokerServerTools } from "./mcpBrokerClient"
|
||||
import { listAllowedBrokerServers, type SandboxMcpBrokerSession } from "./mcpBrokerStore"
|
||||
import type { McpServerInstall } from "./mcpServerStore"
|
||||
|
||||
export const MCP_PROTOCOL_VERSION = "2024-11-05"
|
||||
const MAX_TOOL_NAME_LENGTH = 128
|
||||
|
||||
type JsonRpcId = string | number | null
|
||||
type JsonRpcMessage = {
|
||||
jsonrpc?: string
|
||||
id?: JsonRpcId
|
||||
method?: string
|
||||
params?: unknown
|
||||
}
|
||||
|
||||
type BrokerToolRef = {
|
||||
server: McpServerInstall
|
||||
originalToolName: string
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function hasJsonRpcId(message: JsonRpcMessage) {
|
||||
return Object.hasOwn(message, "id")
|
||||
}
|
||||
|
||||
export function isBrokerMcpJsonRpcBody(value: unknown) {
|
||||
if (Array.isArray(value)) return true
|
||||
return isRecord(value) && (
|
||||
value.jsonrpc === "2.0" ||
|
||||
typeof value.method === "string" ||
|
||||
Object.hasOwn(value, "id")
|
||||
)
|
||||
}
|
||||
|
||||
function responseFor(id: JsonRpcId, result: unknown) {
|
||||
return { jsonrpc: "2.0", id, result }
|
||||
}
|
||||
|
||||
export function brokerMcpErrorFor(id: JsonRpcId, code: number, message: string, data?: unknown) {
|
||||
return {
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
error: {
|
||||
code,
|
||||
message,
|
||||
...(data === undefined ? {} : { data }),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export function brokerMcpUnauthorizedError() {
|
||||
return brokerMcpErrorFor(null, -32001, "MCP broker is unavailable for this sandbox.")
|
||||
}
|
||||
|
||||
function safeToolNamePart(value: string, fallback: string) {
|
||||
const cleaned = value
|
||||
.trim()
|
||||
.replace(/[^A-Za-z0-9_-]+/g, "_")
|
||||
.replace(/_+/g, "_")
|
||||
.replace(/^_+|_+$/g, "")
|
||||
return cleaned || fallback
|
||||
}
|
||||
|
||||
function reserveToolName(
|
||||
usedNames: Set<string>,
|
||||
serverId: string,
|
||||
toolName: string,
|
||||
) {
|
||||
const serverPart = safeToolNamePart(serverId, "server")
|
||||
const toolPart = safeToolNamePart(toolName, "tool")
|
||||
const base = `${serverPart}__${toolPart}`.slice(0, MAX_TOOL_NAME_LENGTH)
|
||||
let candidate = base
|
||||
let counter = 2
|
||||
while (usedNames.has(candidate.toLowerCase())) {
|
||||
const suffix = `_${counter}`
|
||||
candidate = `${base.slice(0, Math.max(1, MAX_TOOL_NAME_LENGTH - suffix.length))}${suffix}`
|
||||
counter += 1
|
||||
}
|
||||
usedNames.add(candidate.toLowerCase())
|
||||
return candidate
|
||||
}
|
||||
|
||||
async function loadToolCatalog(session: SandboxMcpBrokerSession) {
|
||||
const allowedServers = await listAllowedBrokerServers(session)
|
||||
const usedNames = new Set<string>()
|
||||
const refs = new Map<string, BrokerToolRef>()
|
||||
const tools: Record<string, unknown>[] = []
|
||||
|
||||
for (const server of allowedServers) {
|
||||
const serverTools = await listBrokerServerTools(server)
|
||||
for (const tool of serverTools) {
|
||||
const exposedName = reserveToolName(usedNames, server.id, tool.name)
|
||||
refs.set(exposedName, { server, originalToolName: tool.name })
|
||||
tools.push({
|
||||
name: exposedName,
|
||||
title: tool.title || `${server.name}: ${tool.name}`,
|
||||
description: [server.name, tool.description].filter(Boolean).join(" - "),
|
||||
inputSchema: tool.inputSchema || { type: "object" },
|
||||
...(tool.annotations ? { annotations: tool.annotations } : {}),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return { tools, refs }
|
||||
}
|
||||
|
||||
async function handleBrokerMcpJsonRpcMessage(session: SandboxMcpBrokerSession, message: unknown) {
|
||||
if (!isRecord(message)) return brokerMcpErrorFor(null, -32600, "Invalid Request")
|
||||
|
||||
const request = message as JsonRpcMessage
|
||||
const id = hasJsonRpcId(request) ? request.id ?? null : null
|
||||
const method = typeof request.method === "string" ? request.method : ""
|
||||
const isNotification = !hasJsonRpcId(request)
|
||||
|
||||
try {
|
||||
switch (method) {
|
||||
case "initialize":
|
||||
return isNotification ? null : responseFor(id, {
|
||||
protocolVersion: MCP_PROTOCOL_VERSION,
|
||||
capabilities: {
|
||||
tools: {},
|
||||
},
|
||||
serverInfo: {
|
||||
name: "openshell-control-mcp-broker",
|
||||
version: "0.1.0",
|
||||
},
|
||||
})
|
||||
|
||||
case "notifications/initialized":
|
||||
case "notifications/cancelled":
|
||||
return null
|
||||
|
||||
case "ping":
|
||||
return isNotification ? null : responseFor(id, {})
|
||||
|
||||
case "tools/list": {
|
||||
const catalog = await loadToolCatalog(session)
|
||||
return isNotification ? null : responseFor(id, { tools: catalog.tools })
|
||||
}
|
||||
|
||||
case "tools/call": {
|
||||
const params = isRecord(request.params) ? request.params : {}
|
||||
const name = typeof params.name === "string" ? params.name : ""
|
||||
const toolArguments = isRecord(params.arguments) ? params.arguments : {}
|
||||
if (!name) return isNotification ? null : brokerMcpErrorFor(id, -32602, "Tool name is required.")
|
||||
|
||||
const catalog = await loadToolCatalog(session)
|
||||
const ref = catalog.refs.get(name)
|
||||
if (!ref) {
|
||||
return isNotification ? null : responseFor(id, {
|
||||
content: [{ type: "text", text: "Requested MCP capability is unavailable." }],
|
||||
isError: true,
|
||||
})
|
||||
}
|
||||
|
||||
const result = await callBrokerServerTool(ref.server, ref.originalToolName, toolArguments)
|
||||
return isNotification ? null : responseFor(id, result)
|
||||
}
|
||||
|
||||
case "resources/list":
|
||||
return isNotification ? null : responseFor(id, { resources: [] })
|
||||
|
||||
case "prompts/list":
|
||||
return isNotification ? null : responseFor(id, { prompts: [] })
|
||||
|
||||
default:
|
||||
return isNotification ? null : brokerMcpErrorFor(id, -32601, "Method not found.")
|
||||
}
|
||||
} catch (error) {
|
||||
return isNotification ? null : brokerMcpErrorFor(
|
||||
id,
|
||||
-32000,
|
||||
error instanceof Error ? error.message : "MCP broker request failed.",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export async function handleBrokerMcpJsonRpcBody(
|
||||
session: SandboxMcpBrokerSession,
|
||||
body: unknown,
|
||||
) {
|
||||
const isBatch = Array.isArray(body)
|
||||
const messages = isBatch ? body : [body]
|
||||
const responses = []
|
||||
for (const message of messages) {
|
||||
const response = await handleBrokerMcpJsonRpcMessage(session, message)
|
||||
if (response) responses.push(response)
|
||||
}
|
||||
|
||||
if (responses.length === 0) {
|
||||
return { status: 202, body: null }
|
||||
}
|
||||
|
||||
return {
|
||||
status: 200,
|
||||
body: isBatch ? responses : responses[0],
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import { brokerBaseUrlForSandbox } from "./mcpBrokerUrl"
|
||||
import type { McpServerInstall } from "./mcpServerStore"
|
||||
import { sandboxCanAccessMcpServer } from "./mcpServerStore"
|
||||
import { execOpenShell, resolveSandboxRef } from "./openshellHost"
|
||||
import { revokeSandboxMcpManifest, syncSandboxMcpManifest } from "./sandboxMcpManifest"
|
||||
import { revokeBrokerNetworkAccess, syncBrokerNetworkAccess } from "./sandboxPermissions"
|
||||
|
||||
type SandboxRef = {
|
||||
id: string
|
||||
name: string
|
||||
}
|
||||
|
||||
export type SandboxMcpAutoSyncResult = {
|
||||
sandboxId: string
|
||||
sandboxName: string
|
||||
action: "sync" | "revoke"
|
||||
ok: boolean
|
||||
error?: string
|
||||
}
|
||||
|
||||
function stripAnsi(value: string) {
|
||||
return value.replace(/\u001b\[[0-9;]*m/g, "")
|
||||
}
|
||||
|
||||
function parseOpenShellSandboxNames(output: string) {
|
||||
return output
|
||||
.split(/\r?\n/)
|
||||
.map((entry) => stripAnsi(entry).trim())
|
||||
.filter(
|
||||
(entry) =>
|
||||
entry &&
|
||||
!/^name\s+/i.test(entry) &&
|
||||
!/^[\s\-=]+$/.test(entry) &&
|
||||
!/^no sandboxes found\.?$/i.test(entry),
|
||||
)
|
||||
.map((entry) => entry.split(/\s{2,}/)[0]?.trim())
|
||||
.filter((entry): entry is string => Boolean(entry))
|
||||
}
|
||||
|
||||
async function listLiveSandboxRefs() {
|
||||
const { stdout } = await execOpenShell(["sandbox", "list"])
|
||||
const names = parseOpenShellSandboxNames(stdout)
|
||||
const refs: SandboxRef[] = []
|
||||
|
||||
for (const name of names) {
|
||||
try {
|
||||
const resolved = await resolveSandboxRef(name)
|
||||
refs.push({
|
||||
id: resolved.id || resolved.name,
|
||||
name: resolved.name,
|
||||
})
|
||||
} catch {
|
||||
refs.push({ id: name, name })
|
||||
}
|
||||
}
|
||||
|
||||
return refs
|
||||
}
|
||||
|
||||
function sandboxHasMcpAccess(servers: McpServerInstall[], sandbox: SandboxRef) {
|
||||
return servers.some((server) => sandboxCanAccessMcpServer(server, sandbox.id, sandbox.name))
|
||||
}
|
||||
|
||||
function changedServerAccessChanged(
|
||||
beforeServers: McpServerInstall[],
|
||||
afterServers: McpServerInstall[],
|
||||
changedServerIds: Set<string>,
|
||||
sandbox: SandboxRef,
|
||||
) {
|
||||
for (const serverId of changedServerIds) {
|
||||
const before = beforeServers.find((server) => server.id === serverId)
|
||||
const after = afterServers.find((server) => server.id === serverId)
|
||||
const beforeCanAccess = before ? sandboxCanAccessMcpServer(before, sandbox.id, sandbox.name) : false
|
||||
const afterCanAccess = after ? sandboxCanAccessMcpServer(after, sandbox.id, sandbox.name) : false
|
||||
if (beforeCanAccess !== afterCanAccess) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
async function syncOneSandboxMcp(
|
||||
request: Request,
|
||||
sandbox: SandboxRef,
|
||||
action: "sync" | "revoke",
|
||||
): Promise<SandboxMcpAutoSyncResult> {
|
||||
try {
|
||||
const brokerUrl = await brokerBaseUrlForSandbox(request, sandbox)
|
||||
if (action === "revoke") {
|
||||
await revokeSandboxMcpManifest(sandbox)
|
||||
await revokeBrokerNetworkAccess(sandbox.id, brokerUrl)
|
||||
} else {
|
||||
await syncSandboxMcpManifest(sandbox, { brokerBaseUrl: brokerUrl })
|
||||
await syncBrokerNetworkAccess(sandbox.id, brokerUrl)
|
||||
}
|
||||
|
||||
return {
|
||||
sandboxId: sandbox.id,
|
||||
sandboxName: sandbox.name,
|
||||
action,
|
||||
ok: true,
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
sandboxId: sandbox.id,
|
||||
sandboxName: sandbox.name,
|
||||
action,
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : "Failed to sync sandbox MCP config",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function autoSyncSandboxMcpAccess(
|
||||
request: Request,
|
||||
beforeServers: McpServerInstall[],
|
||||
afterServers: McpServerInstall[],
|
||||
changedServerIds: string[],
|
||||
) {
|
||||
const changed = new Set(changedServerIds.filter(Boolean))
|
||||
if (changed.size === 0) return []
|
||||
|
||||
const sandboxes = await listLiveSandboxRefs().catch(() => [] as SandboxRef[])
|
||||
const results: SandboxMcpAutoSyncResult[] = []
|
||||
|
||||
for (const sandbox of sandboxes) {
|
||||
const beforeHasAccess = sandboxHasMcpAccess(beforeServers, sandbox)
|
||||
const afterHasAccess = sandboxHasMcpAccess(afterServers, sandbox)
|
||||
const changedServerTouchedSandbox = changedServerAccessChanged(beforeServers, afterServers, changed, sandbox)
|
||||
if (!beforeHasAccess && !afterHasAccess && !changedServerTouchedSandbox) continue
|
||||
|
||||
if (afterHasAccess && (!beforeHasAccess || changedServerTouchedSandbox)) {
|
||||
results.push(await syncOneSandboxMcp(request, sandbox, "sync"))
|
||||
} else if (beforeHasAccess && !afterHasAccess) {
|
||||
results.push(await syncOneSandboxMcp(request, sandbox, "revoke"))
|
||||
}
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
@@ -1,5 +1,10 @@
|
||||
import { revokeSandboxMcpBrokerSession, rotateSandboxMcpBrokerSession } from "./mcpBrokerStore"
|
||||
import { resolveSandboxName } from "./sandboxFiles"
|
||||
import {
|
||||
OPENSHELL_CONTROL_MCP_SERVER_NAME,
|
||||
syncSandboxOpenClawMcpConfig,
|
||||
revokeSandboxOpenClawMcpConfig,
|
||||
} from "./sandboxOpenClawMcpConfig"
|
||||
import { writeSandboxFilePrivileged } from "./sandboxPrivilegedFiles"
|
||||
|
||||
export const SANDBOX_MCP_MANIFEST_PATH = "/sandbox/openshell_control_mcp.md"
|
||||
@@ -40,9 +45,14 @@ export async function buildSandboxMcpBrokerHandoff(
|
||||
"",
|
||||
"## Broker Endpoints",
|
||||
"",
|
||||
`- MCP: \`${brokerBaseUrl}/mcp\``,
|
||||
`- Capabilities: \`${brokerBaseUrl}/capabilities\``,
|
||||
`- Call: \`${brokerBaseUrl}/call\``,
|
||||
"",
|
||||
"## OpenClaw",
|
||||
"",
|
||||
`OpenShell Control also configures OpenClaw MCP server \`${OPENSHELL_CONTROL_MCP_SERVER_NAME}\` to use the MCP endpoint above.`,
|
||||
"",
|
||||
"## Authentication",
|
||||
"",
|
||||
"Send this token as an Authorization bearer token or x-openshell-mcp-token header:",
|
||||
@@ -73,6 +83,11 @@ export async function syncSandboxMcpManifest(
|
||||
SANDBOX_MCP_MANIFEST_PATH,
|
||||
Buffer.from(handoff.markdown, "utf8"),
|
||||
)
|
||||
const openClaw = await syncSandboxOpenClawMcpConfig(
|
||||
sandboxName,
|
||||
options.brokerBaseUrl,
|
||||
handoff.token,
|
||||
)
|
||||
|
||||
return {
|
||||
path: uploaded.path,
|
||||
@@ -85,6 +100,7 @@ export async function syncSandboxMcpManifest(
|
||||
rotatedAt: handoff.session.rotatedAt,
|
||||
expiresAt: handoff.session.expiresAt,
|
||||
},
|
||||
openClaw,
|
||||
markdown: handoff.markdown,
|
||||
}
|
||||
}
|
||||
@@ -110,6 +126,7 @@ export async function revokeSandboxMcpManifest(sandbox: SandboxRef) {
|
||||
SANDBOX_MCP_MANIFEST_PATH,
|
||||
Buffer.from(markdown, "utf8"),
|
||||
)
|
||||
const openClaw = await revokeSandboxOpenClawMcpConfig(sandboxName)
|
||||
|
||||
return {
|
||||
path: uploaded.path,
|
||||
@@ -122,6 +139,7 @@ export async function revokeSandboxMcpManifest(sandbox: SandboxRef) {
|
||||
rotatedAt: session.rotatedAt,
|
||||
expiresAt: session.expiresAt,
|
||||
} : null,
|
||||
openClaw,
|
||||
markdown,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
import { spawn } from "node:child_process"
|
||||
import { HOST_PATH } from "./hostCommands"
|
||||
|
||||
export const OPENSHELL_CONTROL_MCP_SERVER_NAME = "openshell-control"
|
||||
export const OPENCLAW_CONFIG_PATH = "/sandbox/.openclaw/openclaw.json"
|
||||
const OPENCLAW_CONFIG_HASH_PATH = "/sandbox/.openclaw/.config-hash"
|
||||
|
||||
const DOCKER_BIN = process.env.DOCKER_BIN || "docker"
|
||||
const OPENSHELL_CLUSTER_CONTAINER = process.env.OPENSHELL_CLUSTER_CONTAINER || "openshell-cluster-nemoclaw"
|
||||
const OPENSHELL_NAMESPACE = process.env.OPENSHELL_SANDBOX_NAMESPACE || "openshell"
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function normalizeBrokerBaseUrl(value: string) {
|
||||
return value.replace(/\/+$/, "")
|
||||
}
|
||||
|
||||
function runDockerKubectl(args: string[], input?: string) {
|
||||
return new Promise<{ stdout: string; stderr: string; code: number | null }>((resolve, reject) => {
|
||||
const child = spawn(DOCKER_BIN, ["exec", ...(input ? ["-i"] : []), OPENSHELL_CLUSTER_CONTAINER, "kubectl", ...args], {
|
||||
env: { ...process.env, PATH: HOST_PATH },
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
})
|
||||
let stdout = ""
|
||||
let stderr = ""
|
||||
child.stdout.on("data", (chunk) => { stdout += String(chunk) })
|
||||
child.stderr.on("data", (chunk) => { stderr += String(chunk) })
|
||||
child.on("error", reject)
|
||||
child.on("close", (code) => resolve({ stdout: stdout.trim(), stderr: stderr.trim(), code }))
|
||||
if (input) child.stdin.end(input)
|
||||
else child.stdin.end()
|
||||
})
|
||||
}
|
||||
|
||||
async function readOpenClawConfig(sandboxName: string) {
|
||||
const result = await runDockerKubectl(["exec", "-n", OPENSHELL_NAMESPACE, sandboxName, "--", "cat", OPENCLAW_CONFIG_PATH])
|
||||
if (result.code !== 0) throw new Error(result.stderr || "Failed to read OpenClaw config")
|
||||
const parsed = JSON.parse(result.stdout)
|
||||
if (!isRecord(parsed)) throw new Error("OpenClaw config must be a JSON object")
|
||||
return parsed
|
||||
}
|
||||
|
||||
async function writeOpenClawConfig(sandboxName: string, config: Record<string, unknown>) {
|
||||
const payload = `${JSON.stringify(config, null, 2)}\n`
|
||||
const script = [
|
||||
`cat > ${OPENCLAW_CONFIG_PATH}`,
|
||||
`chmod 444 ${OPENCLAW_CONFIG_PATH}`,
|
||||
`chown root:root ${OPENCLAW_CONFIG_PATH}`,
|
||||
`sha256sum ${OPENCLAW_CONFIG_PATH} > ${OPENCLAW_CONFIG_HASH_PATH}`,
|
||||
`chmod 444 ${OPENCLAW_CONFIG_HASH_PATH}`,
|
||||
`chown root:root ${OPENCLAW_CONFIG_HASH_PATH}`,
|
||||
].join(" && ")
|
||||
const result = await runDockerKubectl(
|
||||
["exec", "-i", "-n", OPENSHELL_NAMESPACE, sandboxName, "--", "sh", "-lc", script],
|
||||
payload,
|
||||
)
|
||||
if (result.code !== 0) throw new Error(result.stderr || "Failed to write OpenClaw MCP config")
|
||||
}
|
||||
|
||||
async function restartOpenClawGatewayIfRunning(sandboxName: string) {
|
||||
const script = "for p in /proc/[0-9]*; do cmd=$(tr '\\0' ' ' < \"$p/cmdline\" 2>/dev/null || true); case \"$cmd\" in *'openclaw gateway'*) kill \"${p##*/}\" 2>/dev/null || true;; esac; done"
|
||||
await runDockerKubectl(["exec", "-n", OPENSHELL_NAMESPACE, sandboxName, "--", "sh", "-lc", script])
|
||||
}
|
||||
|
||||
export function buildOpenClawMcpServerConfig(brokerBaseUrl: string, token: string) {
|
||||
return {
|
||||
transport: "streamable-http",
|
||||
url: `${normalizeBrokerBaseUrl(brokerBaseUrl)}/mcp`,
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
connectionTimeoutMs: 45000,
|
||||
}
|
||||
}
|
||||
|
||||
export async function syncSandboxOpenClawMcpConfig(
|
||||
sandboxName: string,
|
||||
brokerBaseUrl: string,
|
||||
token: string,
|
||||
) {
|
||||
const current = await readOpenClawConfig(sandboxName)
|
||||
const mcp = isRecord(current.mcp) ? { ...current.mcp } : {}
|
||||
const servers = isRecord(mcp.servers) ? { ...mcp.servers } : {}
|
||||
const serverConfig = buildOpenClawMcpServerConfig(brokerBaseUrl, token)
|
||||
|
||||
servers[OPENSHELL_CONTROL_MCP_SERVER_NAME] = serverConfig
|
||||
mcp.servers = servers
|
||||
|
||||
await writeOpenClawConfig(sandboxName, {
|
||||
...current,
|
||||
mcp,
|
||||
})
|
||||
await restartOpenClawGatewayIfRunning(sandboxName)
|
||||
|
||||
return {
|
||||
path: OPENCLAW_CONFIG_PATH,
|
||||
serverName: OPENSHELL_CONTROL_MCP_SERVER_NAME,
|
||||
transport: serverConfig.transport,
|
||||
url: serverConfig.url,
|
||||
}
|
||||
}
|
||||
|
||||
export async function revokeSandboxOpenClawMcpConfig(sandboxName: string) {
|
||||
const current = await readOpenClawConfig(sandboxName)
|
||||
const mcp = isRecord(current.mcp) ? { ...current.mcp } : {}
|
||||
const servers = isRecord(mcp.servers) ? { ...mcp.servers } : {}
|
||||
delete servers[OPENSHELL_CONTROL_MCP_SERVER_NAME]
|
||||
|
||||
const nextConfig: Record<string, unknown> = { ...current }
|
||||
if (Object.keys(servers).length > 0) {
|
||||
mcp.servers = servers
|
||||
nextConfig.mcp = mcp
|
||||
} else {
|
||||
delete mcp.servers
|
||||
if (Object.keys(mcp).length > 0) nextConfig.mcp = mcp
|
||||
else delete nextConfig.mcp
|
||||
}
|
||||
|
||||
await writeOpenClawConfig(sandboxName, nextConfig)
|
||||
await restartOpenClawGatewayIfRunning(sandboxName)
|
||||
|
||||
return {
|
||||
path: OPENCLAW_CONFIG_PATH,
|
||||
serverName: OPENSHELL_CONTROL_MCP_SERVER_NAME,
|
||||
removed: true,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user