Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
feat: add MCP screenshots and live activity
Rahmana89436cae827
diff --git a/.env.example b/.env.exampleindex da6b0f4c..b1c9aab7 100644--- a/.env.example+++ b/.env.example@@ -201,3 +201,10 @@ OS_SESSION_SECRET=# Where clients/codes/tokens live. Default ~/.mso/mcp.json (0600). Only sha256 of# each code and token is ever written.# OS_MCP_STORE=/home/you/.mso/mcp.json+# Optional live MCP activity log shown in Assistant → MCP. Default+# ~/.mso/mcp-activity.log. This is separate from the forensic audit trail and+# records tool lifecycle (started/completed/failed), including bounded reads.+# OS_MCP_ACTIVITY_LOG=/home/you/.mso/mcp-activity.log+# Internal loopback origin used by the read-only `screen_capture` MCP tool. The+# implementation refuses non-loopback values. Default http://127.0.0.1:4005.+# OS_SCREENSHOT_ORIGIN=http://127.0.0.1:4005diff --git a/app/api/mcp/activity/route.ts b/app/api/mcp/activity/route.tsnew file mode 100644index 00000000..157cd31f--- /dev/null+++ b/app/api/mcp/activity/route.ts@@ -0,0 +1,12 @@+import { NextResponse } from "next/server";+import { verifyAuth } from "@/lib/agent/server";+import { readMcpActivity } from "@/lib/mcp/activity";++export const dynamic = "force-dynamic";++export async function GET(req: Request) {+ if (!(await verifyAuth(req))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ const q = new URL(req.url).searchParams;+ const limit = Math.min(Math.max(Number(q.get("limit") ?? 80) || 80, 1), 200);+ return NextResponse.json({ entries: await readMcpActivity(limit) });+}diff --git a/bin/mso b/bin/msoindex 3c39f46f..221aed1a 100755--- a/bin/mso+++ b/bin/mso@@ -56,7 +56,7 @@# models * Model catalog: list | test# skills [name] Skill catalog the assistant sees; with a name, its SKILL.md# changelog What shipped, newest first (same text Settings → About shows)-# mcp * MCP bearer tokens: list | revoke <id> | revoke all+# mcp * MCP tokens + live activity: list | activity [n] | revoke <id> | revoke all# oauth <prov> * Provider sign-in (device code): start | poll# audit [n] [prefix] Audit trail, newest first (writes/exec/auth; reads are not logged)# stock <query> [page] Stock-image search (Unsplash key optional, Openverse fallback)@@ -246,7 +246,7 @@ U_memory="memory list|add <text>|rm <id>"U_config="config show|set <json>|rm <provider>"U_prefs="prefs show|set <json>"U_models="models list|test"-U_mcp="mcp list|revoke <id>|revoke all"+U_mcp="mcp list|activity [n]|revoke <id>|revoke all"U_oauth="oauth <provider> start|poll e.g. mso oauth openai start"U_audit="audit [n] [prefix] e.g. mso audit 20 exec."U_crud="crud list <dir> | get <path> | set <path> <cmd k=v…|text> | del <path> | cmds"@@ -460,7 +460,8 @@ case "$cmd" in# ── MCP tokens (the bearers that let ChatGPT et al. drive this host) ─────mcp)case "${1:-list}" in- list) jget "/api/mcp/tokens" ;;+ list) jget "/api/mcp/tokens" ;;+ activity) jget "/api/mcp/activity?limit=${2:-80}" ;;revoke) [ -n "${2-}" ] || die "usage: mso mcp revoke <id|all> (ids: mso mcp list)"jdel "/api/mcp/tokens?id=$(enc "$2")" ;;*) die "usage: mso $U_mcp" ;;diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex dcb70552..38758893 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -6,6 +6,10 @@ this is the *what*, and it is what Settings → About shows as “What's new”.## 2026-08-19+**Added**++- add MCP screenshots and live activity+**Fixed**- use official agent logosdiff --git a/docs/CLI.md b/docs/CLI.mdindex 4b6b7384..0ce9a37b 100644--- a/docs/CLI.md+++ b/docs/CLI.md@@ -90,7 +90,7 @@ Commands:models * Model catalog: list | testskills [name] Skill catalog the assistant sees; with a name, its SKILL.mdchangelog What shipped, newest first (same text Settings → About shows)- mcp * MCP bearer tokens: list | revoke <id> | revoke all+ mcp * MCP tokens + live activity: list | activity [n] | revoke <id> | revoke alloauth <prov> * Provider sign-in (device code): start | pollaudit [n] [prefix] Audit trail, newest first (writes/exec/auth; reads are not logged)stock <query> [page] Stock-image search (Unsplash key optional, Openverse fallback)diff --git a/frontend/slices/assistant/app.tsx b/frontend/slices/assistant/app.tsxindex 768718f0..7b22c66e 100644--- a/frontend/slices/assistant/app.tsx+++ b/frontend/slices/assistant/app.tsx@@ -16,8 +16,9 @@ import { ChatPanel, type ChatHandle } from "./components/chat-panel";import { ThreadList } from "./components/thread-list";import { LibraryGrid } from "./components/library-grid";import { SkillForm } from "./components/skill-form";+import { McpActivityView } from "./components/mcp-activity-view";-type Tab = "chat" | "agents" | "skills" | "automations";+type Tab = "chat" | "agents" | "skills" | "automations" | "mcp";type FormState =| { kind: "skill"; item?: Skill }| { kind: "agent"; item?: Agent }@@ -29,6 +30,7 @@ const TABS: [Tab, string][] = [["agents", "Agents"],["skills", "Skills"],["automations", "Automations"],+ ["mcp", "MCP"],];// Alfa: tabbed assistant. Chat keeps the real Claude stream; the other tabs@@ -152,6 +154,8 @@ export default function Assistant() {onNew={() => setForm({ kind: "automation" })}onEdit={(it) => setForm({ kind: "automation", item: it })}/>+ ) : tab === "mcp" ? (+ <McpActivityView />) : null}</AppFrame>);diff --git a/frontend/slices/assistant/components/mcp-activity-view.tsx b/frontend/slices/assistant/components/mcp-activity-view.tsxnew file mode 100644index 00000000..2d66fab6--- /dev/null+++ b/frontend/slices/assistant/components/mcp-activity-view.tsx@@ -0,0 +1,114 @@+"use client";++import { useCallback, useEffect, useMemo, useState } from "react";+import { Activity, Camera, CheckCircle2, CircleDashed, ShieldAlert, XCircle } from "lucide-react";+import { Button } from "@/components/ui/button";++export type McpActivityRow = {+ id: string;+ ts: string;+ actor?: string | null;+ tool: string;+ state: "started" | "completed" | "failed" | "denied" | "rate_limited";+ scope?: string;+ target?: string;+ durationMs?: number;+ detail?: string;+};++const stateMeta = {+ started: { label: "running", Icon: CircleDashed, cls: "text-info" },+ completed: { label: "done", Icon: CheckCircle2, cls: "text-success" },+ failed: { label: "failed", Icon: XCircle, cls: "text-destructive" },+ denied: { label: "denied", Icon: ShieldAlert, cls: "text-warning" },+ rate_limited: { label: "limited", Icon: ShieldAlert, cls: "text-warning" },+} as const;++export function McpActivityView() {+ const [entries, setEntries] = useState<McpActivityRow[]>([]);+ const [paused, setPaused] = useState(false);++ const load = useCallback(() => {+ fetch("/api/mcp/activity?limit=160", { cache: "no-store" })+ .then((r) => (r.ok ? r.json() : Promise.reject(new Error(String(r.status)))))+ .then((d: { entries?: McpActivityRow[] }) => setEntries(d.entries ?? []))+ .catch(() => undefined);+ }, []);++ useEffect(() => {+ load();+ if (paused) return;+ const timer = window.setInterval(load, 1000);+ return () => window.clearInterval(timer);+ }, [load, paused]);++ // The log writes one row at start and one at completion. Newest-first means the+ // first row for each id is the current state; collapse the pair for a readable+ // live feed instead of showing every tool twice.+ const rows = useMemo(() => {+ const seen = new Set<string>();+ return entries.filter((e) => {+ if (seen.has(e.id)) return false;+ seen.add(e.id);+ return true;+ }).slice(0, 80);+ }, [entries]);+ const running = rows.filter((r) => r.state === "started").length;++ return (+ <div className="flex h-full min-h-0 flex-col bg-background">+ <div className="flex shrink-0 items-center gap-2 border-b border-border px-3 py-2">+ <Activity className="size-4" />+ <div className="min-w-0 flex-1">+ <p className="text-xs font-semibold">MCP Activity</p>+ <p className="text-[10px] text-muted-foreground">+ {running ? `${running} tool call${running === 1 ? "" : "s"} running now` : "Live tool-call trail from connected AI clients"}+ </p>+ </div>+ <span className="flex items-center gap-1 rounded-full bg-secondary px-2 py-1 text-[10px] text-muted-foreground">+ <span className={`size-1.5 rounded-full ${paused ? "bg-muted-foreground" : "bg-success animate-pulse"}`} />+ {paused ? "Paused" : "Live"}+ </span>+ <Button variant="ghost" size="sm" className="h-8 text-[11px]" onClick={() => setPaused((v) => !v)}>+ {paused ? "Resume" : "Pause"}+ </Button>+ </div>++ <div className="min-h-0 flex-1 overflow-auto p-3">+ {rows.length === 0 ? (+ <div className="grid h-full place-items-center text-center text-xs text-muted-foreground">+ <div>+ <Camera className="mx-auto mb-2 size-7 opacity-60" />+ No MCP activity yet. Ask ChatGPT to check the VPS or capture the MSO screen.+ </div>+ </div>+ ) : (+ <ul className="space-y-1.5">+ {rows.map((row) => {+ const meta = stateMeta[row.state];+ const Icon = meta.Icon;+ return (+ <li key={row.id} className="flex items-start gap-2 rounded-lg border border-border/70 bg-card/50 px-2.5 py-2">+ <Icon className={`mt-0.5 size-3.5 shrink-0 ${meta.cls} ${row.state === "started" ? "animate-spin" : ""}`} />+ <div className="min-w-0 flex-1">+ <div className="flex items-baseline gap-1.5">+ <code className="truncate font-mono text-[11px] font-medium">{row.tool}</code>+ <span className={`shrink-0 text-[10px] ${meta.cls}`}>{meta.label}</span>+ {row.durationMs != null ? <span className="shrink-0 text-[10px] text-muted-foreground">{row.durationMs} ms</span> : null}+ </div>+ {row.target || row.detail ? (+ <p className="truncate font-mono text-[10px] text-muted-foreground">{row.target ?? row.detail}</p>+ ) : null}+ </div>+ <time className="shrink-0 text-[9px] text-muted-foreground">+ {new Date(row.ts).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" })}+ </time>+ </li>+ );+ })}+ </ul>+ )}+ </div>+ </div>+ );+}diff --git a/frontend/slices/os-settings/components/mcp-section.tsx b/frontend/slices/os-settings/components/mcp-section.tsxindex f04ee5bc..0a508719 100644--- a/frontend/slices/os-settings/components/mcp-section.tsx+++ b/frontend/slices/os-settings/components/mcp-section.tsx@@ -173,8 +173,7 @@ export function McpSection() {))}</ul><p className="pt-1.5 text-[11px] text-muted-foreground">- Reads are not logged (bounded and high-volume). Writes, deletes, commands and- refused-for-scope attempts are. Full trail: <code className="font-mono">mso audit</code>.+ This forensic trail still records privileged mutations and denials. The Assistant → MCP tab adds a separate live activity stream for all tool calls, including reads. Full forensic trail: <code className="font-mono">mso audit</code>.</p></div>)}diff --git a/lib/host/index.ts b/lib/host/index.tsindex 9657e407..551291a3 100644--- a/lib/host/index.ts+++ b/lib/host/index.ts@@ -10,6 +10,8 @@ export type { MultipartPart } from "./multipart";export { runCommand } from "./exec";export { openPty, attachPty, writePty, resizePty, closePty, hasPty } from "./pty";export { stats, processes } from "./sys";+export { captureMsoScreen } from "./screenshot";+export type { ScreenshotShell, ScreenshotResult } from "./screenshot";export { audit, readAuditTail } from "./audit";export type { AuditAction, AuditEntry, AuditRecord } from "./audit";export { rateLimited } from "./rate-limit";diff --git a/lib/host/screenshot.ts b/lib/host/screenshot.tsnew file mode 100644index 00000000..a2202989--- /dev/null+++ b/lib/host/screenshot.ts@@ -0,0 +1,191 @@+import { spawn, type ChildProcess } from "child_process";+import { promises as fs } from "fs";+import os from "os";+import path from "path";+import { listDevices } from "@/lib/auth/device-store";+import { signSession, MIN_SECRET_LEN } from "@/lib/auth/session";++export type ScreenshotShell = "macos" | "windows" | "dashboard";++export interface ScreenshotResult {+ mimeType: "image/png";+ data: string;+ width: number;+ height: number;+ shell: ScreenshotShell;+}++type CdpMessage = { id?: number; result?: unknown; error?: { message?: string }; method?: string; params?: unknown };++class CdpClient {+ private next = 1;+ private pending = new Map<number, { resolve: (v: unknown) => void; reject: (e: Error) => void }>();+ constructor(private ws: WebSocket) {+ ws.addEventListener("message", (event) => {+ const raw = typeof event.data === "string" ? event.data : String(event.data);+ let msg: CdpMessage;+ try { msg = JSON.parse(raw) as CdpMessage; } catch { return; }+ if (msg.id == null) return;+ const p = this.pending.get(msg.id);+ if (!p) return;+ this.pending.delete(msg.id);+ if (msg.error) p.reject(new Error(msg.error.message ?? "CDP error"));+ else p.resolve(msg.result);+ });+ }++ call<T = unknown>(method: string, params: Record<string, unknown> = {}): Promise<T> {+ const id = this.next++;+ return new Promise<T>((resolve, reject) => {+ const timer = setTimeout(() => {+ this.pending.delete(id);+ reject(new Error(`CDP timeout: ${method}`));+ }, 12_000);+ this.pending.set(id, {+ resolve: (v) => { clearTimeout(timer); resolve(v as T); },+ reject: (e) => { clearTimeout(timer); reject(e); },+ });+ this.ws.send(JSON.stringify({ id, method, params }));+ });+ }+}++function clamp(n: number | undefined, min: number, max: number, fallback: number): number {+ if (!Number.isFinite(n)) return fallback;+ return Math.min(Math.max(Math.round(n as number), min), max);+}++async function waitForFile(file: string, ms = 8_000): Promise<string> {+ const started = Date.now();+ while (Date.now() - started < ms) {+ const raw = await fs.readFile(file, "utf8").catch(() => "");+ if (raw.trim()) return raw;+ await new Promise((r) => setTimeout(r, 80));+ }+ throw new Error("Chrome did not expose its DevTools port");+}++async function openWs(url: string): Promise<WebSocket> {+ const ws = new WebSocket(url);+ await new Promise<void>((resolve, reject) => {+ const timer = setTimeout(() => reject(new Error("CDP websocket timeout")), 8_000);+ ws.addEventListener("open", () => { clearTimeout(timer); resolve(); }, { once: true });+ ws.addEventListener("error", () => { clearTimeout(timer); reject(new Error("CDP websocket failed")); }, { once: true });+ });+ return ws;+}++async function approvedDeviceId(): Promise<string> {+ const store = await listDevices();+ const candidates = Object.entries(store.approved)+ .sort(([, a], [, b]) => (b.lastSeen ?? b.approvedAt) - (a.lastSeen ?? a.approvedAt));+ if (!candidates.length) throw new Error("No approved MSO device exists; approve a browser first");+ return candidates[0][0];+}++function internalOrigin(): string {+ const raw = process.env.OS_SCREENSHOT_ORIGIN?.trim() || "http://127.0.0.1:4005";+ if (!/^http:\/\/(?:127\.0\.0\.1|localhost):\d+$/.test(raw)) {+ throw new Error("OS_SCREENSHOT_ORIGIN must be loopback http://127.0.0.1:<port> or localhost");+ }+ return raw;+}++export async function captureMsoScreen(opts?: {+ shell?: ScreenshotShell;+ width?: number;+ height?: number;+}): Promise<ScreenshotResult> {+ const shell: ScreenshotShell = opts?.shell && ["macos", "windows", "dashboard"].includes(opts.shell)+ ? opts.shell+ : "macos";+ const width = clamp(opts?.width, 900, 1920, 1440);+ const height = clamp(opts?.height, 600, 1200, 900);+ const secret = process.env.OS_SESSION_SECRET ?? "";+ if (secret.length < MIN_SECRET_LEN) throw new Error("OS_SESSION_SECRET is not configured strongly enough");+ const deviceId = await approvedDeviceId();+ const now = Date.now();+ const session = signSession({ issued_at: now, expires_at: now + 5 * 60_000, device_id: deviceId }, secret);+ const origin = internalOrigin();+ const profile = await fs.mkdtemp(path.join(os.tmpdir(), "mso-shot-"));+ let chrome: ChildProcess | undefined;+ let ws: WebSocket | undefined;++ try {+ chrome = spawn("/usr/bin/google-chrome", [+ "--headless=new",+ "--no-sandbox",+ "--disable-gpu",+ "--disable-dev-shm-usage",+ "--disable-background-networking",+ "--disable-extensions",+ "--disable-sync",+ "--hide-scrollbars",+ "--no-first-run",+ "--no-default-browser-check",+ "--remote-debugging-port=0",+ `--user-data-dir=${profile}`,+ "about:blank",+ ], { stdio: "ignore" });++ const portInfo = await waitForFile(path.join(profile, "DevToolsActivePort"));+ const [port] = portInfo.trim().split(/\r?\n/);+ const targets = await fetch(`http://127.0.0.1:${port}/json/list`).then((r) => r.json()) as Array<{+ type: string;+ webSocketDebuggerUrl?: string;+ }>;+ const target = targets.find((t) => t.type === "page" && t.webSocketDebuggerUrl);+ if (!target?.webSocketDebuggerUrl) throw new Error("Chrome page target unavailable");+ ws = await openWs(target.webSocketDebuggerUrl);+ const cdp = new CdpClient(ws);++ await cdp.call("Page.enable");+ await cdp.call("Runtime.enable");+ await cdp.call("Network.enable");+ await cdp.call("Emulation.setDeviceMetricsOverride", {+ width, height, deviceScaleFactor: 1, mobile: false,+ screenWidth: width, screenHeight: height,+ });+ const cookie = await cdp.call<{ success?: boolean }>("Network.setCookie", {+ name: "session",+ value: session,+ url: origin,+ path: "/",+ httpOnly: true,+ secure: false,+ sameSite: "Strict",+ });+ if (cookie.success === false) throw new Error("Could not seed screenshot session cookie");++ const shellPrefs = JSON.stringify({ desktop: shell, mobile: "ios" });+ await cdp.call("Page.addScriptToEvaluateOnNewDocument", {+ source: `try { localStorage.setItem('sv:shell', ${JSON.stringify(shellPrefs)}); } catch {}`,+ });+ await cdp.call("Page.navigate", { url: `${origin}/` });++ const deadline = Date.now() + 10_000;+ let ready = false;+ while (Date.now() < deadline) {+ const r = await cdp.call<{ result?: { value?: boolean } }>("Runtime.evaluate", {+ expression: `Boolean(document.querySelector('#main-content[data-shell="${shell}"]'))`,+ returnByValue: true,+ }).catch(() => ({ result: { value: false } }));+ if (r.result?.value) { ready = true; break; }+ await new Promise((resolve) => setTimeout(resolve, 140));+ }+ if (!ready) throw new Error(`MSO shell did not become ready for screenshot (${shell})`);+ await new Promise((resolve) => setTimeout(resolve, 650));++ const shot = await cdp.call<{ data: string }>("Page.captureScreenshot", {+ format: "png",+ fromSurface: true,+ captureBeyondViewport: false,+ });+ if (!shot.data) throw new Error("Chrome returned an empty screenshot");+ return { mimeType: "image/png", data: shot.data, width, height, shell };+ } finally {+ try { ws?.close(); } catch { /* noop */ }+ try { chrome?.kill("SIGTERM"); } catch { /* noop */ }+ await fs.rm(profile, { recursive: true, force: true }).catch(() => undefined);+ }+}diff --git a/lib/mcp/activity.test.ts b/lib/mcp/activity.test.tsnew file mode 100644index 00000000..9607bba8--- /dev/null+++ b/lib/mcp/activity.test.ts@@ -0,0 +1,26 @@+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { promises as fs } from "fs";+import os from "os";+import path from "path";++const dir = await fs.mkdtemp(path.join(os.tmpdir(), "mso-mcp-activity-"));+process.env.OS_MCP_ACTIVITY_LOG = path.join(dir, "activity.log");+const { activityTarget, readMcpActivity, recordMcpActivity } = await import("./activity");++describe("MCP activity stream", () => {+ beforeAll(async () => { await fs.rm(process.env.OS_MCP_ACTIVITY_LOG!, { force: true }); });+ afterAll(async () => { await fs.rm(dir, { recursive: true, force: true }); });++ it("never serializes fs_write content into the activity target", () => {+ expect(activityTarget({ path: "/tmp/note.txt", content: "super secret body" })).toBe("/tmp/note.txt");+ expect(activityTarget({ content: "super secret body" })).toBeUndefined();+ });++ it("collates started/completed rows newest-first with one correlation id", async () => {+ await recordMcpActivity({ id: "a", tool: "sys_stats", state: "started", scope: "read" });+ await recordMcpActivity({ id: "a", tool: "sys_stats", state: "completed", scope: "read", durationMs: 12 });+ const rows = await readMcpActivity(10);+ expect(rows[0]).toMatchObject({ id: "a", state: "completed", durationMs: 12 });+ expect(rows[1]).toMatchObject({ id: "a", state: "started" });+ });+});diff --git a/lib/mcp/activity.ts b/lib/mcp/activity.tsnew file mode 100644index 00000000..0b5d1d0b--- /dev/null+++ b/lib/mcp/activity.ts@@ -0,0 +1,80 @@+import { promises as fs } from "fs";+import os from "os";+import path from "path";+import { randomUUID } from "crypto";++export type McpActivityState = "started" | "completed" | "failed" | "denied" | "rate_limited";++export interface McpActivityEntry {+ id: string;+ ts: string;+ actor?: string | null;+ tool: string;+ state: McpActivityState;+ scope?: string;+ target?: string;+ durationMs?: number;+ detail?: string;+}++function activityPath(): string {+ const env = process.env.OS_MCP_ACTIVITY_LOG;+ if (env && env.trim()) return env.replace(/^~(?=$|\/)/, os.homedir());+ return path.join(os.homedir(), ".mso", "mcp-activity.log");+}++function trunc(v: string | undefined, max = 180): string | undefined {+ if (!v) return undefined;+ return v.length > max ? v.slice(0, max) + "…" : v;+}++let chain: Promise<void> = Promise.resolve();++export function newActivityId(): string {+ return randomUUID();+}++export function activityTarget(args: Record<string, unknown>): string | undefined {+ // Never serialize fs_write.content or arbitrary payloads. Prefer the one field+ // that explains what the tool is acting on without leaking the body.+ for (const key of ["path", "id", "query", "from", "command", "on"] as const) {+ const v = args[key];+ if (typeof v === "string" && v) return trunc(v);+ if (typeof v === "boolean") return String(v);+ }+ return undefined;+}++export function recordMcpActivity(entry: Omit<McpActivityEntry, "ts"> & { ts?: string }): Promise<void> {+ if (process.env.VITEST && !process.env.OS_MCP_ACTIVITY_LOG) return Promise.resolve();+ const line = JSON.stringify({+ ...entry,+ ts: entry.ts ?? new Date().toISOString(),+ target: trunc(entry.target),+ detail: trunc(entry.detail, 220),+ }) + "\n";+ chain = chain.then(async () => {+ const file = activityPath();+ try {+ await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });+ await fs.appendFile(file, line, { mode: 0o600 });+ } catch (e) {+ console.error("[mcp-activity] write failed:", e instanceof Error ? e.message : e);+ }+ });+ return chain;+}++export async function readMcpActivity(limit = 80): Promise<McpActivityEntry[]> {+ const raw = await fs.readFile(activityPath(), "utf8").catch(() => "");+ return raw+ .split("\n")+ .filter(Boolean)+ .slice(-800)+ .map((line) => {+ try { return JSON.parse(line) as McpActivityEntry; } catch { return null; }+ })+ .filter((v): v is McpActivityEntry => Boolean(v?.id && v?.tool && v?.state))+ .slice(-Math.min(Math.max(limit, 1), 200))+ .reverse();+}diff --git a/lib/mcp/dispatch.test.ts b/lib/mcp/dispatch.test.tsindex 069d38cd..fb63ebd5 100644--- a/lib/mcp/dispatch.test.ts+++ b/lib/mcp/dispatch.test.ts@@ -98,6 +98,28 @@ describe("tools/call enforces scope even when the tool was never listed", () =>expect(r.error).toBeUndefined();expect((r.result as { isError?: boolean }).isError).toBe(true);});++ it("supports direct MCP image content for visual tools", async () => {+ const tool = TOOLS.find((t) => t.name === "screen_capture");+ expect(tool).toBeTruthy();+ // Do not launch Chrome in the unit suite; temporarily replace the handler so+ // this test only locks the dispatcher response shape.+ const original = tool!.run;+ tool!.run = async () => ({+ __mcpDirect: true,+ content: [+ { type: "image", data: "aGVsbG8=", mimeType: "image/png" },+ { type: "text", text: "shot" },+ ],+ });+ try {+ const r = await dispatch(call("screen_capture"), "read", "mcp:test");+ const content = (r.result as { content: Array<{ type: string }> }).content;+ expect(content.map((c) => c.type)).toEqual(["image", "text"]);+ } finally {+ tool!.run = original;+ }+ });});describe("catalog hygiene", () => {diff --git a/lib/mcp/dispatch.ts b/lib/mcp/dispatch.tsindex 93227327..bd64255d 100644--- a/lib/mcp/dispatch.ts+++ b/lib/mcp/dispatch.ts@@ -1,5 +1,7 @@import { audit, rateLimited } from "@/lib/host";import { TOOLS, TOOLS_BY_NAME } from "./tools";+import { isMcpDirectResult } from "./tool-kit";+import { activityTarget, newActivityId, recordMcpActivity } from "./activity";import { allows, type Scope } from "./scope";// JSON-RPC 2.0 dispatch for the MCP server. No SDK: the surface is initialize,@@ -73,6 +75,7 @@ export async function dispatch(req: RpcRequest, scope: Scope, actor?: string): P// reaching for exec_run is what a prompt-injected model looks like from// the outside, and it is the only place that signal is visible.void audit({ action: "mcp.denied", actor, target: name, ok: false, detail: `scope ${scope} < ${tool.scope}` });+ void recordMcpActivity({ id: newActivityId(), actor, tool: name, state: "denied", scope, target: activityTarget(args), detail: `scope ${scope} < ${tool.scope}` });return ok(id, {content: [{ type: "text", text: `error: this token holds scope "${scope}"; ${name} needs "${tool.scope}". Mint a new token in mso Settings → MCP.` }],isError: true,@@ -89,6 +92,7 @@ export async function dispatch(req: RpcRequest, scope: Scope, actor?: string): Pconst suffix = tool.limit.keyArg ? String(args[tool.limit.keyArg] ?? "") : (actor ?? "mcp");if (rateLimited(`${tool.limit.key}:${suffix}`, tool.limit.max, tool.limit.windowMs)) {void audit({ action: "mcp.denied", actor, target: name, ok: false, detail: "rate limited" });+ void recordMcpActivity({ id: newActivityId(), actor, tool: name, state: "rate_limited", scope, target: activityTarget(args), detail: "rate limited" });return ok(id, {content: [{ type: "text", text: `error: ${name} is rate limited (${tool.limit.max} per ${Math.round(tool.limit.windowMs / 1000)}s). Wait and retry.` }],isError: true,@@ -102,6 +106,10 @@ export async function dispatch(req: RpcRequest, scope: Scope, actor?: string): P// what it did first. Reads stay unaudited, same rule the routes follow.const trail = tool.audit;const target = trail?.targetArg != null ? String(args[trail.targetArg] ?? "") : undefined;+ const activityId = newActivityId();+ const activityStarted = Date.now();+ const activityTgt = activityTarget(args);+ void recordMcpActivity({ id: activityId, actor, tool: name, state: "started", scope, target: activityTgt });try {const result = await tool.run(args);if (trail) {@@ -112,6 +120,8 @@ export async function dispatch(req: RpcRequest, scope: Scope, actor?: string): Pconst o = trail.outcome?.(result);void audit({ action: o?.action ?? trail.action, actor, target, ok: o?.ok ?? true, detail: o?.detail, meta: { via: "mcp", scope } });}+ void recordMcpActivity({ id: activityId, actor, tool: name, state: "completed", scope, target: activityTgt, durationMs: Date.now() - activityStarted });+ if (isMcpDirectResult(result)) return ok(id, { content: result.content, ...(result.isError ? { isError: true } : {}) });return ok(id, { content: [{ type: "text", text: typeof result === "string" ? result : JSON.stringify(result) }] });} catch (e) {// A handler failure stays INSIDE result with isError, never as a JSON-RPC@@ -119,6 +129,7 @@ export async function dispatch(req: RpcRequest, scope: Scope, actor?: string): P// person sees the model give up with no reason shown.const msg = e instanceof Error ? e.message : String(e);if (trail) void audit({ action: trail.action, actor, target, ok: false, detail: msg.slice(0, 200), meta: { via: "mcp", scope } });+ void recordMcpActivity({ id: activityId, actor, tool: name, state: "failed", scope, target: activityTgt, durationMs: Date.now() - activityStarted, detail: msg.slice(0, 220) });return ok(id, { content: [{ type: "text", text: "error: " + msg.slice(0, 500) }], isError: true });}}diff --git a/lib/mcp/parity.test.ts b/lib/mcp/parity.test.tsindex 4f41e87a..b5096374 100644--- a/lib/mcp/parity.test.ts+++ b/lib/mcp/parity.test.ts@@ -34,7 +34,9 @@ const ALFA_ONLY: Record<string, string> = {"memory.forget": "same store; an MCP client has its own memory",};-const MCP_ONLY: Record<string, string> = {};+const MCP_ONLY: Record<string, string> = {+ "screen.capture": "external MCP clients need visual proof of the rendered OS; in-shell Alfa already runs inside that browser UI",+};describe("Alfa ↔ MCP capability parity", () => {const alfa = new Set(HOST_TOOLS.map((t) => capability(t.name)));@@ -89,11 +91,16 @@ describe("MCP rate limits mirror the routes", () => {"fs.write": 120, "fs.mkdir": 120, "fs.move": 120, "fs.copy": 60,"fs.delete": 60, "exec": 60, "managed-app": 12, "camoufox": 12,};+ const MCP_NATIVE_LIMITS: Record<string, number> = {+ // screen_capture has no HTTP route by design; it exists only for connected+ // MCP clients and is expensive enough to deserve a much smaller bucket.+ "screen.capture": 10,+ };for (const t of TOOLS) {if (!t.limit) continue;- const route = ROUTE_LIMITS[t.limit.key];- expect(route, `${t.name} limits on key "${t.limit.key}", which no route uses`).toBeDefined();- expect(t.limit.max, `${t.name} allows more than its route`).toBeLessThanOrEqual(route);+ const authority = ROUTE_LIMITS[t.limit.key] ?? MCP_NATIVE_LIMITS[t.limit.key];+ expect(authority, `${t.name} limits on unknown key "${t.limit.key}"`).toBeDefined();+ expect(t.limit.max, `${t.name} exceeds its limit authority`).toBeLessThanOrEqual(authority);}});});diff --git a/lib/mcp/tool-kit.ts b/lib/mcp/tool-kit.tsindex bacc63b6..4a1bf1d5 100644--- a/lib/mcp/tool-kit.ts+++ b/lib/mcp/tool-kit.ts@@ -8,6 +8,25 @@ import type { Scope } from "./scope";// catastrophic-command filter in exec.ts. That is the whole reason this file is// thin: a tool that reimplemented an operation would reimplement its guard too.++export type McpContent =+ | { type: "text"; text: string }+ | { type: "image"; data: string; mimeType: string };++export interface McpDirectResult {+ __mcpDirect: true;+ content: McpContent[];+ isError?: boolean;+}++export function mcpDirect(content: McpContent[], isError = false): McpDirectResult {+ return { __mcpDirect: true, content, ...(isError ? { isError: true } : {}) };+}++export function isMcpDirectResult(value: unknown): value is McpDirectResult {+ return Boolean(value && typeof value === "object" && (value as McpDirectResult).__mcpDirect === true);+}+export interface McpTool {name: string;description: string;diff --git a/lib/mcp/tools-read.ts b/lib/mcp/tools-read.tsindex 49b9835e..2870df17 100644--- a/lib/mcp/tools-read.ts+++ b/lib/mcp/tools-read.ts@@ -1,8 +1,8 @@-import { listDir, readFile, searchFs, usage, stats, processes } from "@/lib/host";+import { listDir, readFile, searchFs, usage, stats, processes, captureMsoScreen } from "@/lib/host";import { camoufoxStatus } from "@/lib/camoufox/service";import { listManagedApps, getManagedAppLogs } from "@/lib/managed-apps/manager";import { isManagedAppId } from "@/lib/managed-apps/catalog";-import { type McpTool, str, opt, S, PATH_P, READ_ONLY } from "./tool-kit";+import { type McpTool, str, opt, S, PATH_P, READ_ONLY, mcpDirect } from "./tool-kit";// The read tier: observability with no way to change anything. Everything here is// answerable without granting a shell, which is the whole point of the tiering —@@ -99,6 +99,35 @@ export const READ_TOOLS: McpTool[] = [return getManagedAppLogs(id);},},+ {+ name: "screen_capture",+ description:+ "Capture the authenticated MSO desktop and return it as an image. This is intentionally limited to " ++ "MSO itself (no arbitrary URL capture), so it can be used to show visual progress without turning a read token " ++ "into a browser exfiltration primitive. Choose macos, windows or dashboard; default macos.",+ scope: "read",+ annotations: READ_ONLY,+ limit: { key: "screen.capture", max: 10, windowMs: 60_000 },+ inputSchema: S({+ shell: { type: "string", enum: ["macos", "windows", "dashboard"], description: "Desktop shell to render. Default macos." },+ width: { type: "number", minimum: 900, maximum: 1920, description: "Viewport width. Default 1440." },+ height: { type: "number", minimum: 600, maximum: 1200, description: "Viewport height. Default 900." },+ }),+ run: async (a) => {+ const shell = typeof a.shell === "string" && ["macos", "windows", "dashboard"].includes(a.shell)+ ? (a.shell as "macos" | "windows" | "dashboard")+ : "macos";+ const shot = await captureMsoScreen({+ shell,+ width: typeof a.width === "number" ? a.width : undefined,+ height: typeof a.height === "number" ? a.height : undefined,+ });+ return mcpDirect([+ { type: "image", data: shot.data, mimeType: shot.mimeType },+ { type: "text", text: `MSO ${shot.shell} screenshot — ${shot.width}×${shot.height}` },+ ]);+ },+ },{name: "browser_status",description: