diff --git a/app/api/mcp/broker/call/route.ts b/app/api/mcp/broker/call/route.ts
index 643e44c..eddcb1f 100644
--- a/app/api/mcp/broker/call/route.ts
+++ b/app/api/mcp/broker/call/route.ts
@@ -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)
diff --git a/app/api/mcp/broker/mcp/route.ts b/app/api/mcp/broker/mcp/route.ts
new file mode 100644
index 0000000..1e0ad38
--- /dev/null
+++ b/app/api/mcp/broker/mcp/route.ts
@@ -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.",
+ })
+}
diff --git a/app/api/mcp/route.ts b/app/api/mcp/route.ts
index 6443621..ffbfe55 100644
--- a/app/api/mcp/route.ts
+++ b/app/api/mcp/route.ts
@@ -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 })
diff --git a/app/api/sandbox/[sandboxId]/mcp/route.ts b/app/api/sandbox/[sandboxId]/mcp/route.ts
index b01bce7..ad25ccc 100644
--- a/app/api/sandbox/[sandboxId]/mcp/route.ts
+++ b/app/api/sandbox/[sandboxId]/mcp/route.ts
@@ -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"
diff --git a/app/components/McpConfigurationPanel.tsx b/app/components/McpConfigurationPanel.tsx
index 31c6ae6..6283cdd 100644
--- a/app/components/McpConfigurationPanel.tsx
+++ b/app/components/McpConfigurationPanel.tsx
@@ -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) {
diff --git a/app/components/SandboxList.tsx b/app/components/SandboxList.tsx
index 8cc9b13..cbe1422 100644
--- a/app/components/SandboxList.tsx
+++ b/app/components/SandboxList.tsx
@@ -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({
Sandbox Manifest
- Writes /sandbox/openshell_control_mcp.md with broker URL and sandbox token only.
+ Writes /sandbox/openshell_control_mcp.md and configures OpenClaw to use the broker MCP endpoint.
{
+ 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,
+ 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()
+ const refs = new Map()
+ const tools: Record[] = []
+
+ 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],
+ }
+}
diff --git a/app/lib/mcpSandboxAutoSync.ts b/app/lib/mcpSandboxAutoSync.ts
new file mode 100644
index 0000000..352c87f
--- /dev/null
+++ b/app/lib/mcpSandboxAutoSync.ts
@@ -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,
+ 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 {
+ 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
+}
diff --git a/app/lib/sandboxMcpManifest.ts b/app/lib/sandboxMcpManifest.ts
index 579199a..e934874 100644
--- a/app/lib/sandboxMcpManifest.ts
+++ b/app/lib/sandboxMcpManifest.ts
@@ -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,
}
}
diff --git a/app/lib/sandboxOpenClawMcpConfig.ts b/app/lib/sandboxOpenClawMcpConfig.ts
new file mode 100644
index 0000000..d2afe2e
--- /dev/null
+++ b/app/lib/sandboxOpenClawMcpConfig.ts
@@ -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 {
+ 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) {
+ 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 = { ...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,
+ }
+}
diff --git a/tests/mcp-configuration-page-check.mjs b/tests/mcp-configuration-page-check.mjs
index ba54e2b..8c1a14f 100644
--- a/tests/mcp-configuration-page-check.mjs
+++ b/tests/mcp-configuration-page-check.mjs
@@ -7,6 +7,8 @@ const root = process.cwd()
const storePath = path.join(root, 'app/lib/mcpServerStore.ts')
const brokerStorePath = path.join(root, 'app/lib/mcpBrokerStore.ts')
const brokerClientPath = path.join(root, 'app/lib/mcpBrokerClient.ts')
+const brokerProtocolPath = path.join(root, 'app/lib/mcpBrokerProtocol.ts')
+const sandboxAutoSyncPath = path.join(root, 'app/lib/mcpSandboxAutoSync.ts')
const manifestPath = path.join(root, 'app/lib/sandboxMcpManifest.ts')
const privilegedFilesPath = path.join(root, 'app/lib/sandboxPrivilegedFiles.ts')
const routePath = path.join(root, 'app/api/mcp/route.ts')
@@ -21,8 +23,10 @@ const registryStorePath = path.join(root, 'app/lib/mcpRegistryStore.ts')
const inferenceModelPath = path.join(root, 'app/lib/inferenceModel.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 brokerMcpRoutePath = path.join(root, 'app/api/mcp/broker/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 sandboxOpenClawMcpConfigPath = path.join(root, 'app/lib/sandboxOpenClawMcpConfig.ts')
const preflightLibPath = path.join(root, 'app/lib/mcpPreflight.ts')
const preflightRepairLibPath = path.join(root, 'app/lib/mcpPreflightRepair.ts')
const mcpServerSpecsPath = path.join(root, 'mcp_server_specs.md')
@@ -33,10 +37,12 @@ const sidebarPath = path.join(root, 'app/components/Sidebar.tsx')
const sandboxListPath = path.join(root, 'app/components/SandboxList.tsx')
const pagePath = path.join(root, 'app/page.tsx')
-const [storeSource, brokerStoreSource, brokerClientSource, manifestSource, privilegedFilesSource, routeSource, uploadRouteSource, preflightRouteSource, healthRouteSource, registryRouteSource, registriesRouteSource, registriesAssistRouteSource, installAssistRouteSource, registryStoreSource, inferenceModelSource, brokerCapabilitiesRouteSource, brokerCallRouteSource, sandboxMcpRouteSource, brokerUrlSource, preflightLibSource, preflightRepairLibSource, mcpServerSpecsSource, middlewareSource, panelSource, helpSource, sidebarSource, sandboxListSource, pageSource] = await Promise.all([
+const [storeSource, brokerStoreSource, brokerClientSource, brokerProtocolSource, sandboxAutoSyncSource, manifestSource, privilegedFilesSource, routeSource, uploadRouteSource, preflightRouteSource, healthRouteSource, registryRouteSource, registriesRouteSource, registriesAssistRouteSource, installAssistRouteSource, registryStoreSource, inferenceModelSource, brokerCapabilitiesRouteSource, brokerCallRouteSource, brokerMcpRouteSource, sandboxMcpRouteSource, brokerUrlSource, sandboxOpenClawMcpConfigSource, preflightLibSource, preflightRepairLibSource, mcpServerSpecsSource, middlewareSource, panelSource, helpSource, sidebarSource, sandboxListSource, pageSource] = await Promise.all([
readFile(storePath, 'utf8'),
readFile(brokerStorePath, 'utf8'),
readFile(brokerClientPath, 'utf8'),
+ readFile(brokerProtocolPath, 'utf8'),
+ readFile(sandboxAutoSyncPath, 'utf8'),
readFile(manifestPath, 'utf8'),
readFile(privilegedFilesPath, 'utf8'),
readFile(routePath, 'utf8'),
@@ -51,8 +57,10 @@ const [storeSource, brokerStoreSource, brokerClientSource, manifestSource, privi
readFile(inferenceModelPath, 'utf8'),
readFile(brokerCapabilitiesRoutePath, 'utf8'),
readFile(brokerCallRoutePath, 'utf8'),
+ readFile(brokerMcpRoutePath, 'utf8'),
readFile(sandboxMcpRoutePath, 'utf8'),
readFile(brokerUrlPath, 'utf8'),
+ readFile(sandboxOpenClawMcpConfigPath, 'utf8'),
readFile(preflightLibPath, 'utf8'),
readFile(preflightRepairLibPath, 'utf8'),
readFile(mcpServerSpecsPath, 'utf8'),
@@ -82,9 +90,19 @@ assert.match(brokerClientSource, /@modelcontextprotocol\/sdk\/client\/index\.js/
assert.match(brokerClientSource, /StdioClientTransport/, 'MCP broker must support stdio servers')
assert.match(brokerClientSource, /StreamableHTTPClientTransport/, 'MCP broker must support streamable HTTP servers')
assert.match(brokerClientSource, /callBrokerServerTool/, 'MCP broker must forward allowed tool calls')
+assert.match(brokerProtocolSource, /tools\/list/, 'MCP broker protocol adapter must expose an MCP tools/list JSON-RPC method')
+assert.match(brokerProtocolSource, /tools\/call/, 'MCP broker protocol adapter must expose an MCP tools/call JSON-RPC method')
+assert.match(brokerProtocolSource, /listAllowedBrokerServers/, 'MCP broker protocol adapter must reuse broker access policy')
+assert.match(brokerProtocolSource, /reserveToolName/, 'MCP broker protocol adapter must namespace tools by broker server')
+assert.match(sandboxAutoSyncSource, /autoSyncSandboxMcpAccess/, 'MCP access updates must have a server-side sandbox sync helper')
+assert.match(sandboxAutoSyncSource, /syncSandboxMcpManifest/, 'MCP access grants must issue sandbox OpenClaw MCP config')
+assert.match(sandboxAutoSyncSource, /revokeSandboxMcpManifest/, 'MCP access revokes must remove sandbox OpenClaw MCP config when no access remains')
+assert.match(sandboxAutoSyncSource, /changedServerAccessChanged/, 'MCP sandbox auto-sync must target sandboxes touched by the changed server')
assert.match(manifestSource, /openshell_control_mcp\.md/, 'MCP sandbox manifest must use the requested filename')
assert.match(manifestSource, /syncSandboxMcpManifest/, 'MCP sandbox manifest must be syncable into a sandbox')
assert.match(manifestSource, /writeSandboxFilePrivileged/, 'MCP sandbox manifest must use a privileged write path for root-owned /sandbox mounts')
+assert.match(manifestSource, /syncSandboxOpenClawMcpConfig/, 'MCP sandbox manifest sync must also configure OpenClaw MCP')
+assert.match(manifestSource, /\/mcp/, 'MCP sandbox handoff must include the protocol-compatible MCP endpoint')
assert.match(privilegedFilesSource, /kubectl/, 'privileged sandbox file writes must use the OpenShell cluster control path')
assert.doesNotMatch(manifestSource, /allowedServers|renderServer|commandLine/, 'MCP sandbox handoff must not disclose server inventory or launch specs')
assert.match(manifestSource, /control plane enforces/, 'MCP sandbox handoff must explain broker-side enforcement')
@@ -92,23 +110,34 @@ assert.match(brokerCapabilitiesRouteSource, /listAllowedBrokerServers/, 'MCP bro
assert.match(brokerCapabilitiesRouteSource, /listBrokerServerTools/, 'MCP broker capabilities must inspect allowed server tools')
assert.match(brokerCallRouteSource, /Requested MCP capability is unavailable/, 'MCP broker denied calls must not disclose blocked server names')
assert.match(brokerCallRouteSource, /callBrokerServerTool/, 'MCP broker call route must forward allowed calls')
+assert.match(brokerCallRouteSource, /isBrokerMcpJsonRpcBody/, 'Existing broker call route must also accept MCP JSON-RPC payloads')
+assert.match(brokerCallRouteSource, /handleBrokerMcpJsonRpcBody/, 'Existing broker call route must bridge MCP JSON-RPC through broker policy')
+assert.match(brokerMcpRouteSource, /handleBrokerMcpJsonRpcBody/, 'MCP protocol endpoint must use the shared broker protocol adapter')
+assert.match(brokerMcpRouteSource, /readBrokerToken/, 'MCP protocol endpoint must use broker token authentication')
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, /brokerBaseUrlForSandbox/, 'Sandbox MCP broker handoff must build a sandbox-routable broker URL')
+assert.match(sandboxMcpRouteSource, /synced\.openClaw\.path/, 'Sandbox MCP sync response must report the OpenClaw config write')
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(sandboxOpenClawMcpConfigSource, /mcp\.servers = servers/, 'Sandbox MCP sync must write mcp.servers into OpenClaw config')
+assert.match(sandboxOpenClawMcpConfigSource, /streamable-http/, 'OpenClaw MCP broker config must use streamable HTTP transport')
+assert.match(sandboxOpenClawMcpConfigSource, /Authorization: `Bearer \$\{token\}`/, 'OpenClaw MCP broker config must pass the sandbox broker token as bearer auth')
+assert.match(sandboxOpenClawMcpConfigSource, /restartOpenClawGatewayIfRunning/, 'OpenClaw gateway must restart after MCP config changes')
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 POST/, 'MCP API must install and update server configuration')
assert.match(routeSource, /installMcpServer/, 'MCP API must support installing servers')
assert.match(routeSource, /uninstallMcpServer/, 'MCP API must support removing servers')
assert.match(routeSource, /updateMcpServerAccess/, 'MCP API must support access policy updates')
+assert.match(routeSource, /autoSyncSandboxMcpAccess/, 'MCP API access changes must automatically sync affected sandbox OpenClaw MCP config')
+assert.match(routeSource, /sandboxSync/, 'MCP API responses must report automatic sandbox sync results')
assert.match(uploadRouteSource, /request\.formData\(\)/, 'MCP upload API must accept multipart server bundles')
assert.match(uploadRouteSource, /writeDirectoryUpload/, 'MCP upload API must support directory uploads')
assert.match(uploadRouteSource, /writeArchiveUpload/, 'MCP upload API must support archive uploads')
@@ -222,18 +251,16 @@ assert.match(panelSource, /openSecurityServers/, 'MCP security must render insta
assert.match(panelSource, /aria-expanded=\{securityOpen\}/, 'MCP security must render as an accordion')
assert.match(panelSource, /Allow All/, 'MCP security must support allow-all access')
assert.match(panelSource, /Allow Only/, 'MCP security must support allow-list access')
-assert.match(panelSource, /syncSandboxBrokerConfig/, 'MCP configuration grants must sync the sandbox broker config automatically')
-assert.match(panelSource, /\/api\/sandbox\/\$\{encodeURIComponent\(sandbox\.id\)\}\/mcp/, 'MCP configuration grants must call the sandbox MCP sync endpoint')
-assert.match(panelSource, /allowed \|\| hasOtherMcpAccess \? "sync" : "revoke"/, 'MCP configuration revokes must preserve broker config when other MCP access remains')
-assert.match(panelSource, /syncAccessModeChange/, 'MCP availability changes must synchronize sandbox broker policy')
+assert.doesNotMatch(panelSource, /syncSandboxBrokerConfig/, 'MCP configuration grants should rely on server-side sandbox sync instead of duplicate client sync')
+assert.match(panelSource, /syncAccessModeChange/, 'MCP availability changes must update broker policy through the MCP API')
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(helpSource, /MCP Server Health/, 'Help must expose MCP server health checks')
assert.match(helpSource, /\/api\/mcp\/health/, 'Help MCP health check must call the health API')
assert.match(helpSource, /Refresh MCP Health/, 'Help MCP health check must be refreshable')
assert.match(sandboxListSource, /Allowed MCP Server Access/, 'Sandbox page must expose allowed MCP server access accordion')
-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, /Sync Broker Config/, 'Sandbox MCP access controls must keep a manual broker config repair action')
+assert.match(sandboxListSource, /syncMcpManifest/, 'Sandbox MCP access controls must expose manual broker config sync')
assert.match(sandboxListSource, /\/sandbox\/openshell_control_mcp\.md/, 'Sandbox MCP access controls must name the manifest path')
assert.match(sandboxListSource, /sandboxCanAccessMcpServer/, 'Sandbox page must derive MCP access per sandbox')
assert.match(sandboxListSource, /MCP access allowed/, 'Sandbox cards must show a lit MCP access indicator')