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.

feat(mcp): an MCP server so ChatGPT, Claude.ai or Cursor can drive this VPS

Rahman78c9ea102b4c
diff --git a/.env.example b/.env.example
index e7e8168f..de123e19 100644
--- a/.env.example
+++ b/.env.example
@@ -165,3 +165,15 @@ OS_SESSION_SECRET=
# (openssl rand -hex 32) and keep it stable across deploys, else in-flight
# action payloads silently invalidate on rolling restart.
# NEXT_SERVER_ACTIONS_ENCRYPTION_KEY=
+
+# ── MCP server (control this VPS from ChatGPT / Claude.ai / Cursor) ──────────
+# OFF by default. While unset, /mcp and the OAuth discovery documents return 404 —
+# there is no MCP surface at all, not an unauthenticated one.
+# OS_MCP_ENABLED=1
+# Highest tier the consent screen may grant. read | write | exec. Default write,
+# so shell access is opt-in twice: once here, once per token on the consent page.
+# `exec` means a leaked bearer runs any command on this box as you.
+# OS_MCP_MAX_SCOPE=write
+# 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
diff --git a/CLAUDE.md b/CLAUDE.md
index 7f482723..3a431517 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -259,6 +259,28 @@ to `resources/` (rr) and drive any project from one manifest:
filtering is done in the script. `ci.yml` runs the raw fail-closed command on
purpose: a release gate must not pass an audit it could not perform.
+## MCP server (`/mcp`) — optional, OFF by default
+An MCP endpoint so ChatGPT / Claude.ai / Cursor can drive the host. `lib/mcp/*`
+(pkce · scope · store · tools · dispatch) + `app/mcp/route.ts` + `app/oauth/*` +
+`app/.well-known/oauth-*`. **`OS_MCP_ENABLED=1` or every one of those routes 404s** —
+that is the kill switch, and demo mode forces it off. Read `docs/MCP.md` first.
+- **`/mcp` is deliberately NOT under `/api`.** `proxy.ts` blocks mutating `/api` that
+ cannot prove same-origin and an MCP client is cross-origin by definition; the bearer
+ is the control, not the CSRF gate. `proxy.ts` exempts `/mcp`, `/oauth/token`,
+ `/oauth/register` and `/.well-known/oauth-*` from BOTH that gate and the document
+ CSP. `/oauth/authorize` is NOT exempt — it is a real HTML page and needs its nonce.
+- **Every tool is a thin call into `lib/host`**, never node `fs`/`child_process`. That
+ is what makes the MCP surface inherit `OS_FS_*_ROOTS`, the credential denylist
+ (including `~/.mso` itself) and `exec.ts`'s destructive filter for free. A tool that
+ reimplements an operation reimplements its guard too — don't.
+- Scope ladder `read < write < exec`, picked per token on the consent page, capped by
+ `OS_MCP_MAX_SCOPE` (default `write`). `tools/list` filters by it AND `tools/call`
+ re-checks it — a client can call a name it was never shown.
+- Store is `~/.mso/mcp.json`, **sha256 only**, same atomic-write + fail-loud-on-corrupt
+ 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.
+
## 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
(enforced by a test in `bin/mso.test.ts`), plus `doctor`, `completion` and `--base`.
diff --git a/README.md b/README.md
index 88f5f44d..43e99fad 100644
--- a/README.md
+++ b/README.md
@@ -63,6 +63,7 @@ For a real deployment, put MSO behind **Tailscale, a VPN, or a TLS reverse proxy
**Extend** — Alfa AI, modular slices, and custom apps.
- **Use BYOK AI** — Alfa uses credentials stored on your server, not committed to the repo.
+- **Drive the box from ChatGPT, Claude.ai or Cursor** — an optional MCP server (OAuth 2.1 + PKCE) exposes files, system health and, if you grant it, a shell. Off unless you set `OS_MCP_ENABLED=1`, scoped read/write/exec per token, revocable from Settings. See [docs/MCP.md](./docs/MCP.md).
- **Add app slices** — features are modular under `frontend/slices/<slug>/`.
- **Personalize the interface** — macOS, Windows, iOS, and Android shell layouts are UI preferences, not the core product.
@@ -159,6 +160,7 @@ An authenticated MSO session can read allowed files and run commands as the user
- Treat any file Alfa reads as untrusted input. The approval card is the only thing between text hidden inside a file and an `exec.run`. Read the command on the card, not Alfa's summary of it.
- Agents and Skills group tools for your own convenience. They are not a permission boundary: every agent can call every tool.
- `exec.run` is not sandboxed. Its cwd is bounded to your write roots, but the command itself runs in your login shell as the service user. The destructive-command denylist is a short accident tripwire, not a guard.
+- The MCP server is off unless `OS_MCP_ENABLED=1`. When on, a bearer token is a standing credential with whatever scope you granted it: at `exec` it runs any command on the box as you, and every call and result goes to the client's provider. Grant `read` unless you need more, cap the ceiling with `OS_MCP_MAX_SCOPE`, and treat anything the model reads as untrusted — scope is what stops a prompt-injected file talking it into a write. See [docs/MCP.md](./docs/MCP.md).
- MSO has not had a third-party security audit.
More detail: [SECURITY.md](./SECURITY.md), [docs/FAQ.md](./docs/FAQ.md) and [docs/INSTALL.md](./docs/INSTALL.md).
@@ -256,6 +258,7 @@ Not currently supported:
| [docs/ARCHITECTURE.md](./docs/ARCHITECTURE.md) | App shell, host layer, slices, routing |
| [docs/MANAGED-APPS.md](./docs/MANAGED-APPS.md) | Managing Hermes/OpenClaw, per-app origins, workspace modes |
| [docs/MODELS-INTEGRATION.md](./docs/MODELS-INTEGRATION.md) | Alfa AI and BYOK model providers |
+| [docs/MCP.md](./docs/MCP.md) | The MCP server: connecting ChatGPT/Claude/Cursor, scopes, revoking |
| [docs/FAQ.md](./docs/FAQ.md) | Security posture, device approval, costs, product boundaries |
| [docs/TROUBLESHOOTING.md](./docs/TROUBLESHOOTING.md) | Common install, build, and deployment failures |
| [SECURITY.md](./SECURITY.md) | Responsible disclosure and deployment warnings |
diff --git a/app/.well-known/oauth-authorization-server/route.ts b/app/.well-known/oauth-authorization-server/route.ts
new file mode 100644
index 00000000..1ea33e71
--- /dev/null
+++ b/app/.well-known/oauth-authorization-server/route.ts
@@ -0,0 +1,27 @@
+import { publicOrigin } from "@/lib/mcp/origin";
+import { mcpEnabled } from "@/lib/mcp/scope";
+
+// RFC 8414 — authorization-server metadata. Public clients only (no secret),
+// PKCE S256 only, authorization_code only. Dynamic Client Registration is
+// advertised because Claude.ai, Cursor and mcp-remote all expect it; ChatGPT
+// uses a user-defined client and never touches /oauth/register.
+export const runtime = "nodejs";
+
+export async function GET(req: Request) {
+ if (!mcpEnabled()) return new Response("Not Found", { status: 404 });
+ const origin = publicOrigin(req);
+ return Response.json(
+ {
+ issuer: origin,
+ authorization_endpoint: `${origin}/oauth/authorize`,
+ token_endpoint: `${origin}/oauth/token`,
+ registration_endpoint: `${origin}/oauth/register`,
+ response_types_supported: ["code"],
+ grant_types_supported: ["authorization_code"],
+ code_challenge_methods_supported: ["S256"],
+ token_endpoint_auth_methods_supported: ["none"],
+ scopes_supported: ["read", "write", "exec"],
+ },
+ { headers: { "cache-control": "public, max-age=3600" } },
+ );
+}
diff --git a/app/.well-known/oauth-protected-resource/route.ts b/app/.well-known/oauth-protected-resource/route.ts
new file mode 100644
index 00000000..39937bee
--- /dev/null
+++ b/app/.well-known/oauth-protected-resource/route.ts
@@ -0,0 +1,22 @@
+import { publicOrigin } from "@/lib/mcp/origin";
+import { mcpEnabled } from "@/lib/mcp/scope";
+
+// RFC 9728 — tells an MCP client which authorization server protects /mcp.
+// This MUST be served from the same origin as the MCP URL: a client's first
+// discovery probe goes to the resource host, and mirroring it anywhere else is
+// what produces "MCP server does not implement OAuth" with no further detail.
+export const runtime = "nodejs";
+
+export async function GET(req: Request) {
+ if (!mcpEnabled()) return new Response("Not Found", { status: 404 });
+ const origin = publicOrigin(req);
+ return Response.json(
+ {
+ resource: `${origin}/mcp`,
+ authorization_servers: [origin],
+ scopes_supported: ["read", "write", "exec"],
+ bearer_methods_supported: ["header"],
+ },
+ { headers: { "cache-control": "public, max-age=3600" } },
+ );
+}
diff --git a/app/api/mcp/tokens/route.ts b/app/api/mcp/tokens/route.ts
new file mode 100644
index 00000000..7d305947
--- /dev/null
+++ b/app/api/mcp/tokens/route.ts
@@ -0,0 +1,24 @@
+import { NextResponse } from "next/server";
+import { verifyAuth } from "@/lib/agent/server";
+import { listTokens, revokeToken, revokeAllTokens } from "@/lib/mcp/store";
+import { mcpEnabled, maxScope } from "@/lib/mcp/scope";
+
+// Token management for Settings → MCP. Under /api on purpose: this one IS
+// cookie-authenticated and DOES want the depth-2 CSRF gate in proxy.ts, unlike
+// /mcp itself. There is no mint endpoint — tokens only ever come from the OAuth
+// consent flow, so a stolen session cannot silently create a standing bearer
+// without the owner seeing the consent screen.
+export const dynamic = "force-dynamic";
+
+export async function GET(req: Request) {
+ if (!(await verifyAuth(req))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });
+ return NextResponse.json({ enabled: mcpEnabled(), maxScope: maxScope(), tokens: await listTokens() });
+}
+
+export async function DELETE(req: Request) {
+ if (!(await verifyAuth(req))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });
+ const id = new URL(req.url).searchParams.get("id");
+ if (id === "all") return NextResponse.json({ revoked: await revokeAllTokens() });
+ if (!id) return NextResponse.json({ error: "id required" }, { status: 400 });
+ return NextResponse.json({ revoked: (await revokeToken(id)) ? 1 : 0 });
+}
diff --git a/app/mcp/route.ts b/app/mcp/route.ts
new file mode 100644
index 00000000..6342ebed
--- /dev/null
+++ b/app/mcp/route.ts
@@ -0,0 +1,72 @@
+import { dispatch, isNotification, rpcError, UNAUTHORIZED, RATE_LIMITED } from "@/lib/mcp/dispatch";
+import { validateToken, touchToken } from "@/lib/mcp/store";
+import { mcpEnabled } from "@/lib/mcp/scope";
+import { publicOrigin, clientIp } from "@/lib/mcp/origin";
+import { rateLimited } from "@/lib/host";
+
+// The MCP endpoint. Deliberately at /mcp and NOT under /api: proxy.ts blocks
+// mutating /api that cannot prove same-origin, and an MCP client is by definition
+// cross-origin. The CSRF gate is not what protects this route — the bearer is, and
+// a bearer is not something a browser attaches on its own the way a cookie is.
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+
+const CALLS_PER_MIN = 120;
+const CALLS_PER_DAY = 5_000;
+const PREAUTH_PER_MIN = 240;
+
+export async function POST(req: Request) {
+ const origin = publicOrigin(req);
+ const challenge = `Bearer realm="mso", resource_metadata="${origin}/.well-known/oauth-protected-resource"`;
+ const unauthorized = (msg: string) =>
+ Response.json(rpcError(null, UNAUTHORIZED, msg), { status: 401, headers: { "WWW-Authenticate": challenge } });
+
+ if (!mcpEnabled()) return new Response("Not Found", { status: 404 });
+
+ // Pre-auth flood guard: an invalid token still costs a sha256 + a file read.
+ if (rateLimited(`mcp:ip:${clientIp(req)}`, PREAUTH_PER_MIN, 60_000)) {
+ return Response.json(rpcError(null, RATE_LIMITED, "rate limited"), { status: 429, headers: { "Retry-After": "60" } });
+ }
+
+ const bearer = (req.headers.get("authorization") ?? "").replace(/^Bearer\s+/i, "").trim();
+ if (!bearer) return unauthorized("missing bearer token");
+
+ let body: unknown;
+ try {
+ body = await req.json();
+ } catch {
+ return Response.json({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "parse error" } }, { status: 400 });
+ }
+
+ // Ack EVERY notification, not just notifications/initialized — a client that
+ // sends notifications/cancelled hangs waiting for a response it will never get.
+ if (isNotification(body)) return new Response(null, { status: 202 });
+
+ const token = await validateToken(bearer);
+ if (!token) return unauthorized("invalid, revoked or expired MCP token");
+
+ if (rateLimited(`mcp:tok:${token.hash}`, CALLS_PER_MIN, 60_000)) {
+ return Response.json(rpcError(null, RATE_LIMITED, "rate limited — retry in 60s"), { status: 429, headers: { "Retry-After": "60" } });
+ }
+ // Per-minute alone still allows ~172k calls/day from one runaway agent, on an
+ // endpoint whose top scope is a shell. The daily cap is the backstop.
+ if (rateLimited(`mcp:day:${token.hash}`, CALLS_PER_DAY, 86_400_000)) {
+ return Response.json(rpcError(null, RATE_LIMITED, "daily call limit reached for this token"), { status: 429, headers: { "Retry-After": "3600" } });
+ }
+
+ void touchToken(token.hash).catch(() => {});
+ const result = await dispatch(body as Parameters<typeof dispatch>[0], token.scope);
+ return Response.json(result, { status: 200, headers: { "Cache-Control": "no-store" } });
+}
+
+// Some clients probe with GET before POSTing. Answer with what this is, never
+// with anything that needs the token.
+export async function GET(req: Request) {
+ if (!mcpEnabled()) return new Response("Not Found", { status: 404 });
+ return Response.json({
+ name: "mso MCP",
+ transport: "streamable-http (JSON-RPC over POST)",
+ auth: "Bearer <mcp token> — obtain via OAuth 2.1 + PKCE",
+ authorization_servers: [publicOrigin(req)],
+ });
+}
diff --git a/app/oauth/authorize/actions.ts b/app/oauth/authorize/actions.ts
new file mode 100644
index 00000000..b6d11841
--- /dev/null
+++ b/app/oauth/authorize/actions.ts
@@ -0,0 +1,50 @@
+"use server";
+
+import { redirect } from "next/navigation";
+import { requireSession } from "@/lib/auth/require-session";
+import { getClient, storeCode, CODE_TTL_MS } from "@/lib/mcp/store";
+import { randomToken, isAllowedRedirect } from "@/lib/mcp/pkce";
+import { parseScope, clampScope, mcpEnabled, type Scope } from "@/lib/mcp/scope";
+
+// The consent decision. A Server Action rather than an API route because it must
+// be same-origin by construction: this is the one place a signed-in session is
+// converted into a bearer that acts on the host.
+export async function approve(form: FormData): Promise<{ error: string } | never> {
+ if (!mcpEnabled()) return { error: "MCP is disabled on this server." };
+ // The session cookie is the ONLY thing authorizing this. Re-checked here and not
+ // inherited from the page render — a page can be cached, an action cannot.
+ if (!(await requireSession())) return { error: "Not signed in." };
+
+ const clientId = String(form.get("client_id") ?? "");
+ const redirectUri = String(form.get("redirect_uri") ?? "");
+ const challenge = String(form.get("code_challenge") ?? "");
+ const method = String(form.get("code_challenge_method") ?? "");
+ const state = String(form.get("state") ?? "");
+ const scope: Scope = clampScope(parseScope(String(form.get("scope") ?? "read")));
+
+ if (method !== "S256" || !challenge) return { error: "This client did not use PKCE S256, which mso requires." };
+ if (!isAllowedRedirect(redirectUri)) return { error: "The redirect target is not https (or localhost)." };
+
+ const client = await getClient(clientId);
+ // A user-defined client (ChatGPT's flow) never registers, so it has no record
+ // here. That is allowed — the redirect_uri is still https-checked above and the
+ // code is still bound to this exact client_id + redirect_uri at exchange. What
+ // is NOT allowed is a REGISTERED client redirecting somewhere it never declared.
+ if (client && !client.redirectUris.includes(redirectUri)) {
+ return { error: "That redirect target is not registered for this client." };
+ }
+
+ const code = randomToken("mso_code_");
+ await storeCode(code, {
+ clientId,
+ redirectUri,
+ codeChallenge: challenge,
+ scope,
+ expiresAt: Date.now() + CODE_TTL_MS,
+ });
+
+ const dest = new URL(redirectUri);
+ dest.searchParams.set("code", code);
+ if (state) dest.searchParams.set("state", state);
+ redirect(dest.toString());
+}
diff --git a/app/oauth/authorize/consent-form.tsx b/app/oauth/authorize/consent-form.tsx
new file mode 100644
index 00000000..ed26fbea
--- /dev/null
+++ b/app/oauth/authorize/consent-form.tsx
@@ -0,0 +1,119 @@
+"use client";
+
+import { useState } from "react";
+import { Button } from "@/components/ui/button";
+import { approve } from "./actions";
+import type { Scope } from "@/lib/mcp/scope";
+
+const TIERS: { value: Scope; label: string; blurb: string }[] = [
+ { value: "read", label: "Read only", blurb: "List and read files, disk usage, CPU/memory, processes, installed apps." },
+ { value: "write", label: "Read + write files", blurb: "Everything above, plus create, overwrite, move, copy and delete files." },
+ { value: "exec", label: "Full shell", blurb: "Everything above, plus run any shell command as you, and power the browser session." },
+];
+
+export function ConsentForm({
+ clientName,
+ redirectUri,
+ ceiling,
+ hidden,
+}: {
+ clientName: string;
+ redirectUri: string;
+ ceiling: Scope;
+ hidden: Record<string, string>;
+}) {
+ const allowed = TIERS.slice(0, TIERS.findIndex((t) => t.value === ceiling) + 1);
+ const [scope, setScope] = useState<Scope>("read");
+ const [error, setError] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+
+ return (
+ <form
+ action={async (fd) => {
+ setBusy(true);
+ // approve() redirects on success, so anything returned here is a failure.
+ const r = await approve(fd);
+ setBusy(false);
+ if (r?.error) setError(r.error);
+ }}
+ className="space-y-5"
+ >
+ {Object.entries(hidden).map(([k, v]) => (
+ <input key={k} type="hidden" name={k} value={v} />
+ ))}
+
+ <div className="space-y-1">
+ <h1 className="text-lg font-semibold">Connect {clientName} to your VPS</h1>
+ <p className="text-sm text-muted-foreground">
+ It will be able to act on this machine as you, without asking again, until you revoke it in
+ Settings → MCP.
+ </p>
+ </div>
+
+ <div className="rounded-lg border border-border bg-secondary/40 p-3 text-xs">
+ <span className="text-muted-foreground">Sends the result to</span>
+ <div className="mt-0.5 truncate font-mono">{redirectUri}</div>
+ <p className="mt-2 text-muted-foreground">
+ The name above is what the client called itself. Only continue if you just started this
+ connection yourself.
+ </p>
+ </div>
+
+ <fieldset className="space-y-2">
+ <legend className="mb-1 text-sm font-medium">What it may do</legend>
+ {allowed.map((t) => (
+ <label
+ key={t.value}
+ className="flex cursor-pointer gap-3 rounded-lg border border-border p-3 has-[:checked]:border-primary has-[:checked]:bg-primary/5"
+ >
+ <input
+ type="radio"
+ name="scope"
+ value={t.value}
+ checked={scope === t.value}
+ onChange={() => setScope(t.value)}
+ className="mt-0.5 size-4 shrink-0 accent-[var(--primary)]"
+ />
+ <span className="min-w-0">
+ <span className="block text-sm font-medium">{t.label}</span>
+ <span className="block text-xs text-muted-foreground">{t.blurb}</span>
+ </span>
+ </label>
+ ))}
+ {allowed.length < TIERS.length && (
+ <p className="text-xs text-muted-foreground">
+ Higher tiers are disabled by <code className="font-mono">OS_MCP_MAX_SCOPE</code> on this server.
+ </p>
+ )}
+ </fieldset>
+
+ {scope === "exec" && (
+ <p role="alert" className="rounded-lg border border-destructive/40 bg-destructive/10 p-3 text-xs text-destructive">
+ Full shell means whoever holds this token can run any command on this VPS as you, and every
+ command you ask for is sent to the client&apos;s provider. Grant it only to a client you trust
+ that much.
+ </p>
+ )}
+
+ {error && (
+ <p role="alert" className="text-xs text-destructive">
+ {error}
+ </p>
+ )}
+
+ <div className="flex gap-2">
+ <Button type="submit" disabled={busy} className="flex-1 [@media(pointer:coarse)]:min-h-[44px]">
+ {busy ? "Connecting…" : "Allow"}
+ </Button>
+ <Button
+ type="button"
+ variant="secondary"
+ className="flex-1 [@media(pointer:coarse)]:min-h-[44px]"
+ onClick={() => history.back()}
+ >
+ Cancel
+ </Button>
+ </div>
+ </form>
+ );
+}
diff --git a/app/oauth/authorize/page.tsx b/app/oauth/authorize/page.tsx
new file mode 100644
index 00000000..eff99fcc
--- /dev/null
+++ b/app/oauth/authorize/page.tsx
@@ -0,0 +1,84 @@
+import Link from "next/link";
+import { notFound } from "next/navigation";
+import { requireSession } from "@/lib/auth/require-session";
+import { getClient } from "@/lib/mcp/store";
+import { isAllowedRedirect } from "@/lib/mcp/pkce";
+import { mcpEnabled, maxScope } from "@/lib/mcp/scope";
+import { ConsentForm } from "./consent-form";
+
+// OAuth consent. Renders only for a signed-in owner; everything it needs to mint
+// a code is carried in the query string and re-validated in the action.
+export const dynamic = "force-dynamic";
+
+function Shell({ children }: { children: React.ReactNode }) {
+ return (
+ <main id="main-content" className="grid min-h-dvh place-items-center bg-background p-4">
+ <div className="w-full max-w-md rounded-2xl border border-border bg-card p-6 shadow-xl">{children}</div>
+ </main>
+ );
+}
+
+export default async function AuthorizePage({
+ searchParams,
+}: {
+ searchParams: Promise<Record<string, string | string[] | undefined>>;
+}) {
+ if (!mcpEnabled()) notFound();
+ const q = await searchParams;
+ const one = (k: string) => (Array.isArray(q[k]) ? q[k][0] : q[k]) ?? "";
+
+ const clientId = one("client_id");
+ const redirectUri = one("redirect_uri");
+ const challenge = one("code_challenge");
+ const method = one("code_challenge_method");
+
+ if (!(await requireSession())) {
+ return (
+ <Shell>
+ <h1 className="text-lg font-semibold">Sign in first</h1>
+ <p className="mt-2 text-sm text-muted-foreground">
+ Open mso, unlock it on this device, then start the connection again from the client. This page
+ cannot authorize anything on its own.
+ </p>
+ <Link className="mt-4 inline-block text-sm underline" href="/" prefetch={false}>
+ Open mso
+ </Link>
+ </Shell>
+ );
+ }
+
+ // Fail loudly and specifically BEFORE showing an Allow button — a consent screen
+ // that approves a malformed request is worse than one that refuses to render.
+ const problem =
+ !clientId ? "The client did not send a client_id."
+ : !isAllowedRedirect(redirectUri) ? "The client's redirect target is missing, or is not https (or localhost)."
+ : method !== "S256" || !challenge ? "The client did not use PKCE with S256, which mso requires."
+ : null;
+
+ if (problem) {
+ return (
+ <Shell>
+ <h1 className="text-lg font-semibold">Cannot connect this client</h1>
+ <p className="mt-2 text-sm text-muted-foreground">{problem}</p>
+ </Shell>
+ );
+ }
+
+ const client = await getClient(clientId);
+ return (
+ <Shell>
+ <ConsentForm
+ clientName={client?.name ?? clientId}
+ redirectUri={redirectUri}
+ ceiling={maxScope()}
+ hidden={{
+ client_id: clientId,
+ redirect_uri: redirectUri,
+ code_challenge: challenge,
+ code_challenge_method: method,
+ state: one("state"),
+ }}
+ />
+ </Shell>
+ );
+}
diff --git a/app/oauth/register/route.ts b/app/oauth/register/route.ts
new file mode 100644
index 00000000..036f99a5
--- /dev/null
+++ b/app/oauth/register/route.ts
@@ -0,0 +1,51 @@
+import { registerClient } from "@/lib/mcp/store";
+import { isAllowedRedirect } from "@/lib/mcp/pkce";
+import { mcpEnabled } from "@/lib/mcp/scope";
+import { clientIp } from "@/lib/mcp/origin";
+import { rateLimited } from "@/lib/host";
+
+// RFC 7591 Dynamic Client Registration. Open by design and safe to be: a
+// registered client is INERT until the owner approves it on the consent page and
+// completes PKCE. All this records is a name and a redirect list.
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+
+const bad = (error: string, description: string, status = 400) =>
+ Response.json({ error, error_description: description }, { status, headers: { "Cache-Control": "no-store" } });
+
+export async function POST(req: Request) {
+ if (!mcpEnabled()) return new Response("Not Found", { status: 404 });
+ if (rateLimited(`mcp:dcr:${clientIp(req)}`, 10, 3_600_000)) {
+ return Response.json({ error: "rate_limited" }, { status: 429, headers: { "Retry-After": "3600" } });
+ }
+
+ let body: { redirect_uris?: unknown; client_name?: unknown };
+ try {
+ body = await req.json();
+ } catch {
+ return bad("invalid_request", "body must be JSON");
+ }
+
+ if (!Array.isArray(body.redirect_uris) || body.redirect_uris.length === 0) {
+ return bad("invalid_redirect_uri", "redirect_uris is required and must be a non-empty array");
+ }
+ const uris = [...new Set(body.redirect_uris.map(String).filter(isAllowedRedirect))];
+ // Say WHICH rule was broken. A generic 400 here is why DCR failures are so hard
+ // to debug from the client side — the client cannot see the server's reasoning.
+ if (uris.length === 0) return bad("invalid_redirect_uri", "at least one https (or localhost) redirect_uri is required");
+ if (uris.length > 8) return bad("invalid_client_metadata", "at most 8 redirect_uris");
+
+ const name = typeof body.client_name === "string" ? body.client_name : "MCP Client";
+ const clientId = await registerClient(name, uris);
+ return Response.json(
+ {
+ client_id: clientId,
+ redirect_uris: uris,
+ client_name: name.slice(0, 80),
+ token_endpoint_auth_method: "none",
+ grant_types: ["authorization_code"],
+ response_types: ["code"],
+ },
+ { status: 201, headers: { "Cache-Control": "no-store" } },
+ );
+}
diff --git a/app/oauth/token/route.ts b/app/oauth/token/route.ts
new file mode 100644
index 00000000..2b95f7d4
--- /dev/null
+++ b/app/oauth/token/route.ts
@@ -0,0 +1,52 @@
+import { consumeCode, storeToken, TOKEN_TTL_MS } from "@/lib/mcp/store";
+import { verifyPkce, randomToken } from "@/lib/mcp/pkce";
+import { mcpEnabled } from "@/lib/mcp/scope";
+import { clientIp } from "@/lib/mcp/origin";
+import { rateLimited } from "@/lib/host";
+
+// OAuth token endpoint. authorization_code only, PKCE mandatory.
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+
+const json = (body: unknown, status: number) =>
+ Response.json(body, { status, headers: { "Cache-Control": "no-store", Pragma: "no-cache" } });
+
+export async function POST(req: Request) {
+ if (!mcpEnabled()) return new Response("Not Found", { status: 404 });
+ if (rateLimited(`mcp:token:${clientIp(req)}`, 30, 60_000)) {
+ return Response.json({ error: "rate_limited" }, { status: 429, headers: { "Retry-After": "60" } });
+ }
+
+ // ChatGPT posts form-encoded; some clients post JSON. Accept both.
+ const p: Record<string, string> = {};
+ const ct = req.headers.get("content-type") ?? "";
+ if (ct.includes("application/json")) {
+ Object.assign(p, await req.json().catch(() => ({})));
+ } else {
+ const form = await req.formData().catch(() => null);
+ if (form) for (const [k, v] of form.entries()) p[k] = String(v);
+ }
+
+ if (p.grant_type !== "authorization_code") return json({ error: "unsupported_grant_type" }, 400);
+ if (!p.code || !p.code_verifier || !p.client_id || !p.redirect_uri) return json({ error: "invalid_request" }, 400);
+
+ // Consume FIRST: the row is gone before anything is minted, so a replay (or two
+ // racing retries) finds nothing and gets invalid_grant rather than a second token.
+ const rec = await consumeCode(p.code);
+ // Every failure below is the same opaque invalid_grant — telling a caller which
+ // check failed tells an attacker which half of the guess was right.
+ if (!rec) return json({ error: "invalid_grant" }, 400);
+ if (rec.clientId !== p.client_id || rec.redirectUri !== p.redirect_uri) return json({ error: "invalid_grant" }, 400);
+ if (!verifyPkce(p.code_verifier, rec.codeChallenge, "S256")) return json({ error: "invalid_grant" }, 400);
+
+ const token = randomToken("mso_mcp_");
+ await storeToken(token, {
+ label: `oauth · ${rec.clientId.slice(0, 14)}`,
+ clientId: rec.clientId,
+ scope: rec.scope,
+ });
+ return json(
+ { access_token: token, token_type: "Bearer", scope: rec.scope, expires_in: Math.floor(TOKEN_TTL_MS / 1000) },
+ 200,
+ );
+}
diff --git a/bin/mso b/bin/mso
index a8f60803..b47e829b 100755
--- a/bin/mso
+++ b/bin/mso
@@ -55,6 +55,7 @@
# prefs * UI preferences: show | set
# models * Model catalog: list | test
# skills Skill catalog the assistant sees
+# mcp * MCP bearer tokens: list | revoke <id> | revoke all
# stock <query> [page] Stock-image search (Unsplash key optional, Openverse fallback)
#
# Devices (a local file — these work while the service is down)
@@ -228,6 +229,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_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"
@@ -397,6 +399,15 @@ case "$cmd" in
dev_script "$1" "${@:2}" ;;
revoke) [ -n "${1-}" ] || die "usage: mso revoke <deviceId> (ids: mso device list)"
dev_script --revoke "$1" ;;
+ # ── MCP tokens (the bearers that let ChatGPT et al. drive this host) ─────
+ mcp)
+ case "${1:-list}" in
+ list) jget "/api/mcp/tokens" ;;
+ 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" ;;
+ esac ;;
+
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 b31232ce..d1b22a60 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -89,6 +89,7 @@ Commands:
prefs * UI preferences: show | set
models * Model catalog: list | test
skills Skill catalog the assistant sees
+ mcp * MCP bearer tokens: list | revoke <id> | revoke all
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
new file mode 100644
index 00000000..6052a251
--- /dev/null
+++ b/docs/MCP.md
@@ -0,0 +1,145 @@
+# MCP — drive this VPS from ChatGPT, Claude.ai or Cursor
+
+mso ships an MCP server so an AI client can call the same host operations the web
+UI does: list and read files, write them, check CPU/memory/disk, list processes and
+managed apps, and — if you grant it — run shell commands.
+
+It is **off by default**. While `OS_MCP_ENABLED` is unset, `/mcp` and both OAuth
+discovery documents return 404. There is no MCP surface at all, not an
+unauthenticated one.
+
+## Turn it on
+
+```bash
+# .env.local
+OS_MCP_ENABLED=1
+OS_MCP_MAX_SCOPE=write # read | write | exec — the ceiling the consent screen may grant
+```
+
+Then `bun run build && sudo systemctl restart mso.service` (build THEN restart —
+see CLAUDE.md's deploy hazard).
+
+## Connect ChatGPT
+
+Settings → Connectors → New App. Every field is copy-pasteable from
+**mso → Settings → MCP**.
+
+| Field | Value |
+|---|---|
+| MCP Server URL | `https://mso.rahmanef.com/mcp` |
+| Authentication | `OAuth` |
+| Registration method | `User-Defined OAuth Client` |
+| Client ID | `chatgpt-mso` (any string) |
+| Client Secret | *empty* |
+| Token endpoint auth method | `none` |
+| Auth URL | `https://mso.rahmanef.com/oauth/authorize` |
+| Token URL | `https://mso.rahmanef.com/oauth/token` |
+| Resource | `https://mso.rahmanef.com/mcp` |
+
+Clicking Create sends you to mso's consent screen. **You must already be signed in
+to mso on that device** — the consent page cannot authorize anything on its own;
+it converts an existing approved session into a bearer.
+
+Claude.ai, Cursor and `mcp-remote` register themselves through RFC 7591 DCR — give
+them the MCP Server URL and nothing else.
+
+Verify discovery before you click Create:
+
+```bash
+curl -s https://mso.rahmanef.com/.well-known/oauth-protected-resource | jq
+curl -s https://mso.rahmanef.com/.well-known/oauth-authorization-server | jq
+```
+
+A 404 there is the cause of ChatGPT's unhelpful "MCP server does not implement
+OAuth" — it means `OS_MCP_ENABLED` is not set on the running process.
+
+## The three scopes
+
+Picked per token, on the consent screen, capped by `OS_MCP_MAX_SCOPE`.
+
+| Scope | Tools |
+|---|---|
+| `read` | `fs_list` `fs_read` `fs_search` `fs_usage` `sys_stats` `sys_processes` `apps_list` `browser_status` |
+| `write` | + `fs_write` `fs_mkdir` `fs_move` `fs_copy` `fs_delete` |
+| `exec` | + `exec_run` `browser_power` |
+
+`tools/list` is filtered by the token's scope, and `tools/call` re-checks it — a
+client that calls a tool it was never shown still gets refused.
+
+## What this does and does not protect
+
+Every tool goes through `lib/host`, so the MCP surface inherits the bounds that
+already guard `/api/v1`:
+
+- `OS_FS_READ_ROOTS` / `OS_FS_WRITE_ROOTS`
+- the credential denylist — `~/.ssh`, `~/.gnupg`, cloud and AI tokens, and `~/.mso`
+ itself, so a read tool cannot exfiltrate the device allowlist, the BYOK key or
+ the browser profile's cookies
+- realpath escape checks on every path
+- the catastrophic-command filter in `lib/host/exec.ts` (`rm -rf /`, fork bombs,
+ disk wipes)
+
+The Camoufox viewer URL and its one-time VNC password are deliberately **not**
+returned by `browser_status`. That profile holds a live Google session; its
+credentials never leave the box through a tool result.
+
+**What it does not protect against, and you should decide with open eyes:**
+
+- A bearer is a standing credential. Anyone who obtains it has your scope until you
+ revoke it. Tokens expire after 90 days; that is a backstop, not a control.
+- At `exec` scope, that means arbitrary commands on this VPS as you.
+- Every tool call and its result goes to the client's provider. At `read` scope
+ that is file contents; at `exec` scope it is command output.
+- Prompt injection is real here: content the model READS (a file, a log line, a
+ web page it was told to fetch) can try to talk it into calling a write or exec
+ tool. Scope is the containment — a `read` token cannot be talked into `rm`.
+
+Grant `read` unless you actually need more, and mint a second token when you do.
+
+## Revoking
+
+**mso → Settings → MCP**, or from the CLI:
+
+```bash
+mso mcp list
+mso mcp revoke <id>
+mso mcp revoke all # panic button
+```
+
+Revocation is immediate: the token is re-validated on every single call, so an
+in-flight connector stops on its next request.
+
+## Storage
+
+`~/.mso/mcp.json`, mode 0600, written atomically. It holds **sha256 only** — of
+every authorization code and every bearer. The raw value exists in flight and is
+handed to the client exactly once. A stolen copy of that file tells an attacker
+what was issued, not how to use it.
+
+Authorization codes are single-use with a 60-second TTL and are deleted before the
+token is minted, so a replayed code finds nothing and gets `invalid_grant`.
+
+## Rate limits
+
+Per token: 120 calls/min, 5,000/day. Per IP before auth: 240/min. DCR: 10
+registrations/hour/IP. Token exchange: 30/min/IP. All in-memory (process-local,
+resets on restart) — enough to blunt a runaway agent, which is the realistic
+failure mode for an endpoint whose top scope is a shell.
+
+## Layout
+
+```
+lib/mcp/pkce.ts S256 verify, base64url, hashing, redirect_uri rules
+lib/mcp/scope.ts the read/write/exec ladder + the env kill switch
+lib/mcp/store.ts ~/.mso/mcp.json — clients, codes, tokens (hashed)
+lib/mcp/tools.ts the catalog; every handler is a thin call into lib/host
+lib/mcp/dispatch.ts JSON-RPC: initialize / ping / tools.list / tools.call
+app/mcp/route.ts the endpoint — bearer, rate limits, dispatch
+app/oauth/* authorize (consent) · token · register (DCR)
+app/.well-known/* RFC 9728 + RFC 8414 discovery
+```
+
+`/mcp` lives outside `/api` on purpose: `proxy.ts` blocks mutating `/api` that
+cannot prove same-origin, and an MCP client is cross-origin by definition. The
+CSRF gate is not the control here — the bearer is, and a browser never attaches
+one on its own the way it does a cookie.
diff --git a/frontend/slices/os-settings/components/mcp-section.tsx b/frontend/slices/os-settings/components/mcp-section.tsx
new file mode 100644
index 00000000..8323a3d6
--- /dev/null
+++ b/frontend/slices/os-settings/components/mcp-section.tsx
@@ -0,0 +1,163 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { Plug, Copy, Check } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { SettingsSection } from "@/features/shell-settings";
+import { toast } from "@/features/os-shell";
+import { IS_DEMO } from "@/lib/demo";
+
+type TokenRow = {
+ id: string;
+ label: string;
+ clientId: string;
+ scope: string;
+ createdAt: number;
+ expiresAt: number;
+ lastUsedAt?: number;
+ status: "active" | "revoked" | "expired";
+};
+
+const fmt = (t?: number) => (t ? new Date(t).toLocaleString() : "—");
+
+function CopyRow({ label, value }: { label: string; value: string }) {
+ const [copied, setCopied] = useState(false);
+ return (
+ <div className="flex items-center gap-2 py-1.5">
+ <span className="w-40 shrink-0 text-xs text-muted-foreground">{label}</span>
+ <code className="min-w-0 flex-1 truncate rounded bg-secondary px-2 py-1 font-mono text-[11px]">{value}</code>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ aria-label={`Copy ${label}`}
+ className="size-8 shrink-0 [@media(pointer:coarse)]:size-11"
+ onClick={() => {
+ void navigator.clipboard.writeText(value).then(() => {
+ setCopied(true);
+ setTimeout(() => setCopied(false), 1500);
+ });
+ }}
+ >
+ {copied ? <Check className="size-4" /> : <Copy className="size-4" />}
+ </Button>
+ </div>
+ );
+}
+
+export function McpSection() {
+ const [state, setState] = useState<{ enabled: boolean; maxScope: string; tokens: TokenRow[] } | null>(null);
+ const [origin, setOrigin] = useState("");
+
+ const load = useCallback(() => {
+ if (IS_DEMO) return;
+ fetch("/api/mcp/tokens", { cache: "no-store" })
+ .then((r) => (r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`))))
+ .then((s) => {
+ // Read the origin here rather than in the effect body: window.location is
+ // an impure render-time read, and a synchronous setState in an effect is a
+ // cascading render. Both are lint errors, and both are avoidable by doing
+ // it once, in the callback that already updates this component.
+ setOrigin(window.location.origin);
+ setState(s);
+ })
+ .catch(() => toast("Couldn't load MCP tokens", { tone: "error" }));
+ }, []);
+
+ useEffect(load, [load]);
+
+ async function revoke(id: string, what: string) {
+ const r = await fetch(`/api/mcp/tokens?id=${encodeURIComponent(id)}`, { method: "DELETE" });
+ if (!r.ok) {
+ toast(`Couldn't revoke ${what}`, { tone: "error" });
+ return;
+ }
+ toast(`Revoked ${what}. Any client using it is cut off now.`);
+ load();
+ }
+
+ const live = state?.tokens.filter((t) => t.status === "active") ?? [];
+
+ return (
+ <SettingsSection
+ icon={<Plug />}
+ title="MCP — control this VPS from ChatGPT"
+ footnote="Tokens are stored as a hash; the raw value is shown to the client once, at mint. Revoking is immediate — it is re-checked on every call."
+ >
+ {!state?.enabled ? (
+ <p className="text-xs text-muted-foreground">
+ Disabled. Set <code className="font-mono">OS_MCP_ENABLED=1</code> in <code className="font-mono">.env.local</code>{" "}
+ and restart mso.service. While it is off, <code className="font-mono">/mcp</code> and the OAuth
+ discovery documents return 404 — there is no MCP surface at all, not an unauthenticated one.
+ </p>
+ ) : (
+ <>
+ <div className="space-y-0.5">
+ <p className="pb-1 text-xs text-muted-foreground">
+ In ChatGPT: Settings → Connectors → New App. Authentication <strong>OAuth</strong>, registration{" "}
+ <strong>User-Defined OAuth Client</strong>, Client Secret <strong>empty</strong>, token endpoint auth{" "}
+ <strong>none</strong>.
+ </p>
+ <CopyRow label="MCP Server URL" value={`${origin}/mcp`} />
+ <CopyRow label="Auth URL" value={`${origin}/oauth/authorize`} />
+ <CopyRow label="Token URL" value={`${origin}/oauth/token`} />
+ <CopyRow label="Resource" value={`${origin}/mcp`} />
+ <CopyRow label="Client ID" value="chatgpt-mso" />
+ <p className="pt-1 text-xs text-muted-foreground">
+ Claude.ai, Cursor and mcp-remote register themselves — give them{" "}
+ <code className="font-mono">{origin}/mcp</code> and nothing else. Highest tier this server will
+ mint: <strong>{state.maxScope}</strong> (<code className="font-mono">OS_MCP_MAX_SCOPE</code>).
+ </p>
+ </div>
+
+ <div className="mt-3 border-t border-border pt-3">
+ {state.tokens.length === 0 ? (
+ <p className="text-xs text-muted-foreground">
+ No tokens yet. One is minted when you approve a client on the consent screen.
+ </p>
+ ) : (
+ <ul className="space-y-1.5">
+ {state.tokens.map((t) => {
+ const dead = t.status !== "active";
+ return (
+ <li key={t.id} className="flex items-center gap-2 text-xs">
+ <span className={dead ? "min-w-0 flex-1 truncate text-muted-foreground line-through" : "min-w-0 flex-1 truncate"}>
+ {t.label}
+ <span className="ml-1.5 rounded bg-secondary px-1.5 py-0.5 font-mono text-[10px]">{t.scope}</span>
+ </span>
+ <span className="hidden shrink-0 text-muted-foreground sm:inline">last used {fmt(t.lastUsedAt)}</span>
+ {dead ? (
+ <span className="shrink-0 text-muted-foreground">{t.status}</span>
+ ) : (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="h-8 shrink-0 text-destructive [@media(pointer:coarse)]:min-h-[44px]"
+ onClick={() => void revoke(t.id, t.label)}
+ >
+ Revoke
+ </Button>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ {live.length > 0 && (
+ <Button
+ type="button"
+ variant="secondary"
+ size="sm"
+ className="mt-3 w-full text-destructive [@media(pointer:coarse)]:min-h-[44px]"
+ onClick={() => void revoke("all", `all ${live.length} live token(s)`)}
+ >
+ Revoke all ({live.length})
+ </Button>
+ )}
+ </div>
+ </>
+ )}
+ </SettingsSection>
+ );
+}
diff --git a/frontend/slices/os-settings/components/nav.tsx b/frontend/slices/os-settings/components/nav.tsx
index 812d97a5..9e9caf97 100644
--- a/frontend/slices/os-settings/components/nav.tsx
+++ b/frontend/slices/os-settings/components/nav.tsx
@@ -6,6 +6,7 @@ import {
Link2,
Paintbrush,
Palette,
+ Plug,
Server,
ShieldCheck,
Sparkles,
@@ -14,7 +15,7 @@ import {
import { cn } from "@/lib/utils";
export type SectionId =
- | "appearance" | "theme" | "ai" | "quicklinks" | "devices" | "server" | "cleanup" | "about";
+ | "appearance" | "theme" | "ai" | "quicklinks" | "mcp" | "devices" | "server" | "cleanup" | "about";
// Semantic buckets for the iOS grouped index (mobile). Reorder-safe: the mobile
// cards derive from this field, not an index slice, so adding/reordering a
@@ -36,6 +37,7 @@ export const SECTIONS: ReadonlyArray<{
{ id: "theme", label: "Theme", blurb: "Mode, presets, font, contrast", icon: Paintbrush, color: "#ff375f", group: "personalization" },
{ id: "ai", label: "AI", blurb: "Model and API key", icon: Sparkles, color: "#bf5af2", group: "services" },
{ id: "quicklinks", label: "Quicklink", blurb: "Website shortcuts with favicons", icon: Link2, color: "#5e5ce6", group: "services" },
+ { id: "mcp", label: "MCP", blurb: "Control this VPS from ChatGPT", icon: Plug, color: "#00c7be", group: "services" },
{ id: "devices", label: "Devices", blurb: "Approved browsers and sessions", icon: ShieldCheck, color: "#30d158", group: "system" },
{ id: "server", label: "Server", blurb: "Mock or live host data", icon: Server, color: "#ff9f0a", group: "system" },
{ id: "cleanup", label: "Cleanup", blurb: "Free disk space safely", icon: Trash2, color: "#64d2ff", group: "system" },
diff --git a/frontend/slices/os-settings/components/sections.tsx b/frontend/slices/os-settings/components/sections.tsx
index d30f13fb..b8b80127 100644
--- a/frontend/slices/os-settings/components/sections.tsx
+++ b/frontend/slices/os-settings/components/sections.tsx
@@ -13,6 +13,7 @@ import { ThemeSection } from "./theme-section";
import { AiSection } from "./ai-section";
import { MemorySection } from "./memory-section";
import { QuicklinksSection } from "./quicklinks-section";
+import { McpSection } from "./mcp-section";
import { ServerSection } from "./server-section";
import { CleanupSection } from "./cleanup-section";
import { AboutSection } from "./about-section";
@@ -35,6 +36,8 @@ function SectionBody({ id }: { id: SectionId }) {
);
case "quicklinks":
return <QuicklinksSection />;
+ case "mcp":
+ return <McpSection />;
case "devices":
return (
<div className="space-y-4 sm:space-y-5">
diff --git a/lib/mcp/dispatch.test.ts b/lib/mcp/dispatch.test.ts
new file mode 100644
index 00000000..a003c715
--- /dev/null
+++ b/lib/mcp/dispatch.test.ts
@@ -0,0 +1,120 @@
+import { describe, it, expect, vi } 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", () => ({}));
+const { dispatch, isNotification } = await import("./dispatch");
+const { TOOLS } = await import("./tools");
+
+const call = (name: string, args: Record<string, unknown> = {}) =>
+ ({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } });
+
+describe("protocol", () => {
+ it("echoes the client's protocolVersion when it sends one", async () => {
+ const r = await dispatch({ id: 1, method: "initialize", params: { protocolVersion: "2025-06-18" } }, "read");
+ expect((r.result as Record<string, unknown>).protocolVersion).toBe("2025-06-18");
+ });
+
+ it("answers ping and initialized", async () => {
+ expect(await dispatch({ id: 2, method: "ping" }, "read")).toMatchObject({ result: {} });
+ expect(await dispatch({ id: 3, method: "notifications/initialized" }, "read")).toMatchObject({ result: {} });
+ });
+
+ it("returns a JSON-RPC error for an unknown method", async () => {
+ const r = await dispatch({ id: 4, method: "tools/nope" }, "read");
+ expect((r.error as { code: number }).code).toBe(-32601);
+ });
+
+ it("recognises notifications, which must be acked without a body", () => {
+ expect(isNotification({ jsonrpc: "2.0", method: "notifications/cancelled" })).toBe(true);
+ expect(isNotification({ jsonrpc: "2.0", id: 1, method: "tools/list" })).toBe(false);
+ expect(isNotification({ jsonrpc: "2.0", id: 1, method: "notifications/initialized" })).toBe(false);
+ });
+});
+
+describe("tools/list is scope-filtered", () => {
+ const names = async (scope: "read" | "write" | "exec") => {
+ const r = await dispatch({ id: 1, method: "tools/list" }, scope);
+ return ((r.result as { tools: { name: string }[] }).tools).map((t) => t.name);
+ };
+
+ it("shows a read token only read tools", async () => {
+ const n = await names("read");
+ expect(n).toContain("fs_list");
+ expect(n).toContain("sys_stats");
+ expect(n).not.toContain("fs_write");
+ expect(n).not.toContain("exec_run");
+ });
+
+ it("shows a write token everything but the shell", async () => {
+ const n = await names("write");
+ expect(n).toContain("fs_write");
+ expect(n).toContain("fs_delete");
+ expect(n).not.toContain("exec_run");
+ expect(n).not.toContain("browser_power");
+ });
+
+ it("shows an exec token the whole catalog", async () => {
+ expect(await names("exec")).toHaveLength(TOOLS.length);
+ });
+});
+
+describe("tools/call enforces scope even when the tool was never listed", () => {
+ it("refuses exec_run for a write token, and says how to fix it", async () => {
+ const r = await dispatch(call("exec_run", { command: "id" }), "write");
+ const res = r.result as { isError: boolean; content: { text: string }[] };
+ expect(res.isError).toBe(true);
+ expect(res.content[0].text).toContain('needs "exec"');
+ // NOT a JSON-RPC error — ChatGPT hides those from the user entirely.
+ expect(r.error).toBeUndefined();
+ });
+
+ it("refuses fs_delete for a read token", async () => {
+ const r = await dispatch(call("fs_delete", { path: "/tmp/x" }), "read");
+ expect((r.result as { isError: boolean }).isError).toBe(true);
+ });
+
+ it("rejects an unknown tool name", async () => {
+ expect((await dispatch(call("rm_rf_slash"), "exec")).error).toMatchObject({ code: -32602 });
+ });
+
+ it("rejects a call missing a required argument before running anything", async () => {
+ expect((await dispatch(call("fs_read", {}), "read")).error).toMatchObject({ code: -32602 });
+ });
+
+ it("returns a handler failure as isError text, never as a protocol error", async () => {
+ // Outside every read root → lib/host refuses. The point is the SHAPE.
+ const r = await dispatch(call("fs_read", { path: "/proc/1/environ" }), "read");
+ expect(r.error).toBeUndefined();
+ expect((r.result as { isError?: boolean }).isError).toBe(true);
+ });
+});
+
+describe("catalog hygiene", () => {
+ it("every tool is snake_case and uniquely named", () => {
+ const names = TOOLS.map((t) => t.name);
+ expect(new Set(names).size).toBe(names.length);
+ for (const n of names) expect(n).toMatch(/^[a-z][a-z0-9_]*$/);
+ });
+
+ it("every required arg is declared in properties — a mismatch is unfixable by the model", () => {
+ for (const t of TOOLS) {
+ for (const k of t.inputSchema.required ?? []) {
+ expect(Object.keys(t.inputSchema.properties), `${t.name}.${k}`).toContain(k);
+ }
+ }
+ });
+
+ it("read-scope tools are all annotated readOnlyHint, and no write tool claims it", () => {
+ for (const t of TOOLS) {
+ if (t.scope === "read") expect(t.annotations?.readOnlyHint, t.name).toBe(true);
+ else expect(t.annotations?.readOnlyHint, t.name).not.toBe(true);
+ }
+ });
+
+ it("the irreversible tools carry destructiveHint so clients keep prompting", () => {
+ for (const name of ["fs_delete", "exec_run", "browser_power"]) {
+ expect(TOOLS.find((t) => t.name === name)?.annotations?.destructiveHint, name).toBe(true);
+ }
+ });
+});
diff --git a/lib/mcp/dispatch.ts b/lib/mcp/dispatch.ts
new file mode 100644
index 00000000..5cd6d18e
--- /dev/null
+++ b/lib/mcp/dispatch.ts
@@ -0,0 +1,90 @@
+import { TOOLS, TOOLS_BY_NAME } from "./tools";
+import { allows, type Scope } from "./scope";
+
+// JSON-RPC 2.0 dispatch for the MCP server. No SDK: the surface is initialize,
+// ping, notifications/*, tools/list and tools/call, and hand-rolling it is far
+// less code than adapting a transport we do not use.
+
+export interface RpcRequest {
+ jsonrpc?: string;
+ id?: string | number | null;
+ method?: string;
+ params?: { name?: string; arguments?: Record<string, unknown>; protocolVersion?: string };
+}
+
+// Newest version every shipping client still accepts. We echo the client's own
+// version when it sends one, per the spec's negotiation rule.
+const PROTOCOL = "2024-11-05";
+
+export const UNAUTHORIZED = -32001;
+export const RATE_LIMITED = -32029;
+
+const ok = (id: RpcRequest["id"], result: unknown) => ({ jsonrpc: "2.0", id: id ?? null, result });
+const fail = (id: RpcRequest["id"], code: number, message: string) =>
+ ({ jsonrpc: "2.0", id: id ?? null, error: { code, message } });
+
+/** True for a JSON-RPC notification — no id, expects no response body. */
+export function isNotification(body: unknown): boolean {
+ const b = body as RpcRequest | null;
+ return b?.id == null && String(b?.method ?? "").startsWith("notifications/");
+}
+
+function toolList(scope: Scope) {
+ // Only advertise what this token can actually call. A tool listed but refused
+ // on use makes the model retry the same dead call; not listing it makes the
+ // model route around it, which is the behaviour we want from a read-only token.
+ return TOOLS.filter((t) => allows(scope, t.scope)).map((t) => ({
+ name: t.name,
+ description: t.description,
+ inputSchema: t.inputSchema,
+ ...(t.annotations ? { annotations: t.annotations } : {}),
+ }));
+}
+
+export async function dispatch(req: RpcRequest, scope: Scope): Promise<Record<string, unknown>> {
+ const id = req.id ?? null;
+ switch (req.method) {
+ case "initialize":
+ return ok(id, {
+ protocolVersion: req.params?.protocolVersion ?? PROTOCOL,
+ capabilities: { tools: { listChanged: false } },
+ serverInfo: { name: "mso", version: "1.0.0" },
+ });
+ case "notifications/initialized":
+ case "ping":
+ return ok(id, {});
+ case "tools/list":
+ return ok(id, { tools: toolList(scope) });
+ case "tools/call": {
+ const name = String(req.params?.name ?? "");
+ const args = req.params?.arguments ?? {};
+ const tool = TOOLS_BY_NAME.get(name);
+ if (!tool) return fail(id, -32602, `unknown tool: ${name}`);
+ // 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)) {
+ 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,
+ });
+ }
+ for (const k of tool.inputSchema.required ?? []) {
+ if (args[k] == null) return fail(id, -32602, `${name} needs { ${(tool.inputSchema.required ?? []).join(", ")} }`);
+ }
+ try {
+ const result = await tool.run(args);
+ 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);
+ return ok(id, { content: [{ type: "text", text: "error: " + msg.slice(0, 500) }], isError: true });
+ }
+ }
+ default:
+ return fail(id, -32601, `unknown method: ${req.method}`);
+ }
+}
+
+export { fail as rpcError };
diff --git a/lib/mcp/origin.ts b/lib/mcp/origin.ts
new file mode 100644
index 00000000..8edc9961
--- /dev/null
+++ b/lib/mcp/origin.ts
@@ -0,0 +1,33 @@
+// The origin an MCP client must be told to use. Discovery metadata is
+// origin-scoped (RFC 8414 / 9728), so getting this wrong is the single most common
+// way a connector fails with "MCP server does not implement OAuth".
+//
+// Precedence mirrors lib/managed-apps/proxy-headers: OS_PUBLIC_ORIGIN is
+// deployment-owned and wins; the real Host header comes next; X-Forwarded-Host is
+// client-settable and is consulted LAST.
+export function publicOrigin(req: Request): string {
+ const explicit = process.env.OS_PUBLIC_ORIGIN?.trim();
+ if (explicit) {
+ try {
+ return new URL(explicit).origin;
+ } catch {
+ // Misconfigured value (a bare hostname, no scheme) — fall through to the
+ // headers rather than emit a URL no client can resolve.
+ }
+ }
+ const url = new URL(req.url);
+ const proto = req.headers.get("x-forwarded-proto")?.split(",")[0].trim() || url.protocol.replace(":", "");
+ const host = req.headers.get("host") ?? req.headers.get("x-forwarded-host") ?? url.host;
+ return `${proto}://${host}`;
+}
+
+/** Best-effort client IP for the pre-auth rate limiter. Spoofable behind a proxy
+ * that does not overwrite the header — which is why it only ever gates rate
+ * limits, never authorization. */
+export function clientIp(req: Request): string {
+ return (
+ req.headers.get("x-forwarded-for")?.split(",")[0].trim() ||
+ req.headers.get("x-real-ip")?.trim() ||
+ "unknown"
+ );
+}
diff --git a/lib/mcp/pkce.test.ts b/lib/mcp/pkce.test.ts
new file mode 100644
index 00000000..4db1b362
--- /dev/null
+++ b/lib/mcp/pkce.test.ts
@@ -0,0 +1,75 @@
+import { describe, it, expect } from "vitest";
+import { createHash } from "node:crypto";
+import { sha256b64url, verifyPkce, isAllowedRedirect, randomToken, safeEqualHex } from "./pkce";
+
+const VERIFIER = "a".repeat(43);
+const CHALLENGE = createHash("sha256").update(VERIFIER).digest("base64url");
+
+describe("sha256b64url", () => {
+ it("is base64URL, never standard base64 — a `+` or `/` here never matches a real client", () => {
+ // A payload whose sha256 contains bytes that encode to + and / in std base64.
+ for (let i = 0; i < 200; i++) {
+ const out = sha256b64url(`probe-${i}`);
+ expect(out).not.toMatch(/[+/=]/);
+ }
+ });
+});
+
+describe("verifyPkce", () => {
+ it("accepts the verifier that produced the challenge", () => {
+ expect(verifyPkce(VERIFIER, CHALLENGE, "S256")).toBe(true);
+ });
+
+ it("rejects a different verifier", () => {
+ expect(verifyPkce("b".repeat(43), CHALLENGE, "S256")).toBe(false);
+ });
+
+ it("refuses the `plain` method — OAuth 2.1 drops it and it defeats the whole point", () => {
+ expect(verifyPkce(CHALLENGE, CHALLENGE, "plain")).toBe(false);
+ expect(verifyPkce(VERIFIER, CHALLENGE, "")).toBe(false);
+ });
+
+ it("enforces RFC 7636 §4.1 length bounds", () => {
+ const short = "a".repeat(42);
+ const long = "a".repeat(129);
+ expect(verifyPkce(short, sha256b64url(short), "S256")).toBe(false);
+ expect(verifyPkce(long, sha256b64url(long), "S256")).toBe(false);
+ });
+
+ it("rejects characters outside the unreserved set", () => {
+ const bad = "a".repeat(42) + "/";
+ expect(verifyPkce(bad, sha256b64url(bad), "S256")).toBe(false);
+ });
+});
+
+describe("isAllowedRedirect", () => {
+ it.each([
+ ["https://chatgpt.com/connector_platform_oauth_redirect", true],
+ ["http://localhost:6274/callback", true],
+ ["http://127.0.0.1:9999/cb", true],
+ ["http://evil.example/cb", false], // plaintext on the internet leaks the code
+ ["javascript:alert(1)", false],
+ ["mso://cb", false],
+ ["not a url", false],
+ ])("%s → %s", (uri, expected) => {
+ expect(isAllowedRedirect(uri)).toBe(expected);
+ });
+});
+
+describe("randomToken", () => {
+ it("is prefixed, url-safe and not repeatable", () => {
+ const a = randomToken("mso_mcp_");
+ const b = randomToken("mso_mcp_");
+ expect(a.startsWith("mso_mcp_")).toBe(true);
+ expect(a).not.toBe(b);
+ expect(a.slice(8)).not.toMatch(/[+/=]/);
+ expect(a.length).toBeGreaterThan(40);
+ });
+});
+
+describe("safeEqualHex", () => {
+ it("is false for different lengths instead of throwing", () => {
+ expect(safeEqualHex("abc", "abcd")).toBe(false);
+ expect(safeEqualHex("abcd", "abcd")).toBe(true);
+ });
+});
diff --git a/lib/mcp/pkce.ts b/lib/mcp/pkce.ts
new file mode 100644
index 00000000..a30a250a
--- /dev/null
+++ b/lib/mcp/pkce.ts
@@ -0,0 +1,53 @@
+import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
+
+// PKCE (RFC 7636) + the hashing every MCP secret is stored under. Raw codes and
+// raw bearers exist only in flight: the store only ever holds sha256, so a leaked
+// ~/.mso/mcp.json cannot be replayed against the server.
+
+export function sha256hex(s: string): string {
+ return createHash("sha256").update(s).digest("hex");
+}
+
+/** base64url, NOT base64 — `+`→`-`, `/`→`_`, no padding. Standard base64 here
+ * silently produces a challenge that never matches (RFC 7636 §4.2). */
+export function sha256b64url(s: string): string {
+ return createHash("sha256").update(s).digest("base64url");
+}
+
+export function randomToken(prefix: string, bytes = 32): string {
+ return prefix + randomBytes(bytes).toString("base64url");
+}
+
+/** Constant-time for equal-length input; length itself is not a secret. */
+export function safeEqualHex(a: string, b: string): boolean {
+ if (a.length !== b.length) return false;
+ return timingSafeEqual(Buffer.from(a), Buffer.from(b));
+}
+
+/**
+ * True when `verifier` is the one that produced `challenge`.
+ *
+ * `plain` is refused outright — OAuth 2.1 drops it, and accepting it would mean a
+ * proxy that saw the authorization redirect could complete the exchange itself.
+ * The 43..128 bound is RFC 7636 §4.1: anything outside it cannot be a verifier at
+ * all, so rejecting early keeps a malformed value out of the hash comparison.
+ */
+export function verifyPkce(verifier: string, challenge: string, method: string): boolean {
+ if (method !== "S256") return false;
+ if (typeof verifier !== "string" || verifier.length < 43 || verifier.length > 128) return false;
+ if (!/^[A-Za-z0-9\-._~]+$/.test(verifier)) return false;
+ const computed = sha256b64url(verifier);
+ return computed.length === challenge.length && safeEqualHex(computed, challenge);
+}
+
+/** https, or loopback for a desktop client's local callback. Anything else — a
+ * custom scheme, an http host on the internet — can leak the code in transit. */
+export function isAllowedRedirect(u: string): boolean {
+ try {
+ const url = new URL(u);
+ if (url.protocol === "https:") return true;
+ return url.protocol === "http:" && (url.hostname === "localhost" || url.hostname === "127.0.0.1");
+ } catch {
+ return false;
+ }
+}
diff --git a/lib/mcp/scope.test.ts b/lib/mcp/scope.test.ts
new file mode 100644
index 00000000..9163a9a9
--- /dev/null
+++ b/lib/mcp/scope.test.ts
@@ -0,0 +1,80 @@
+import { describe, it, expect, afterEach } from "vitest";
+import { parseScope, allows, mcpEnabled, maxScope, clampScope } from "./scope";
+
+const env = { ...process.env };
+afterEach(() => {
+ process.env = { ...env };
+});
+
+describe("parseScope", () => {
+ it("defaults to least privilege for absent or unknown input", () => {
+ expect(parseScope(undefined)).toBe("read");
+ expect(parseScope("")).toBe("read");
+ expect(parseScope("admin root sudo")).toBe("read");
+ });
+
+ it("takes the HIGHEST tier present, so a space-separated grant is not silently narrowed", () => {
+ expect(parseScope("read write")).toBe("write");
+ expect(parseScope("exec read")).toBe("exec");
+ expect(parseScope("read,write,exec")).toBe("exec");
+ });
+});
+
+describe("allows", () => {
+ it("is a ladder — a higher tier implies every lower one", () => {
+ expect(allows("exec", "read")).toBe(true);
+ expect(allows("exec", "write")).toBe(true);
+ expect(allows("write", "read")).toBe(true);
+ expect(allows("read", "read")).toBe(true);
+ });
+
+ it("never lets a lower tier reach a higher one", () => {
+ expect(allows("read", "write")).toBe(false);
+ expect(allows("read", "exec")).toBe(false);
+ expect(allows("write", "exec")).toBe(false); // the one that matters: no shell
+ });
+});
+
+describe("mcpEnabled", () => {
+ it("is OFF unless explicitly turned on", () => {
+ delete process.env.OS_MCP_ENABLED;
+ expect(mcpEnabled()).toBe(false);
+ process.env.OS_MCP_ENABLED = "0";
+ expect(mcpEnabled()).toBe(false);
+ process.env.OS_MCP_ENABLED = "true"; // only "1" counts
+ expect(mcpEnabled()).toBe(false);
+ process.env.OS_MCP_ENABLED = "1";
+ expect(mcpEnabled()).toBe(true);
+ });
+
+ it("stays off in demo mode even when enabled — demo has no login at all", () => {
+ process.env.OS_MCP_ENABLED = "1";
+ process.env.NEXT_PUBLIC_OS_DEMO = "1";
+ expect(mcpEnabled()).toBe(false);
+ });
+});
+
+describe("maxScope / clampScope", () => {
+ it("defaults the ceiling to write, so shell access is opt-in twice", () => {
+ delete process.env.OS_MCP_MAX_SCOPE;
+ expect(maxScope()).toBe("write");
+ expect(clampScope("exec")).toBe("write");
+ });
+
+ it("honours a lower ceiling", () => {
+ process.env.OS_MCP_MAX_SCOPE = "read";
+ expect(clampScope("exec")).toBe("read");
+ expect(clampScope("write")).toBe("read");
+ });
+
+ it("lets exec through only when the deployment asks for it", () => {
+ process.env.OS_MCP_MAX_SCOPE = "exec";
+ expect(clampScope("exec")).toBe("exec");
+ expect(clampScope("read")).toBe("read"); // never widens
+ });
+
+ it("falls back to write on a junk value rather than to exec", () => {
+ process.env.OS_MCP_MAX_SCOPE = "root";
+ expect(maxScope()).toBe("write");
+ });
+});
diff --git a/lib/mcp/scope.ts b/lib/mcp/scope.ts
new file mode 100644
index 00000000..82bce994
--- /dev/null
+++ b/lib/mcp/scope.ts
@@ -0,0 +1,49 @@
+// What an MCP bearer is allowed to do. mso is single-owner, so a token is not an
+// identity — it IS the capability, and the only thing standing between a leaked
+// bearer and the host is this tier.
+//
+// Deliberately three tiers, not one: "let ChatGPT read my VPS" and "let ChatGPT
+// run shell commands as me" are wildly different bets, and a connector that only
+// ever needs to read files should not hold the second one. The owner picks per
+// token on the consent page.
+
+export const SCOPES = ["read", "write", "exec"] as const;
+export type Scope = (typeof SCOPES)[number];
+
+/** Ranked: holding a tier implies every tier below it. */
+const RANK: Record<Scope, number> = { read: 0, write: 1, exec: 2 };
+
+export function parseScope(raw: string | undefined | null): Scope {
+ const asked = String(raw ?? "")
+ .split(/[\s,]+/)
+ .filter((s): s is Scope => (SCOPES as readonly string[]).includes(s));
+ if (asked.length === 0) return "read"; // unknown/absent → least privilege
+ return asked.reduce((a, b) => (RANK[b] > RANK[a] ? b : a));
+}
+
+export function allows(held: Scope, needed: Scope): boolean {
+ return RANK[held] >= RANK[needed];
+}
+
+/** MCP is OFF unless the owner turns it on. An install that never sets this has
+ * no MCP surface at all — not an unauthenticated one, none. Demo mode disables
+ * login entirely, so it must never expose a host-control endpoint either. */
+export function mcpEnabled(): boolean {
+ if (process.env.NEXT_PUBLIC_OS_DEMO === "1") return false;
+ return process.env.OS_MCP_ENABLED === "1";
+}
+
+/** The ceiling the deployment allows, whatever a consent page asks for. Set
+ * `OS_MCP_MAX_SCOPE=read` to make it impossible to mint an exec token even by
+ * accident. Defaults to `write`: shell access is opt-in, twice. */
+export function maxScope(): Scope {
+ const raw = process.env.OS_MCP_MAX_SCOPE;
+ if (!raw) return "write";
+ const s = String(raw).trim();
+ return (SCOPES as readonly string[]).includes(s) ? (s as Scope) : "write";
+}
+
+export function clampScope(asked: Scope): Scope {
+ const ceiling = maxScope();
+ return RANK[asked] > RANK[ceiling] ? ceiling : asked;
+}
diff --git a/lib/mcp/store.test.ts b/lib/mcp/store.test.ts
new file mode 100644
index 00000000..a4a5c5bd
--- /dev/null
+++ b/lib/mcp/store.test.ts
@@ -0,0 +1,116 @@
+import { describe, it, expect, beforeEach, afterAll } from "vitest";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+const DIR = path.join(os.tmpdir(), `mso-mcp-test-${process.pid}`);
+process.env.OS_MCP_STORE = path.join(DIR, "mcp.json");
+
+const store = await import("./store");
+const { sha256hex } = await import("./pkce");
+
+beforeEach(async () => {
+ await fs.rm(DIR, { recursive: true, force: true });
+});
+afterAll(async () => {
+ await fs.rm(DIR, { recursive: true, force: true });
+});
+
+describe("codes", () => {
+ const rec = () => ({
+ clientId: "c1",
+ redirectUri: "https://chatgpt.com/cb",
+ codeChallenge: "chal",
+ scope: "read" as const,
+ expiresAt: Date.now() + 60_000,
+ });
+
+ it("round-trips a code exactly once — a replay finds nothing", async () => {
+ await store.storeCode("code-1", rec());
+ expect(await store.consumeCode("code-1")).toMatchObject({ clientId: "c1", scope: "read" });
+ expect(await store.consumeCode("code-1")).toBeNull();
+ });
+
+ it("refuses an expired code", async () => {
+ await store.storeCode("old", { ...rec(), expiresAt: Date.now() - 1 });
+ expect(await store.consumeCode("old")).toBeNull();
+ });
+
+ it("never writes the raw code to disk", async () => {
+ await store.storeCode("super-secret-code", rec());
+ const raw = await fs.readFile(process.env.OS_MCP_STORE!, "utf8");
+ expect(raw).not.toContain("super-secret-code");
+ expect(raw).toContain(sha256hex("super-secret-code"));
+ });
+});
+
+describe("tokens", () => {
+ const mint = (t: string, scope: "read" | "write" | "exec" = "read") =>
+ store.storeToken(t, { label: "test", clientId: "c1", scope });
+
+ it("validates a live token and never stores it raw", async () => {
+ await mint("tok-live");
+ expect(await store.validateToken("tok-live")).toMatchObject({ scope: "read", label: "test" });
+ const raw = await fs.readFile(process.env.OS_MCP_STORE!, "utf8");
+ expect(raw).not.toContain("tok-live");
+ });
+
+ it("rejects an unknown token", async () => {
+ expect(await store.validateToken("nope")).toBeNull();
+ expect(await store.validateToken("")).toBeNull();
+ });
+
+ it("stops validating the instant a token is revoked — this IS the kill switch", async () => {
+ await mint("tok-revoke");
+ const listed = (await store.listTokens())[0];
+ expect(await store.revokeToken(listed.id)).toBe(true);
+ expect(await store.validateToken("tok-revoke")).toBeNull();
+ expect(await store.revokeToken(listed.id)).toBe(false); // already dead
+ });
+
+ it("revokeAll kills every live token and reports the count", async () => {
+ await mint("a");
+ await mint("b");
+ await mint("c");
+ expect(await store.revokeAllTokens()).toBe(3);
+ expect(await store.validateToken("b")).toBeNull();
+ expect(await store.revokeAllTokens()).toBe(0);
+ });
+
+ it("carries the granted scope through, so a read token cannot become an exec one", async () => {
+ await mint("ro", "read");
+ await mint("rw", "exec");
+ expect((await store.validateToken("ro"))!.scope).toBe("read");
+ expect((await store.validateToken("rw"))!.scope).toBe("exec");
+ });
+});
+
+describe("clients", () => {
+ it("returns the SAME id for an identical redirect set — clients re-register on every launch", async () => {
+ const a = await store.registerClient("Cursor", ["https://cursor.sh/cb"]);
+ const b = await store.registerClient("Cursor", ["https://cursor.sh/cb"]);
+ expect(b).toBe(a);
+ const c = await store.registerClient("Cursor", ["https://cursor.sh/other"]);
+ expect(c).not.toBe(a);
+ });
+
+ it("reads back a registered client", async () => {
+ const id = await store.registerClient("Claude", ["https://claude.ai/cb"]);
+ expect(await store.getClient(id)).toMatchObject({ name: "Claude", redirectUris: ["https://claude.ai/cb"] });
+ expect(await store.getClient("mcpc_nope")).toBeNull();
+ });
+});
+
+describe("read()", () => {
+ it("throws on a corrupt file instead of silently reporting an empty store", async () => {
+ await fs.mkdir(DIR, { recursive: true });
+ await fs.writeFile(process.env.OS_MCP_STORE!, "{not json");
+ // Same rule as lib/auth/device-store: swallowing this would make the next
+ // write erase every issued token AND keep honouring revoked ones.
+ await expect(store.listTokens()).rejects.toThrow();
+ });
+
+ it("treats a missing file as empty", async () => {
+ expect(await store.listTokens()).toEqual([]);
+ });
+});
diff --git a/lib/mcp/store.ts b/lib/mcp/store.ts
new file mode 100644
index 00000000..4498d1e1
--- /dev/null
+++ b/lib/mcp/store.ts
@@ -0,0 +1,193 @@
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { sha256hex } from "./pkce";
+import type { Scope } from "./scope";
+
+// OAuth clients, authorization codes and bearer tokens for the MCP server.
+// mso has no database, so this is the same shape lib/auth/device-store.ts uses:
+// one JSON file under ~/.mso, written atomically (tmp + rename, 0600).
+//
+// SECRETS ARE NEVER STORED RAW. Codes and tokens live here as sha256 only; the
+// raw value is returned to the client exactly once, at mint. A stolen copy of
+// this file leaks WHAT was issued, not a usable credential.
+
+export interface McpClient {
+ name: string;
+ redirectUris: string[];
+ createdAt: number;
+}
+
+export interface McpCode {
+ clientId: string;
+ redirectUri: string;
+ codeChallenge: string;
+ scope: Scope;
+ expiresAt: number;
+}
+
+export interface McpToken {
+ label: string;
+ clientId: string;
+ scope: Scope;
+ createdAt: number;
+ expiresAt: number;
+ lastUsedAt?: number;
+ revokedAt?: number;
+}
+
+interface Store {
+ clients: Record<string, McpClient>;
+ codes: Record<string, McpCode>;
+ tokens: Record<string, McpToken>;
+}
+
+const STORE_PATH = process.env.OS_MCP_STORE ?? path.join(os.homedir(), ".mso", "mcp.json");
+
+export const CODE_TTL_MS = 60_000; // RFC 6749 wants ≤10 min; the exchange is immediate
+export const TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000; // 90d — a forgotten bearer expires
+const MAX_CLIENTS = 32;
+
+const empty = (): Store => ({ clients: {}, codes: {}, tokens: {} });
+
+// Same rule as device-store: "no file yet" is the ONLY failure that may read as an
+// empty store. A corrupt file or EACCES must throw, because read() feeds a
+// read-modify-write — swallowing it would silently erase every issued token and,
+// worse, keep answering requests as if nothing had been revoked.
+async function read(): Promise<Store> {
+ let raw: string;
+ try {
+ raw = await fs.readFile(STORE_PATH, "utf8");
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException).code === "ENOENT") return empty();
+ throw e;
+ }
+ const p = JSON.parse(raw) as Partial<Store>;
+ return { clients: p.clients ?? {}, codes: p.codes ?? {}, tokens: p.tokens ?? {} };
+}
+
+async function write(store: Store): Promise<void> {
+ await fs.mkdir(path.dirname(STORE_PATH), { recursive: true, mode: 0o700 });
+ const tmp = `${STORE_PATH}.tmp`;
+ await fs.writeFile(tmp, JSON.stringify(store, null, 2), { encoding: "utf8", mode: 0o600 });
+ await fs.rename(tmp, STORE_PATH);
+}
+
+/** Drop expired codes on every write path — they are single-use and short-lived,
+ * so without this the file grows one dead row per abandoned consent, forever. */
+function sweep(store: Store): Store {
+ const now = Date.now();
+ for (const [k, v] of Object.entries(store.codes)) if (v.expiresAt < now) delete store.codes[k];
+ return store;
+}
+
+export async function registerClient(name: string, redirectUris: string[]): Promise<string> {
+ const store = sweep(await read());
+ // Re-registering the same redirect set returns the existing id instead of
+ // minting a new one — mcp-remote and Cursor re-register on every launch.
+ const key = [...redirectUris].sort().join(" ");
+ for (const [id, c] of Object.entries(store.clients)) {
+ if ([...c.redirectUris].sort().join(" ") === key) return id;
+ }
+ const ids = Object.keys(store.clients);
+ if (ids.length >= MAX_CLIENTS) {
+ ids.sort((a, b) => store.clients[a].createdAt - store.clients[b].createdAt)
+ .slice(0, ids.length - MAX_CLIENTS + 1)
+ .forEach((id) => delete store.clients[id]);
+ }
+ const clientId = "mcpc_" + sha256hex(key + Date.now()).slice(0, 24);
+ store.clients[clientId] = { name: name.slice(0, 80) || "MCP Client", redirectUris, createdAt: Date.now() };
+ await write(store);
+ return clientId;
+}
+
+export async function getClient(clientId: string): Promise<McpClient | null> {
+ return (await read()).clients[clientId] ?? null;
+}
+
+export async function storeCode(code: string, rec: McpCode): Promise<void> {
+ const store = sweep(await read());
+ store.codes[sha256hex(code)] = rec;
+ await write(store);
+}
+
+/**
+ * Single-use exchange. The row is DELETED before the caller mints anything, so a
+ * replayed code finds nothing and gets `invalid_grant` — and the table does not
+ * grow a dead "consumed" row per successful login.
+ */
+export async function consumeCode(code: string): Promise<McpCode | null> {
+ const store = sweep(await read());
+ const hash = sha256hex(code);
+ const rec = store.codes[hash];
+ if (!rec || rec.expiresAt < Date.now()) return null;
+ delete store.codes[hash];
+ await write(store);
+ return rec;
+}
+
+export async function storeToken(token: string, rec: Omit<McpToken, "createdAt" | "expiresAt">): Promise<void> {
+ const store = sweep(await read());
+ const now = Date.now();
+ store.tokens[sha256hex(token)] = { ...rec, createdAt: now, expiresAt: now + TOKEN_TTL_MS };
+ await write(store);
+}
+
+/** Returns the live token record, or null for unknown / revoked / expired. Both
+ * revocation and expiry are re-checked on EVERY call — that is what makes the
+ * Revoke button in Settings kill an in-flight connector immediately. */
+export async function validateToken(token: string): Promise<(McpToken & { hash: string }) | null> {
+ if (!token) return null;
+ const hash = sha256hex(token);
+ const rec = (await read()).tokens[hash];
+ if (!rec || rec.revokedAt) return null;
+ if (rec.expiresAt < Date.now()) return null;
+ return { ...rec, hash };
+}
+
+export async function touchToken(hash: string): Promise<void> {
+ const store = await read();
+ const rec = store.tokens[hash];
+ if (!rec) return;
+ rec.lastUsedAt = Date.now();
+ await write(store);
+}
+
+export interface TokenView extends McpToken {
+ id: string;
+ /** Resolved HERE, not in the browser: the server owns the clock, and computing
+ * it during render is an impure read the React compiler rejects anyway. */
+ status: "active" | "revoked" | "expired";
+}
+
+/** For the Settings table. There is no raw token to withhold — only the sha256
+ * was ever written — so the id here is a short prefix of the hash. */
+export async function listTokens(): Promise<TokenView[]> {
+ const store = await read();
+ const now = Date.now();
+ return Object.entries(store.tokens)
+ .map(([hash, t]) => ({
+ ...t,
+ id: hash.slice(0, 16),
+ status: t.revokedAt ? ("revoked" as const) : t.expiresAt < now ? ("expired" as const) : ("active" as const),
+ }))
+ .sort((a, b) => b.createdAt - a.createdAt);
+}
+
+export async function revokeToken(id: string): Promise<boolean> {
+ const store = await read();
+ const hit = Object.keys(store.tokens).find((h) => h.startsWith(id));
+ if (!hit || store.tokens[hit].revokedAt) return false;
+ store.tokens[hit].revokedAt = Date.now();
+ await write(store);
+ return true;
+}
+
+/** Panic button — kills every live bearer at once. */
+export async function revokeAllTokens(): Promise<number> {
+ const store = await read();
+ let n = 0;
+ for (const t of Object.values(store.tokens)) if (!t.revokedAt) { t.revokedAt = Date.now(); n++; }
+ if (n) await write(store);
+ return n;
+}
diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.ts
new file mode 100644
index 00000000..f6d2b63a
--- /dev/null
+++ b/lib/mcp/tools.ts
@@ -0,0 +1,203 @@
+import {
+ listDir, readFile, writeFile, makeDir, remove, move, copy, searchFs, usage,
+ runCommand, stats, processes,
+} from "@/lib/host";
+import { camoufoxStatus, setCamoufoxEnabled } from "@/lib/camoufox/service";
+import { listManagedApps } from "@/lib/managed-apps/manager";
+import type { Scope } from "./scope";
+
+// The MCP tool catalog. EVERY handler goes through lib/host — never node fs or
+// child_process directly — so all of it inherits the bounds that already guard
+// /api/v1: OS_FS_READ_ROOTS / OS_FS_WRITE_ROOTS, the credential denylist
+// (~/.ssh, ~/.mso itself, cloud + AI tokens), realpath escape checks, and the
+// 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 interface McpTool {
+ name: string;
+ description: string;
+ scope: Scope;
+ inputSchema: { type: "object"; properties: Record<string, unknown>; required?: string[] };
+ annotations?: Record<string, boolean>;
+ run: (a: Record<string, unknown>) => Promise<unknown>;
+}
+
+const str = (a: Record<string, unknown>, k: string): string => {
+ const v = a[k];
+ if (typeof v !== "string" || !v) throw new Error(`${k} must be a non-empty string`);
+ return v;
+};
+const opt = (a: Record<string, unknown>, k: string): string | undefined =>
+ typeof a[k] === "string" && a[k] ? (a[k] as string) : undefined;
+
+const S = (properties: Record<string, unknown>, required?: string[]) =>
+ ({ type: "object" as const, properties, ...(required ? { required } : {}) });
+
+const PATH_P = { path: { type: "string", description: "Absolute path on the VPS, or ~/… for the owner's home." } };
+const READ_ONLY = { readOnlyHint: true, idempotentHint: true };
+
+export const TOOLS: McpTool[] = [
+ {
+ name: "fs_list",
+ description:
+ "List a directory on the VPS. Returns entries with name, type, size and mtime. " +
+ "USE THIS FIRST to discover paths before reading or writing — guessing a path wastes a call. " +
+ "Reads are bounded to OS_FS_READ_ROOTS and credential paths (~/.ssh, ~/.mso, cloud tokens) are refused.",
+ scope: "read",
+ annotations: READ_ONLY,
+ inputSchema: S({ ...PATH_P, includeHidden: { type: "boolean", description: "Include dotfiles. Default true." } }, ["path"]),
+ run: (a) => listDir(str(a, "path"), a.includeHidden !== false),
+ },
+ {
+ name: "fs_read",
+ description:
+ "Read a text file on the VPS and return its contents. For binary files this will be garbage — " +
+ "check the extension from fs_list first. NOT for finding a file: use fs_search.",
+ scope: "read",
+ annotations: READ_ONLY,
+ inputSchema: S(PATH_P, ["path"]),
+ run: async (a) => ({ path: a.path, content: await readFile(str(a, "path")) }),
+ },
+ {
+ name: "fs_search",
+ description:
+ "Find DIRECTORIES whose name contains a fragment, recursively, under a root. Use it to locate a " +
+ "project folder before fs_list — it is bounded and needs no shell scope, unlike exec_run with find. " +
+ "It does NOT match file names or file contents; fs_list the directory it returns.",
+ scope: "read",
+ annotations: READ_ONLY,
+ inputSchema: S({
+ query: { type: "string", description: "Substring matched against directory names." },
+ root: { type: "string", description: "Where to search from. Defaults to ~/projects." },
+ }, ["query"]),
+ run: (a) => searchFs(str(a, "query"), { root: opt(a, "root") }),
+ },
+ {
+ name: "fs_usage",
+ description: "Disk usage for a path: total, used and free bytes. Use for 'is the VPS full?'.",
+ scope: "read",
+ annotations: READ_ONLY,
+ inputSchema: S(PATH_P, ["path"]),
+ run: (a) => usage(str(a, "path")),
+ },
+ {
+ name: "sys_stats",
+ description:
+ "Live VPS health: CPU load, memory, disk, uptime. USE THIS for 'how is the server doing' — " +
+ "it is one cheap call and needs no shell scope.",
+ scope: "read",
+ annotations: READ_ONLY,
+ inputSchema: S({}),
+ run: () => stats(),
+ },
+ {
+ name: "sys_processes",
+ description: "Top processes by CPU with pid, command, cpu% and memory%. Use to find what is eating the box.",
+ scope: "read",
+ annotations: READ_ONLY,
+ inputSchema: S({}),
+ run: () => processes(),
+ },
+ {
+ name: "apps_list",
+ description:
+ "List the managed applications mso can install and control on this VPS, with install and running state. " +
+ "This is NOT the mso app list (Files, Terminal, …) — those are UI surfaces with no server state.",
+ scope: "read",
+ annotations: READ_ONLY,
+ inputSchema: S({}),
+ run: () => listManagedApps(),
+ },
+ {
+ name: "browser_status",
+ description:
+ "State of the Camoufox anti-fingerprinting browser (a real Firefox on a headless display). " +
+ "Returns installed/running/autostart only. The viewer URL and its one-time VNC password are DELIBERATELY not " +
+ "returned here — that session holds live Google and LinkedIn logins, so its credentials never leave " +
+ "the box through a tool result. Open Settings in mso to get them.",
+ scope: "read",
+ annotations: READ_ONLY,
+ inputSchema: S({}),
+ run: async () => {
+ const s = await camoufoxStatus();
+ return { installed: s.installed, running: s.running, autostart: s.enabled };
+ },
+ },
+
+ {
+ name: "fs_write",
+ 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).",
+ scope: "write",
+ annotations: { idempotentHint: true },
+ inputSchema: S({ ...PATH_P, content: { type: "string" } }, ["path", "content"]),
+ run: async (a) => {
+ await writeFile(str(a, "path"), typeof a.content === "string" ? a.content : "");
+ return { ok: true, path: a.path };
+ },
+ },
+ {
+ name: "fs_mkdir",
+ description: "Create a directory (and any missing parents) on the VPS.",
+ scope: "write",
+ annotations: { idempotentHint: true },
+ inputSchema: S(PATH_P, ["path"]),
+ run: async (a) => { await makeDir(str(a, "path")); return { ok: true, path: a.path }; },
+ },
+ {
+ name: "fs_move",
+ 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"]),
+ run: async (a) => { await move(str(a, "from"), str(a, "to")); return { ok: true }; },
+ },
+ {
+ name: "fs_copy",
+ 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"]),
+ run: async (a) => { await copy(str(a, "from"), str(a, "to")); return { ok: true }; },
+ },
+ {
+ name: "fs_delete",
+ 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.",
+ scope: "write",
+ annotations: { destructiveHint: true },
+ inputSchema: S(PATH_P, ["path"]),
+ run: async (a) => { await remove(str(a, "path")); return { ok: true, path: a.path }; },
+ },
+
+ {
+ name: "exec_run",
+ 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 " +
+ "this is not. Catastrophic patterns (rm -rf /, fork bombs, disk wipes) are refused by the server. " +
+ "Long-running or interactive commands will time out: this is not a terminal session.",
+ scope: "exec",
+ annotations: { destructiveHint: true, openWorldHint: true },
+ inputSchema: S({
+ command: { type: "string", description: "The shell command line to run." },
+ cwd: { type: "string", description: "Working directory. Defaults to the owner's home." },
+ }, ["command"]),
+ run: (a) => runCommand(str(a, "command"), opt(a, "cwd")),
+ },
+ {
+ name: "browser_power",
+ 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.",
+ scope: "exec",
+ annotations: { destructiveHint: true },
+ inputSchema: S({ on: { type: "boolean", description: "true = start, false = stop." } }, ["on"]),
+ run: async (a) => {
+ const s = await setCamoufoxEnabled(a.on === true);
+ return { installed: s.installed, running: s.running, autostart: s.enabled };
+ },
+ },
+];
+
+export const TOOLS_BY_NAME = new Map(TOOLS.map((t) => [t.name, t]));
diff --git a/proxy.ts b/proxy.ts
index 5f64ac02..dd4c3693 100644
--- a/proxy.ts
+++ b/proxy.ts
@@ -217,7 +217,20 @@ export async function proxy(request: NextRequest) {
if (MATCHER_EXCLUDED.test(pathname)) return NextResponse.next();
- const isApi = pathname.startsWith("/api/");
+ // The MCP endpoint and its OAuth discovery documents are JSON, not HTML, and are
+ // reached CROSS-ORIGIN by design (ChatGPT, Claude.ai, Cursor). They live outside
+ // /api deliberately: the depth-2 CSRF gate below would block every one of them,
+ // and it is the wrong control here — their credential is a bearer token, which a
+ // browser never attaches on its own, so there is no cross-site request to forge.
+ // Treated like /api for header purposes: no nonce, no document CSP.
+ // NOTE /oauth/authorize is NOT here on purpose — it is a real HTML consent page
+ // and must keep the nonce + document CSP. Only the JSON endpoints are listed.
+ const isMcp =
+ pathname === "/mcp" ||
+ pathname.startsWith("/.well-known/oauth-") ||
+ pathname === "/oauth/token" ||
+ pathname === "/oauth/register";
+ const isApi = pathname.startsWith("/api/") || isMcp;
const isCamoufoxVnc = pathname.startsWith("/camoufox-vnc/");
// Camoufox's VNC bridge — noVNC + websockify in front of x11vnc, i.e. live
@@ -248,8 +261,10 @@ export async function proxy(request: NextRequest) {
: NextResponse.rewrite(target);
}
- // CSRF depth-2 for mutating /api (unchanged semantics).
- if (MUTATING.has(request.method) && isApi && crossOriginMutation(request)) return blocked();
+ // CSRF depth-2 for mutating /api (unchanged semantics). `isMcp` is excluded —
+ // see the note above: bearer-authenticated, so same-origin proof is meaningless
+ // and enforcing it would break every remote MCP client.
+ if (MUTATING.has(request.method) && isApi && !isMcp && crossOriginMutation(request)) return blocked();
// /api owns its own response headers (fs/raw sets `content-security-policy:
// sandbox`, Cache-Control no-store) and serves no inline scripts — never stamp