Skip to content

armgit / mso

Public Imported from GitHub
0

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.

fix(mcp): record what an MCP token did — the trail it was bypassing

Rahman6b08951112b4
diff --git a/CLAUDE.md b/CLAUDE.md
index 3a431517..64a91c4c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -280,6 +280,15 @@ that is the kill switch, and demo mode forces it off. Read `docs/MCP.md` first.
rule as `lib/auth/device-store.ts`. Codes are single-use, 60 s, deleted BEFORE the
token is minted. `browser_status` must never return the VNC password — that profile
holds a live Google session.
+- **The dispatcher writes the audit trail, because the tools bypass the one that
+ exists.** `audit()` is called at the ROUTE layer for `/api/v1`; MCP tools call
+ `lib/host` directly, so every write/delete/exec over MCP would otherwise be absent
+ from `~/.mso/audit.log`. `McpTool.audit` declares the action + which arg is the
+ target; `dispatch()` records it with `actor: mcp:<id>` (the id Settings shows) and
+ `meta.via = "mcp"`. Scope refusals log `mcp.denied` — that is the prompt-injection
+ signal. Reads stay unlogged, same rule the routes follow. `GET /api/v1/sys/audit`
+ reads it (session-gated); there is deliberately **no MCP tool** for it, or a
+ compromised token could check whether it had been noticed.
## CLI (`bin/mso`) — the web UI is only one frontend
`bin/mso` reaches the same `/api` surface from a shell — every route has a named verb
diff --git a/app/api/v1/sys/audit/route.ts b/app/api/v1/sys/audit/route.ts
new file mode 100644
index 00000000..28e055b4
--- /dev/null
+++ b/app/api/v1/sys/audit/route.ts
@@ -0,0 +1,23 @@
+import { NextResponse } from "next/server";
+import { verifyAuth } from "@/lib/agent/server";
+import { readAuditTail } from "@/lib/host";
+
+// The audit trail, read-only. Session-gated like every other /api/v1 route.
+//
+// There is deliberately NO MCP tool for this. The trail records what every MCP
+// token did; letting a token read it would let a compromised one check whether it
+// had been noticed, and edit nothing but its own expectations. Forensics is a
+// surface for the owner in a browser, not for an agent.
+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") ?? 50) || 50, 1), 200);
+ const prefix = q.get("prefix") ?? undefined;
+ const actor = q.get("actor") ?? undefined;
+ const entries = await readAuditTail({ prefix, limit: actor ? 200 : limit });
+ return NextResponse.json({
+ entries: (actor ? entries.filter((e) => (e.actor ?? "").startsWith(actor)) : entries).slice(0, limit),
+ });
+}
diff --git a/app/mcp/route.ts b/app/mcp/route.ts
index 6342ebed..fa8fa1b8 100644
--- a/app/mcp/route.ts
+++ b/app/mcp/route.ts
@@ -55,7 +55,9 @@ export async function POST(req: Request) {
}
void touchToken(token.hash).catch(() => {});
- const result = await dispatch(body as Parameters<typeof dispatch>[0], token.scope);
+ // Same 16-char id the Settings table and `mso mcp list` show, so an audit line
+ // maps straight back to the token you would revoke.
+ const result = await dispatch(body as Parameters<typeof dispatch>[0], token.scope, `mcp:${token.hash.slice(0, 16)}`);
return Response.json(result, { status: 200, headers: { "Cache-Control": "no-store" } });
}
diff --git a/bin/mso b/bin/mso
index b47e829b..627dbbe0 100755
--- a/bin/mso
+++ b/bin/mso
@@ -56,6 +56,7 @@
# models * Model catalog: list | test
# skills Skill catalog the assistant sees
# mcp * MCP bearer tokens: list | revoke <id> | revoke all
+# 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)
#
# Devices (a local file — these work while the service is down)
@@ -230,6 +231,7 @@ 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_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"
U_api="api <METHOD> <path> [json] e.g. mso api GET /api/v1/sys/stats"
@@ -408,6 +410,11 @@ case "$cmd" in
*) die "usage: mso $U_mcp" ;;
esac ;;
+ # ── audit trail (the forensic record; MCP writes land here too) ──────────
+ audit)
+ q="limit=${1:-50}"; [ -n "${2-}" ] && q="$q&prefix=$(enc "$2")"
+ jget "/api/v1/sys/audit?$q" ;;
+
whoami) echo "cli device: $(cli_device)"; jget "/api/auth/me" ;;
login) rm -f "$JAR"; login; echo "logged in as device $(cli_device)" ;;
logout) [ -f "$JAR" ] && jpost "/api/auth/logout" >/dev/null 2>&1 || true
diff --git a/docs/CLI.md b/docs/CLI.md
index d1b22a60..1748f22c 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -90,6 +90,7 @@ Commands:
models * Model catalog: list | test
skills Skill catalog the assistant sees
mcp * MCP bearer tokens: list | revoke <id> | revoke all
+ 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)
Devices (a local file — these work while the service is down)
diff --git a/docs/MCP.md b/docs/MCP.md
index 6052a251..72bcebff 100644
--- a/docs/MCP.md
+++ b/docs/MCP.md
@@ -96,6 +96,35 @@ credentials never leave the box through a tool result.
Grant `read` unless you actually need more, and mint a second token when you do.
+## Seeing what a token did
+
+Revoking is a weak control if you cannot see what already went through, so every
+mutating MCP call lands in the same audit trail (`~/.mso/audit.log`, JSONL) that
+the web UI's writes and commands do — with `actor` set to `mcp:<id>`, the same id
+the Settings table and `mso mcp list` show.
+
+```bash
+mso audit # newest 50, everything
+mso audit 100 exec. # just command execution
+mso audit 50 mcp. # just scope refusals
+jq -c 'select(.actor|startswith("mcp:"))' ~/.mso/audit.log # everything MCP did
+```
+
+Settings → MCP shows the last 20 MCP lines inline.
+
+What is recorded: `fs.write` `fs.mkdir` `fs.move` `fs.copy` `fs.delete`
+`exec.run` `camoufox.power`, each with its target and whether it succeeded, plus
+`mcp.denied` when a token asks for a tool above its scope. **That last one is the
+signal worth watching** — a `read` connector repeatedly reaching for `exec_run` is
+what a prompt-injected model looks like from the outside.
+
+Reads are NOT recorded. Same rule the `/api/v1` routes follow: they are bounded
+and high-volume, and logging them would bury the lines that matter.
+
+There is deliberately no MCP tool for reading the trail. It records what every
+token did; letting a token read it would let a compromised one check whether it
+had been noticed. `GET /api/v1/sys/audit` is session-gated, browser and CLI only.
+
## Revoking
**mso → Settings → MCP**, or from the CLI:
diff --git a/frontend/slices/os-settings/components/mcp-section.tsx b/frontend/slices/os-settings/components/mcp-section.tsx
index 8323a3d6..f04ee5bc 100644
--- a/frontend/slices/os-settings/components/mcp-section.tsx
+++ b/frontend/slices/os-settings/components/mcp-section.tsx
@@ -7,6 +7,15 @@ import { SettingsSection } from "@/features/shell-settings";
import { toast } from "@/features/os-shell";
import { IS_DEMO } from "@/lib/demo";
+type AuditRow = {
+ ts?: string;
+ action: string;
+ actor?: string | null;
+ target?: string;
+ ok?: boolean;
+ detail?: string;
+};
+
type TokenRow = {
id: string;
label: string;
@@ -47,6 +56,7 @@ function CopyRow({ label, value }: { label: string; value: string }) {
export function McpSection() {
const [state, setState] = useState<{ enabled: boolean; maxScope: string; tokens: TokenRow[] } | null>(null);
+ const [trail, setTrail] = useState<AuditRow[]>([]);
const [origin, setOrigin] = useState("");
const load = useCallback(() => {
@@ -62,6 +72,12 @@ export function McpSection() {
setState(s);
})
.catch(() => toast("Couldn't load MCP tokens", { tone: "error" }));
+ // What those tokens actually DID. Revoking is a weak control if you cannot
+ // see the writes and commands that already went through.
+ fetch("/api/v1/sys/audit?actor=mcp%3A&limit=20", { cache: "no-store" })
+ .then((r) => (r.ok ? r.json() : { entries: [] }))
+ .then((d: { entries?: AuditRow[] }) => setTrail(d.entries ?? []))
+ .catch(() => setTrail([]));
}, []);
useEffect(load, [load]);
@@ -144,6 +160,24 @@ export function McpSection() {
})}
</ul>
)}
+ {trail.length > 0 && (
+ <div className="mt-4 border-t border-border pt-3">
+ <p className="pb-1.5 text-xs font-medium">Recent MCP activity</p>
+ <ul className="space-y-1">
+ {trail.map((e, i) => (
+ <li key={i} className="flex items-baseline gap-2 text-[11px]">
+ <code className={e.ok === false ? "shrink-0 font-mono text-destructive" : "shrink-0 font-mono"}>{e.action}</code>
+ <span className="min-w-0 flex-1 truncate font-mono text-muted-foreground">{e.target ?? e.detail ?? ""}</span>
+ <span className="shrink-0 text-muted-foreground">{e.ts ? new Date(e.ts).toLocaleString() : ""}</span>
+ </li>
+ ))}
+ </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>.
+ </p>
+ </div>
+ )}
{live.length > 0 && (
<Button
type="button"
diff --git a/lib/host/audit.ts b/lib/host/audit.ts
index cc84c346..2b3df366 100644
--- a/lib/host/audit.ts
+++ b/lib/host/audit.ts
@@ -24,6 +24,10 @@ export type AuditAction =
| "sys.cleanup"
| "managed-app.action"
| "camoufox.power"
+ /** An MCP token asked for a tool above its scope. Not an error — it is the
+ * signal that matters: a `read` connector repeatedly reaching for `exec_run`
+ * is what a prompt-injected model looks like from the outside. */
+ | "mcp.denied"
| "auth.login"
| "auth.pending"
| "auth.denied"
diff --git a/lib/mcp/dispatch.test.ts b/lib/mcp/dispatch.test.ts
index a003c715..f809ea6a 100644
--- a/lib/mcp/dispatch.test.ts
+++ b/lib/mcp/dispatch.test.ts
@@ -1,8 +1,18 @@
-import { describe, it, expect, vi } from "vitest";
+import { describe, it, expect, vi, beforeEach } from "vitest";
// The catalog reaches lib/camoufox + lib/managed-apps, which are `server-only`.
// Next aliases that specifier internally; vitest does not, so stub it — same
// pattern as lib/managed-apps/manager.test.ts.
vi.mock("server-only", () => ({}));
+
+// Spy on the trail without writing to ~/.mso/audit.log. Everything else in
+// @/lib/host stays REAL — the point of these cases is that the dispatcher, not
+// each tool, is what records.
+const audited: { action: string; actor?: string; target?: string; ok?: boolean }[] = [];
+vi.mock("@/lib/host", async (orig) => {
+ const real = await orig<typeof import("@/lib/host")>();
+ return { ...real, audit: (e: { action: string }) => { audited.push(e); return Promise.resolve(); } };
+});
+
const { dispatch, isNotification } = await import("./dispatch");
const { TOOLS } = await import("./tools");
@@ -118,3 +128,43 @@ describe("catalog hygiene", () => {
}
});
});
+
+describe("audit trail", () => {
+ beforeEach(() => {
+ audited.length = 0;
+ });
+
+ it("records a scope refusal — a read token reaching for exec IS the injection signal", async () => {
+ await dispatch(call("exec_run", { command: "id" }), "read", "mcp:abc123");
+ expect(audited).toEqual([
+ expect.objectContaining({ action: "mcp.denied", actor: "mcp:abc123", target: "exec_run", ok: false }),
+ ]);
+ });
+
+ it("records a failed write with its target, so a blocked path is visible", async () => {
+ await dispatch(call("fs_write", { path: "/etc/shadow", content: "x" }), "write", "mcp:abc123");
+ expect(audited).toEqual([
+ expect.objectContaining({ action: "fs.write", actor: "mcp:abc123", target: "/etc/shadow", ok: false }),
+ ]);
+ expect(audited[0]).toMatchObject({ meta: { via: "mcp", scope: "write" } });
+ });
+
+ it("records exec_run with the command as the target", async () => {
+ await dispatch(call("exec_run", { command: "echo hi" }), "exec", "mcp:abc123");
+ expect(audited[0]).toMatchObject({ action: "exec.run", target: "echo hi" });
+ });
+
+ it("does NOT record reads — bounded and high-volume, same rule /api/v1 follows", async () => {
+ await dispatch(call("sys_stats"), "read", "mcp:abc123");
+ await dispatch(call("fs_list", { path: "~/projects" }), "read", "mcp:abc123");
+ await dispatch({ id: 1, method: "tools/list" }, "exec", "mcp:abc123");
+ expect(audited).toEqual([]);
+ });
+
+ it("every write/exec tool declares an audit action, and no read tool does", () => {
+ for (const t of TOOLS) {
+ if (t.scope === "read") expect(t.audit, t.name).toBeUndefined();
+ else expect(t.audit?.action, t.name).toBeTruthy();
+ }
+ });
+});
diff --git a/lib/mcp/dispatch.ts b/lib/mcp/dispatch.ts
index 5cd6d18e..d05509b8 100644
--- a/lib/mcp/dispatch.ts
+++ b/lib/mcp/dispatch.ts
@@ -1,3 +1,4 @@
+import { audit } from "@/lib/host";
import { TOOLS, TOOLS_BY_NAME } from "./tools";
import { allows, type Scope } from "./scope";
@@ -41,7 +42,12 @@ function toolList(scope: Scope) {
}));
}
-export async function dispatch(req: RpcRequest, scope: Scope): Promise<Record<string, unknown>> {
+/**
+ * @param actor identifies WHICH token acted, as `mcp:<id>` — the same id the
+ * Settings table and `mso mcp list` show, so a line in the trail maps back to a
+ * revoke button. Never the raw bearer.
+ */
+export async function dispatch(req: RpcRequest, scope: Scope, actor?: string): Promise<Record<string, unknown>> {
const id = req.id ?? null;
switch (req.method) {
case "initialize":
@@ -63,6 +69,10 @@ export async function dispatch(req: RpcRequest, scope: Scope): Promise<Record<st
// Scope is re-checked HERE, not just at tools/list — a client can call any
// name it likes, and the list is only a hint.
if (!allows(scope, tool.scope)) {
+ // Logged even though nothing happened: a `read` connector repeatedly
+ // 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}` });
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,
@@ -71,14 +81,23 @@ export async function dispatch(req: RpcRequest, scope: Scope): Promise<Record<st
for (const k of tool.inputSchema.required ?? []) {
if (args[k] == null) return fail(id, -32602, `${name} needs { ${(tool.inputSchema.required ?? []).join(", ")} }`);
}
+ // MCP tools call lib/host directly, so the ROUTE-level audit that covers
+ // /api/v1 never runs for them. Without this, every write, delete and exec
+ // that arrived over MCP would be missing from the one forensic trail there
+ // is — and "revoke the token" is not much of a control if you cannot see
+ // 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;
try {
const result = await tool.run(args);
+ if (trail) void audit({ action: trail.action, actor, target, ok: true, meta: { via: "mcp", scope } });
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
// error object: ChatGPT hides protocol-level errors from the user, so the
// 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 } });
return ok(id, { content: [{ type: "text", text: "error: " + msg.slice(0, 500) }], isError: true });
}
}
diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.ts
index f6d2b63a..9d500df3 100644
--- a/lib/mcp/tools.ts
+++ b/lib/mcp/tools.ts
@@ -2,6 +2,7 @@ import {
listDir, readFile, writeFile, makeDir, remove, move, copy, searchFs, usage,
runCommand, stats, processes,
} from "@/lib/host";
+import type { AuditAction } from "@/lib/host";
import { camoufoxStatus, setCamoufoxEnabled } from "@/lib/camoufox/service";
import { listManagedApps } from "@/lib/managed-apps/manager";
import type { Scope } from "./scope";
@@ -20,6 +21,14 @@ export interface McpTool {
inputSchema: { type: "object"; properties: Record<string, unknown>; required?: string[] };
annotations?: Record<string, boolean>;
run: (a: Record<string, unknown>) => Promise<unknown>;
+ /** Which audit action this writes, and which argument names the target. Reads
+ * are deliberately unaudited (bounded + high-volume, same rule the /api/v1
+ * routes follow); a tool without this field writes nothing.
+ *
+ * This exists because MCP tools call lib/host DIRECTLY. The /api/v1 routes
+ * audit at the ROUTE layer, so without this every write, delete and exec that
+ * arrived over MCP would be invisible in the only forensic trail there is. */
+ audit?: { action: AuditAction; targetArg?: string };
}
const str = (a: Record<string, unknown>, k: string): string => {
@@ -126,6 +135,7 @@ export const TOOLS: McpTool[] = [
{
name: "fs_write",
+ audit: { action: "fs.write" as const, targetArg: "path" },
description:
"Create or overwrite a text file on the VPS. Overwrites without warning — fs_read first if you need " +
"the old contents. Bounded to OS_FS_WRITE_ROOTS (home + ~/projects by default).",
@@ -139,6 +149,7 @@ export const TOOLS: McpTool[] = [
},
{
name: "fs_mkdir",
+ audit: { action: "fs.mkdir" as const, targetArg: "path" },
description: "Create a directory (and any missing parents) on the VPS.",
scope: "write",
annotations: { idempotentHint: true },
@@ -147,6 +158,7 @@ export const TOOLS: McpTool[] = [
},
{
name: "fs_move",
+ audit: { action: "fs.move" as const, targetArg: "from" },
description: "Move or rename a file or directory. Refuses when the source holds credential paths.",
scope: "write",
inputSchema: S({ from: { type: "string" }, to: { type: "string" } }, ["from", "to"]),
@@ -154,6 +166,7 @@ export const TOOLS: McpTool[] = [
},
{
name: "fs_copy",
+ audit: { action: "fs.copy" as const, targetArg: "from" },
description: "Copy a file or directory. The cockpit's own secrets are skipped rather than duplicated.",
scope: "write",
inputSchema: S({ from: { type: "string" }, to: { type: "string" } }, ["from", "to"]),
@@ -161,6 +174,7 @@ export const TOOLS: McpTool[] = [
},
{
name: "fs_delete",
+ audit: { action: "fs.delete" as const, targetArg: "path" },
description:
"Delete a file or directory on the VPS. PERMANENT — there is no trash and no undo. " +
"Confirm with the user before calling this on anything you did not create in this conversation.",
@@ -172,6 +186,7 @@ export const TOOLS: McpTool[] = [
{
name: "exec_run",
+ audit: { action: "exec.run" as const, targetArg: "command" },
description:
"Run a shell command on the VPS as the owner and return stdout, stderr and exit code. " +
"FULL HOST POWER — prefer fs_* and sys_* tools whenever they cover the task; they are bounded and " +
@@ -187,6 +202,7 @@ export const TOOLS: McpTool[] = [
},
{
name: "browser_power",
+ audit: { action: "camoufox.power" as const, targetArg: "on" },
description:
"Start or stop the Camoufox browser session on the VPS. Starting boots a real Firefox on a headless " +
"X display; the session self-terminates after 2h. Stop it when done — it holds a live logged-in profile.",