Add inter-sandbox chat MCP server

This commit is contained in:
mmckeen-nv
2026-04-30 08:24:11 -07:00
parent 3ff1a664d7
commit acf4c05aeb
6 changed files with 243 additions and 6 deletions
+17
View File
@@ -2,6 +2,7 @@ import { NextResponse } from "next/server"
import { execFile, spawn } from "node:child_process"
import { promisify } from "node:util"
import { inspectSandbox } from "@/app/lib/openshellHost"
import { repairOpenClawWorkspacePermissions } from "@/app/lib/sandboxPrivilegedFiles"
import {
commandExists,
HOST_PATH,
@@ -437,6 +438,11 @@ export async function POST(request: Request) {
error: "Sandbox readiness polling produced no verification result.",
}
const created = readiness.verified
const workspaceRepair = created ? await repairOpenClawWorkspacePermissions(sandboxName).catch((error) => ({
sandboxName,
path: "/sandbox/.openclaw/workspace",
error: error instanceof Error ? error.message : "Failed to repair OpenClaw workspace permissions",
})) : null
const deviceApproval = created ? await approveOpenClawDeviceRequests(sandboxName) : null
console.log(
`[sandbox/create] request:complete sandbox=${sandboxName} created=${created} readinessAttempts=${readiness.attempts} deviceApproval=${deviceApproval?.approved ?? false} elapsedMs=${elapsedMs(requestStartedAt)}`,
@@ -458,6 +464,7 @@ export async function POST(request: Request) {
attempts: readiness.attempts,
elapsedMs: readiness.elapsedMs,
},
workspaceRepair,
deviceApproval,
stdout: result.stdout,
stderr: result.stderr,
@@ -466,6 +473,8 @@ export async function POST(request: Request) {
enableTailscale
? "NemoClaw blueprint workflow completed with Tailscale-enabled prerequisites. Existing healthy OpenShell gateways are reused before any new gateway start is attempted."
: "NemoClaw blueprint workflow completed in local/default mode. Existing healthy OpenShell gateways are reused before any new gateway start is attempted.",
workspaceRepair && "note" in workspaceRepair ? workspaceRepair.note : false,
workspaceRepair && "error" in workspaceRepair ? `OpenClaw workspace permission repair failed: ${workspaceRepair.error}` : false,
deviceApproval?.note,
)
: "Blueprint command reported success, but the sandbox never reached a ready verification state afterward.",
@@ -500,6 +509,11 @@ export async function POST(request: Request) {
error: "Sandbox readiness polling produced no verification result.",
}
const created = readiness.verified
const workspaceRepair = created ? await repairOpenClawWorkspacePermissions(sandboxName).catch((error) => ({
sandboxName,
path: "/sandbox/.openclaw/workspace",
error: error instanceof Error ? error.message : "Failed to repair OpenClaw workspace permissions",
})) : null
const deviceApproval = created ? await approveOpenClawDeviceRequests(sandboxName) : null
const policyPrepared = Boolean(policy)
console.log(
@@ -526,6 +540,7 @@ export async function POST(request: Request) {
attempts: readiness.attempts,
elapsedMs: readiness.elapsedMs,
},
workspaceRepair,
deviceApproval,
policyPrepared,
note: created
@@ -535,6 +550,8 @@ export async function POST(request: Request) {
: (policyPrepared
? "Custom sandbox created. Policy draft is prepared, but applying it live should be a follow-up action."
: "Custom sandbox created."),
workspaceRepair && "note" in workspaceRepair ? workspaceRepair.note : false,
workspaceRepair && "error" in workspaceRepair ? `OpenClaw workspace permission repair failed: ${workspaceRepair.error}` : false,
deviceApproval?.note,
)
: "Create command started, but the sandbox never reached a ready verification state afterward.",
+20 -5
View File
@@ -64,6 +64,16 @@ export const MCP_SERVER_CATALOG: McpCatalogEntry[] = [
env: {},
tags: ["state", "local"],
},
{
id: "inter-sandbox-chat",
name: "Inter-Sandbox Chat",
summary: "Give allowed sandboxes a shared roomed message board so agents can post updates and read messages from each other through the MCP broker.",
transport: "stdio",
command: "node",
args: [path.join(process.cwd(), "scripts/inter-sandbox-chat-mcp.mjs")],
env: {},
tags: ["chat", "collaboration", "sandbox"],
},
{
id: "git",
name: "Git",
@@ -118,6 +128,10 @@ function normalizeTransport(value: unknown): McpTransport {
return value === "http" ? "http" : "stdio"
}
function withoutUndefined<T extends Record<string, unknown>>(input: T): Partial<T> {
return Object.fromEntries(Object.entries(input).filter(([, value]) => value !== undefined)) as Partial<T>
}
function normalizeInstall(input: Partial<McpServerInstall>, existing?: McpServerInstall | null): McpServerInstall {
const name = typeof input.name === "string" && input.name.trim() ? input.name.trim() : existing?.name || "MCP Server"
const id = slugify(typeof input.id === "string" && input.id.trim() ? input.id : existing?.id || name)
@@ -224,16 +238,17 @@ export async function listMcpServers() {
export async function installMcpServer(input: Partial<McpServerInstall>) {
const store = await readStore()
const fromCatalog = typeof input.id === "string"
? MCP_SERVER_CATALOG.find((entry) => entry.id === input.id)
const cleanInput = withoutUndefined(input as Record<string, unknown>) as Partial<McpServerInstall>
const fromCatalog = typeof cleanInput.id === "string"
? MCP_SERVER_CATALOG.find((entry) => entry.id === cleanInput.id)
: null
const next = normalizeInstall(
{
...fromCatalog,
...input,
source: input.source || (fromCatalog ? "catalog" : "custom"),
...cleanInput,
source: cleanInput.source || (fromCatalog ? "catalog" : "custom"),
},
typeof input.id === "string" ? store.servers[slugify(input.id)] : null,
typeof cleanInput.id === "string" ? store.servers[slugify(cleanInput.id)] : null,
)
store.servers[next.id] = next
await writeStore(store)
+35
View File
@@ -49,3 +49,38 @@ export async function writeSandboxFilePrivileged(
bytes: payload.byteLength,
}
}
export async function repairOpenClawWorkspacePermissions(sandboxName: string) {
const mutableDirs = [
"agents",
"extensions",
"workspace",
"skills",
"hooks",
"identity",
"devices",
"canvas",
"cron",
"memory",
"logs",
"credentials",
"sandbox",
"telegram",
]
const script = [
`for dir in ${mutableDirs.map(shellQuote).join(" ")}; do target="/sandbox/.openclaw-data/$dir"; link="/sandbox/.openclaw/$dir"; mkdir -p "$target"; if [ -d "$link" ] && [ ! -L "$link" ]; then cp -a "$link/." "$target/" 2>/dev/null || true; rm -rf "$link"; fi; ln -sfn "$target" "$link"; done`,
`chown -R sandbox:sandbox /sandbox/.openclaw-data 2>/dev/null || chown -R 998:998 /sandbox/.openclaw-data`,
`for dir in ${mutableDirs.map(shellQuote).join(" ")}; do chmod 0775 "/sandbox/.openclaw-data/$dir"; done`,
].join(" && ")
const result = await runDockerKubectl(
["exec", "-n", OPENSHELL_NAMESPACE, sandboxName, "--", "sh", "-lc", script],
)
if (result.code !== 0) throw new Error(result.stderr || "failed to repair OpenClaw mutable paths")
return {
sandboxName,
path: "/sandbox/.openclaw",
target: "/sandbox/.openclaw-data",
mutableDirs,
note: "Repaired OpenClaw mutable paths so AGENTS.md, session lock, and agent state writes resolve into writable .openclaw-data storage.",
}
}
+148
View File
@@ -0,0 +1,148 @@
#!/usr/bin/env node
import { mkdir, readFile, writeFile } from "node:fs/promises"
import os from "node:os"
import path from "node:path"
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
import { z } from "zod"
const STORE_DIR = process.env.NEMOCLAW_DASHBOARD_STATE_DIR || path.join(os.homedir(), ".nemoclaw-dashboard")
const STORE_PATH = process.env.INTER_SANDBOX_CHAT_STORE || path.join(STORE_DIR, "inter-sandbox-chat.json")
const MAX_MESSAGES_PER_ROOM = Number.parseInt(process.env.INTER_SANDBOX_CHAT_ROOM_LIMIT || "500", 10)
const MAX_MESSAGE_LENGTH = Number.parseInt(process.env.INTER_SANDBOX_CHAT_MESSAGE_LIMIT || "8000", 10)
function nowIso() {
return new Date().toISOString()
}
function cleanRoom(value) {
const room = String(value || "lobby")
.trim()
.toLowerCase()
.replace(/[^a-z0-9._-]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 80)
return room || "lobby"
}
function cleanText(value, fallback = "") {
return String(value ?? fallback).trim()
}
async function readStore() {
try {
const raw = await readFile(STORE_PATH, "utf8")
const parsed = JSON.parse(raw)
return parsed && typeof parsed === "object" && parsed.rooms && typeof parsed.rooms === "object"
? parsed
: { rooms: {} }
} catch {
return { rooms: {} }
}
}
async function writeStore(store) {
await mkdir(path.dirname(STORE_PATH), { recursive: true, mode: 0o700 })
await writeFile(STORE_PATH, `${JSON.stringify(store, null, 2)}\n`, { mode: 0o600 })
}
function asText(payload) {
return {
content: [
{
type: "text",
text: typeof payload === "string" ? payload : JSON.stringify(payload, null, 2),
},
],
}
}
const server = new McpServer({
name: "inter-sandbox-chat",
version: "0.1.0",
})
server.registerTool(
"post_message",
{
title: "Post Message",
description: "Post a message into an inter-sandbox chat room. Use a stable sender name such as the sandbox name.",
inputSchema: {
room: z.string().default("lobby").describe("Chat room name. Defaults to lobby."),
sender: z.string().default("anonymous-sandbox").describe("Sender name, usually the sandbox or agent name."),
message: z.string().min(1).max(MAX_MESSAGE_LENGTH).describe("Message text to share with other sandboxes."),
},
},
async ({ room, sender, message }) => {
const store = await readStore()
const roomId = cleanRoom(room)
const senderName = cleanText(sender, "anonymous-sandbox").slice(0, 120) || "anonymous-sandbox"
const text = cleanText(message).slice(0, MAX_MESSAGE_LENGTH)
if (!text) return asText({ ok: false, error: "message is required" })
const messages = Array.isArray(store.rooms[roomId]?.messages) ? store.rooms[roomId].messages : []
const entry = {
id: `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`,
at: nowIso(),
room: roomId,
sender: senderName,
message: text,
}
store.rooms[roomId] = {
updatedAt: entry.at,
messages: [...messages, entry].slice(-Math.max(1, MAX_MESSAGES_PER_ROOM)),
}
await writeStore(store)
return asText({ ok: true, room: roomId, message: entry })
},
)
server.registerTool(
"read_messages",
{
title: "Read Messages",
description: "Read recent messages from an inter-sandbox chat room.",
inputSchema: {
room: z.string().default("lobby").describe("Chat room name. Defaults to lobby."),
afterId: z.string().optional().describe("Only return messages after this message id."),
limit: z.number().int().min(1).max(100).default(50).describe("Maximum number of messages to return."),
},
},
async ({ room, afterId, limit }) => {
const store = await readStore()
const roomId = cleanRoom(room)
const messages = Array.isArray(store.rooms[roomId]?.messages) ? store.rooms[roomId].messages : []
const start = afterId ? messages.findIndex((message) => message.id === afterId) + 1 : 0
const selected = messages.slice(Math.max(0, start)).slice(-limit)
return asText({ ok: true, room: roomId, count: selected.length, messages: selected })
},
)
server.registerTool(
"list_rooms",
{
title: "List Rooms",
description: "List inter-sandbox chat rooms that currently have messages.",
inputSchema: {
includeEmpty: z.boolean().default(false).describe("Reserved for compatibility; rooms are created when messages are posted."),
},
},
async () => {
const store = await readStore()
const rooms = Object.entries(store.rooms)
.map(([room, value]) => ({
room,
updatedAt: value?.updatedAt || null,
messageCount: Array.isArray(value?.messages) ? value.messages.length : 0,
latestMessageId: Array.isArray(value?.messages) && value.messages.length > 0
? value.messages[value.messages.length - 1].id
: null,
}))
.sort((a, b) => String(b.updatedAt || "").localeCompare(String(a.updatedAt || "")))
return asText({ ok: true, rooms })
},
)
const transport = new StdioServerTransport()
await server.connect(transport)
+11 -1
View File
@@ -36,8 +36,9 @@ const helpPath = path.join(root, 'app/components/HelpPanel.tsx')
const sidebarPath = path.join(root, 'app/components/Sidebar.tsx')
const sandboxListPath = path.join(root, 'app/components/SandboxList.tsx')
const pagePath = path.join(root, 'app/page.tsx')
const interSandboxChatPath = path.join(root, 'scripts/inter-sandbox-chat-mcp.mjs')
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([
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, interSandboxChatSource] = await Promise.all([
readFile(storePath, 'utf8'),
readFile(brokerStorePath, 'utf8'),
readFile(brokerClientPath, 'utf8'),
@@ -70,16 +71,21 @@ const [storeSource, brokerStoreSource, brokerClientSource, brokerProtocolSource,
readFile(sidebarPath, 'utf8'),
readFile(sandboxListPath, 'utf8'),
readFile(pagePath, 'utf8'),
readFile(interSandboxChatPath, 'utf8'),
])
assert.match(storeSource, /export const MCP_SERVER_CATALOG/, 'MCP store must expose an install catalog')
assert.match(storeSource, /blendermcp\.org/, 'MCP catalog must include the requested BlenderMCP site')
assert.match(storeSource, /args:\s*\["blender-mcp"\]/, 'MCP catalog must install BlenderMCP via uvx blender-mcp')
assert.match(storeSource, /id: "inter-sandbox-chat"/, 'MCP catalog must include Inter-Sandbox Chat')
assert.match(storeSource, /Inter-Sandbox Chat/, 'MCP catalog must expose the Inter-Sandbox Chat display name')
assert.match(storeSource, /inter-sandbox-chat-mcp\.mjs/, 'MCP catalog must launch the local Inter-Sandbox Chat server')
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, /accessMode/, 'MCP installs must persist sandbox access mode')
assert.match(storeSource, /allowedSandboxIds/, 'MCP installs must persist allowed sandbox lists')
assert.match(storeSource, /withoutUndefined/, 'MCP catalog installs must not let omitted API fields erase preset command definitions')
assert.match(storeSource, /existing\?\.accessMode \|\| "disabled"/, 'MCP server access should default to disabled for sandboxes')
assert.match(storeSource, /export function buildMcpClientConfig/, 'MCP store must export client config JSON')
assert.match(storeSource, /mcpServers/, 'MCP client config must use the common mcpServers shape')
@@ -90,6 +96,10 @@ 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(interSandboxChatSource, /post_message/, 'Inter-Sandbox Chat MCP server must let agents post messages')
assert.match(interSandboxChatSource, /read_messages/, 'Inter-Sandbox Chat MCP server must let agents read messages')
assert.match(interSandboxChatSource, /list_rooms/, 'Inter-Sandbox Chat MCP server must let agents discover rooms')
assert.match(interSandboxChatSource, /inter-sandbox-chat\.json/, 'Inter-Sandbox Chat MCP server must persist chat state in dashboard storage')
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')
+12
View File
@@ -16,6 +16,7 @@ const sandboxInferenceApplyLibPath = path.join(root, 'app/lib/sandboxInferenceAp
const sandboxInferenceStorePath = path.join(root, 'app/lib/sandboxInferenceStore.ts')
const sandboxRestartRoutePath = path.join(root, 'app/api/sandbox/[sandboxId]/restart/route.ts')
const gatewayRepairRoutePath = path.join(root, 'app/api/openshell/gateway/repair/route.ts')
const sandboxPrivilegedFilesPath = path.join(root, 'app/lib/sandboxPrivilegedFiles.ts')
const hookPath = path.join(root, 'app/hooks/useSandboxInventory.ts')
const pagePath = path.join(root, 'app/page.tsx')
const configPanelPath = path.join(root, 'app/components/ConfigurationPanel.tsx')
@@ -37,6 +38,7 @@ const sandboxInferenceApplyLibSource = await readFile(sandboxInferenceApplyLibPa
const sandboxInferenceStoreSource = await readFile(sandboxInferenceStorePath, 'utf8')
const sandboxRestartRouteSource = await readFile(sandboxRestartRoutePath, 'utf8')
const gatewayRepairRouteSource = await readFile(gatewayRepairRoutePath, 'utf8')
const sandboxPrivilegedFilesSource = await readFile(sandboxPrivilegedFilesPath, 'utf8')
const hookSource = await readFile(hookPath, 'utf8')
const pageSource = await readFile(pagePath, 'utf8')
const configPanelSource = await readFile(configPanelPath, 'utf8')
@@ -62,6 +64,16 @@ assert.match(createRouteSource, /NEMOCLAW_EXPERIMENTAL = "1"/, 'blueprint create
assert.match(createRouteSource, /NEMOCLAW_PROVIDER = "vllm"/, 'blueprint create must support the vLLM onboarding provider')
assert.match(createRouteSource, /NEMOCLAW_PROVIDER = "nim-local"/, 'blueprint create must support the NVIDIA NIM onboarding provider')
assert.match(createRouteSource, /NEMOCLAW_PROVIDER_KEY = apiKey/, 'blueprint create must pass NVIDIA API keys through provider env without changing NemoClaw')
assert.match(createRouteSource, /repairOpenClawWorkspacePermissions/, 'sandbox create must repair OpenClaw workspace permissions after readiness')
assert.match(createRouteSource, /workspaceRepair/, 'sandbox create response must report OpenClaw workspace permission repair status')
assert.match(sandboxPrivilegedFilesSource, /"workspace"/, 'workspace repair must target the OpenClaw workspace directory')
assert.match(sandboxPrivilegedFilesSource, /\/sandbox\/\.openclaw-data\/\$dir/, 'workspace repair must use the policy-writable OpenClaw data tree')
assert.match(sandboxPrivilegedFilesSource, /ln -sfn/, 'workspace repair must link the OpenClaw workspace path into writable storage')
assert.match(sandboxPrivilegedFilesSource, /chown -R sandbox:sandbox \/sandbox\/\.openclaw-data/, 'workspace repair must make the writable OpenClaw data tree owned by the sandbox user')
assert.match(sandboxPrivilegedFilesSource, /AGENTS\.md/, 'workspace repair note must document the AGENTS.md permission failure it prevents')
assert.match(sandboxPrivilegedFilesSource, /"agents"/, 'workspace repair must target the OpenClaw agent directory so sessions are writable through .openclaw-data')
assert.match(sandboxPrivilegedFilesSource, /"agents"[\s\S]*"workspace"[\s\S]*"memory"/, 'workspace repair must cover NemoClaw expected OpenClaw mutable symlink directories')
assert.match(sandboxPrivilegedFilesSource, /sessions\.json\.lock|session lock/, 'workspace repair note must document the sessions.json.lock permission failure it prevents')
assert.match(hookSource, /type RefreshOptions = \{\s*force\?: boolean\s*\}/, 'inventory refresh must accept a force option')
assert.match(hookSource, /!refreshOptions\?\.force && inFlightRef\.current/, 'forced inventory refresh must bypass existing in-flight reads')