Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
feat(mcp): add guided client setup
Rahman95e15f1f446e
diff --git a/README.md b/README.mdindex a2a8e61e..ff6043dd 100644--- a/README.md+++ b/README.md@@ -72,7 +72,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, global project/skill discovery, ChatGPT file import and, at `exec`, a shell. The read/write/exec ladder is the server-side permission boundary. See the [ChatGPT custom MCP app guide](./docs/CHATGPT-PLUGIN.md) for setup/diagrams and [MCP reference](./docs/MCP.md) for internals.+- **Drive the box from ChatGPT, Codex, Claude Code, Cursor, Gemini CLI or VS Code** — Settings → MCP now provides client-specific numbered setup, copy-ready remote configs, live MCP/OAuth discovery checks, tunnel/domain guidance, and the same OAuth 2.1 + PKCE `read → write → exec` permission ladder enforced server-side. See the [ChatGPT Plugin / custom MCP app guide](./docs/CHATGPT-PLUGIN.md) and [MCP reference](./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.@@ -429,7 +429,7 @@ Not currently supported:| [docs/9ROUTER-INTEGRATION.md](./docs/9ROUTER-INTEGRATION.md) | 9Router immutable-image ownership, loopback default and explicit dashboard exposure || [docs/MODELS-INTEGRATION.md](./docs/MODELS-INTEGRATION.md) | Alfa BYOK/custom/Codex model credentials || [docs/MCP.md](./docs/MCP.md) | MCP/OAuth tools, discovery, workflow memory and security internals |-| [docs/CHATGPT-PLUGIN.md](./docs/CHATGPT-PLUGIN.md) | ChatGPT custom MCP app setup + architecture/OAuth/tool/file diagrams |+| [docs/CHATGPT-PLUGIN.md](./docs/CHATGPT-PLUGIN.md) | ChatGPT Plugin/custom MCP app setup + architecture/OAuth/tool/file diagrams || [docs/FAQ.md](./docs/FAQ.md) | Security, product and operator boundaries || [docs/TROUBLESHOOTING.md](./docs/TROUBLESHOOTING.md) | Current symptom → cause → supported recovery || [SECURITY.md](./SECURITY.md) | Security posture and vulnerability reporting |diff --git a/app/api/mcp/tokens/route.test.ts b/app/api/mcp/tokens/route.test.tsnew file mode 100644index 00000000..9b1efc58--- /dev/null+++ b/app/api/mcp/tokens/route.test.ts@@ -0,0 +1,34 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ verifyAuth: vi.fn(async () => true),+ listTokens: vi.fn(async () => []),+ publicOrigin: vi.fn(() => "https://mso.example.test"),+}));++vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));+vi.mock("@/lib/mcp/store", () => ({ listTokens: mocks.listTokens, revokeToken: vi.fn(), revokeAllTokens: vi.fn() }));+vi.mock("@/lib/mcp/scope", () => ({ mcpEnabled: () => true, maxScope: () => "write" }));+vi.mock("@/lib/mcp/tools", () => ({ TOOLS: [] }));+vi.mock("@/lib/mcp/toolset", () => ({ toolsetInfo: () => ({ serverVersion: "1", version: "v", hash: "h", changedAt: "2026-08-31", toolCount: 0, byScope: { read: 0, write: 0, exec: 0 } }) }));+vi.mock("@/lib/mcp/origin", () => ({ publicOrigin: mocks.publicOrigin }));++beforeEach(() => vi.clearAllMocks());++describe("Settings MCP state", () => {+ it("returns the deployment-owned public origin instead of forcing the browser origin", async () => {+ const { GET } = await import("./route");+ const request = new Request("http://127.0.0.1:4005/api/mcp/tokens");+ const response = await GET(request);+ expect(response.status).toBe(200);+ await expect(response.json()).resolves.toMatchObject({ enabled: true, maxScope: "write", origin: "https://mso.example.test" });+ expect(mocks.publicOrigin).toHaveBeenCalledWith(request);+ });++ it("does not reveal connection metadata without owner auth", async () => {+ mocks.verifyAuth.mockResolvedValueOnce(false);+ const { GET } = await import("./route");+ const response = await GET(new Request("https://mso.example.test/api/mcp/tokens"));+ expect(response.status).toBe(401);+ });+});diff --git a/app/api/mcp/tokens/route.ts b/app/api/mcp/tokens/route.tsindex a063be34..f732dda4 100644--- a/app/api/mcp/tokens/route.ts+++ b/app/api/mcp/tokens/route.ts@@ -4,6 +4,7 @@ import { listTokens, revokeToken, revokeAllTokens } from "@/lib/mcp/store";import { mcpEnabled, maxScope } from "@/lib/mcp/scope";import { TOOLS } from "@/lib/mcp/tools";import { toolsetInfo } from "@/lib/mcp/toolset";+import { publicOrigin } from "@/lib/mcp/origin";// 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@@ -14,7 +15,7 @@ export const dynamic = "force-dynamic";export async function GET(req: Request) {if (!(await verifyAuth(req, "owner"))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });- return NextResponse.json({ enabled: mcpEnabled(), maxScope: maxScope(), toolset: toolsetInfo(TOOLS), tokens: await listTokens() });+ return NextResponse.json({ enabled: mcpEnabled(), maxScope: maxScope(), origin: publicOrigin(req), toolset: toolsetInfo(TOOLS), tokens: await listTokens() });}export async function DELETE(req: Request) {diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex b1caf53c..4b4e2d3c 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -6,12 +6,22 @@ this is the *what*, and it is what Settings → About shows as “What's new”.## 2026-08-31+**Added**++- `mcp` add guided client setup+**Fixed**- `settings` hide premature update warning- `update` enforce main and raise MCP daily limit- `mcp` raise daily token call limit+**Chores**++- `deps` bump aquasecurity/trivy-action (#32)+- `deps` bump actions/checkout from 6.1.0 to 7.0.1 (#31)+- `deps-dev` bump @types/react-dom (#29)+## 2026-08-30**Added**diff --git a/docs/CHATGPT-PLUGIN.md b/docs/CHATGPT-PLUGIN.mdindex 07863500..99de7db1 100644--- a/docs/CHATGPT-PLUGIN.md+++ b/docs/CHATGPT-PLUGIN.md@@ -1,14 +1,16 @@# ChatGPT plugin / custom MCP app for MSO-> **Current reference.** In this project, people often say "the ChatGPT plugin". The-> current ChatGPT product calls this a **custom MCP app/connector** in Developer Mode. It-> is not a legacy ChatGPT Plugin manifest, browser extension, or a plugin installed inside-> Hermes/OpenClaw.+> **Current reference.** OpenAI moved its app directory to the **Plugin directory** on+> 2026-07-09; plugins are now the discovery surface across ChatGPT/Codex, while the underlying+> MSO connection remains a custom MCP app created in Developer Mode. Depending on workspace+> controls, the UI can say **Plugins → New Plugin** or **Apps → Create**. This is not a legacy+> ChatGPT Plugin manifest, browser extension, or a plugin installed inside Hermes/OpenClaw.>-> ChatGPT's Developer Mode UI and plan availability are controlled by OpenAI and may change-> while full MCP is in beta. The stable contract on the MSO side is the remote MCP endpoint-> plus OAuth metadata documented here. OpenAI's current overview is:+> ChatGPT's Developer Mode UI and permissions are controlled by OpenAI and can change during+> the MCP beta. Settings → MCP in MSO therefore shows the live endpoint, OAuth metadata and a+> guided setup instead of freezing one menu layout. Current OpenAI references:> <https://help.openai.com/en/articles/12584461-developer-mode-and-mcp-apps-in-chatgpt-beta>+> and <https://help.openai.com/en/articles/20001256-plugins-in-chatgpt-and-codex>.<!-- mcp-toolset: server=1.6.0 version=2026.08.28.1 tools=31 read=16 write=10 exec=5 -->@@ -51,22 +53,20 @@ You need:5. a ChatGPT plan/workspace that currently permits the MCP capability you need.ChatGPT connects to a **remote** MCP server. A private-only MSO endpoint therefore needs a-supported remote path rather than an unreachable `localhost` URL. OpenAI's current docs-name **Secure MCP Tunnel** as the supported option for private/on-prem/developer-machine-servers; use the current OpenAI instructions rather than exposing the MSO shell port merely-to satisfy discovery.+reachable HTTPS path rather than an unreachable `localhost` URL. MSO's supported laptop path+is `mso gateway start` (temporary preview URL) or a named/custom-domain tunnel; the Next app+itself remains loopback-only instead of publishing port 4005 directly.After changing MSO environment configuration, use the normal MSO update/rebuild path; donot treat a Git push as deployment.-### Current ChatGPT availability (external, as of 2026-08-24)+### Current ChatGPT availability (external, checked 2026-08-31)-OpenAI's current Developer Mode documentation says custom MCP apps are a **web** capability-in beta. Full MCP including write/modify actions is available to Business, Enterprise and-Edu workspaces under their workspace controls; Pro can connect custom MCP servers for-read/fetch access. Workspace admins can further restrict or disable the capability. This-availability is an OpenAI product decision and can change independently of MSO—check the-current OpenAI article before treating the table as entitlement:+OpenAI's current Developer Mode documentation says full MCP, including write/modify actions,+is rolling out in beta for Business, Enterprise and Edu workspaces and remains subject to+workspace/admin controls. The Plugin/App UI and entitlements are OpenAI product decisions and+can change independently of MSO, so Settings → MCP intentionally does not hard-code a plan+matrix. Check the current OpenAI article before treating any plan as entitled:<https://help.openai.com/en/articles/12584461-developer-mode-and-mcp-apps-in-chatgpt-beta>.MSO itself does not special-case ChatGPT plans. It publishes the same scoped MCP server; the@@ -89,10 +89,21 @@ MSO supports public OAuth clients with PKCE S256 and token-endpoint authenticati`none`. ChatGPT can use the predefined public client id `chatgpt-mso`; a client secret isnot required. Other MCP clients can use Dynamic Client Registration where supported.-The exact ChatGPT form labels can change during the beta. In Developer Mode, create a-custom MCP app, provide the remote MCP endpoint, select OAuth, then let ChatGPT scan tools.-When the authorization browser opens, sign into MSO on an approved device, review the-requested scope, and Allow only the tier you intend.+The exact ChatGPT form labels can change during the beta. The current MSO Settings → MCP+guide mirrors the common flow shown by OpenAI's Plugin/App UI:++1. enable Developer Mode for the account/workspace if required;+2. open Plugins or Apps and choose **New Plugin / Create**;+3. choose **Server URL** and paste the live MCP Server URL shown by MSO;+4. choose **OAuth**. MSO publishes the two `.well-known` documents automatically, uses PKCE+ S256, requires no client secret, and advertises token endpoint authentication `none`;+5. complete authorization in the browser, choose the lowest useful MSO scope, then return to+ ChatGPT and **Scan Tools / Create**;+6. enable the resulting MSO app/plugin from the tools or `+` menu in the chat before using it.++If ChatGPT shows the custom-server risk acknowledgement, review it rather than treating it as+an error. When the authorization browser opens, sign into MSO on an approved device and Allow+only the tier you intend.## 4. OAuth lifecycle@@ -129,7 +140,7 @@ A token sees a scope prefix; there is no per-project or per-agent hidden tool fi`tools/list` filters the catalog and `tools/call` independently re-checks the requiredscope.-### `read` — 15 tools+### `read` — 16 tools- `fs_list`- `fs_read`@@ -146,6 +157,7 @@ scope.- `skills_read`- `skills_search`- `screen_capture`+- `exec_job_status`### `write` — read + 10 tools@@ -160,9 +172,11 @@ scope.- `workflow_cancel`- `workflow_finish`-### `exec` — write + 3 tools+### `exec` — write + 5 tools- `exec_run`+- `exec_job_start`+- `exec_job_cancel`- `browser_power`- `project_function_call`@@ -181,9 +195,9 @@ Settings → MCP:```textserver: 1.6.0-toolset: 2026.08.21.1-hash: 8c3c9092013069de-count: 28+toolset: 2026.08.28.1+hash: <live schema hash>+count: 31```Use this sequence after an MSO MCP change:diff --git a/docs/MCP.md b/docs/MCP.mdindex b3b3e5da..dd38e543 100644--- a/docs/MCP.md+++ b/docs/MCP.md@@ -50,11 +50,12 @@ signed-in MSO page: an approved human browser session converts into a scoped MCPconsent page is not a second login mechanism. Expired/revoked bearers therefore require anew authorization flow.-For ChatGPT, the current product surface is a **custom MCP app/connector in Developer-Mode**. Its UI and plan availability are owned by OpenAI and can change during the beta, so-this deep reference does not freeze ChatGPT menu labels. Use-[`CHATGPT-PLUGIN.md`](./CHATGPT-PLUGIN.md) for the current field mapping, OAuth sequence,-tool-snapshot refresh and troubleshooting.+For ChatGPT, the connection is a **custom MCP app** created in Developer Mode and surfaced+through OpenAI's current Plugin/App experience. OpenAI moved the directory to Plugins in July+2026, while some workspace configuration pages still say Apps → Create; MSO therefore does not+freeze one menu label. Settings → MCP renders the live server URL, probes MCP/OAuth discovery,+and provides client-specific numbered steps. Use [`CHATGPT-PLUGIN.md`](./CHATGPT-PLUGIN.md) for+the current field mapping, OAuth sequence, tool-snapshot refresh and troubleshooting.Clients that support RFC 7591 Dynamic Client Registration can register through`/oauth/register`. ChatGPT can also use the predefined public `chatgpt-mso` client without adiff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex c648352e..d3392558 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -2,6 +2,26 @@Running log of what shipped each phase. Newest at top.+## 2026-08-31 — Guided multi-client MCP setup in Settings (IN REVIEW)++Settings → MCP now treats connection as an onboarding workflow instead of a developer-only list of+OAuth endpoints. The authenticated Settings API returns MSO's deployment-owned public origin, so a+loopback browser no longer teaches ChatGPT a `localhost` URL when `OS_PUBLIC_ORIGIN` is configured.+The connection card probes `GET /mcp`, the Bearer OAuth challenge, protected-resource metadata and+authorization-server metadata and reports readiness only when all four agree on the same deployment.++The UI now mirrors modern MCP client setup flows: choose ChatGPT, Codex, Claude Code, Cursor, Gemini+CLI, VS Code, or a generic Streamable HTTP client; follow numbered steps; copy the exact server URL,+CLI/config snippet, and only expand advanced OAuth fields when a client asks for them. ChatGPT gets+copy-ready Name/Description/Connection/Authentication values matching the New Plugin form. Local-only+origins are called out before users paste them into a cloud client, with MSO Gateway and stable+custom-domain/reverse-proxy instructions that keep the raw Next listener loopback-only. Scope guidance+starts at `read` and explicitly describes `write` and `exec` blast radius.++The existing token revocation, audit trail and toolset-signature cards remain the operational truth+after connection. Current MCP/ChatGPT docs were refreshed at the same time, including the live+31-tool split (16 read / 10 write / 5 exec) and current Plugin/App terminology.+## 2026-08-31 — 10× MCP daily allowance + truthful Settings updater preflight (SHIPPED)The authenticated MCP endpoint now permits 50,000 calls per token per fixed 24-hour process-local@@ -408,8 +428,9 @@ MCP/ChatGPT documentation is now split by responsibility. `docs/MCP.md` remainsprotocol/security/discovery/workflow reference, and new `docs/CHATGPT-PLUGIN.md` is theoperator-facing custom MCP app guide with architecture, OAuth sequence, scope/tool,tool-snapshot refresh, workflow-id, ChatGPT-file-upload and credential-boundary Mermaid-diagrams. It pins the live MSO MCP contract at server `1.6.0`, toolset `2026.08.21.1`, 28-tools (15 read / 10 write / 3 exec), documents the authorization-code-only PKCE flow and+diagrams. At that 2026-08-24 snapshot it recorded server `1.6.0`, toolset `2026.08.21.1`,+28 tools (15 read / 10 write / 3 exec); those counts are historical, while Settings → MCP and+`GET /mcp` are the current authority. The guide also documents the authorization-code-only PKCE flow and90-day bearer reauthorization boundary, and clearly separates MSO MCP OAuth from Alfa'sOpenAI Codex/ChatGPT-subscription OAuth. Current OpenAI Developer Mode availability andfrozen-action behaviour are labeled as an external dated dependency rather than an MSOdiff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.mdindex 145b58a7..77bbbac1 100644--- a/docs/TROUBLESHOOTING.md+++ b/docs/TROUBLESHOOTING.md@@ -312,6 +312,28 @@ See `docs/MODELS-INTEGRATION.md` and `docs/CHATGPT-PLUGIN.md`.## MCP / ChatGPT custom app+### Where do I start?++Use **Settings → MCP → Connect an AI client**. It now derives the MCP URL from MSO's+deployment-owned public origin, probes the MCP endpoint plus OAuth challenge/resource/server+metadata, and shows numbered setup steps for ChatGPT, Codex, Claude Code, Cursor, Gemini CLI,+VS Code, and a generic Streamable HTTP client. Advanced OAuth fields stay collapsed unless a+client actually asks for them.++If Settings says the origin is local-only (`127.0.0.1`, `localhost`, or `::1`), do not paste+that URL into a cloud client. Keep MSO loopback-only and use `mso gateway start` for a temporary+HTTPS endpoint, or configure a stable HTTPS tunnel/reverse proxy and set the same origin with+`mso gateway domain set https://…`. Reopen Settings through that public origin before copying+the client URL.++### Settings → MCP Test connection is red++The test is not a generic ping. All four public contracts must agree on the same deployment:+`GET /mcp`, the unauthenticated Bearer/OAuth challenge from `POST /mcp`, RFC 9728 protected+resource metadata, and RFC 8414 authorization-server metadata. Expand **Advanced OAuth settings**+and compare the URLs if one badge is red. A proxy/domain mismatch is more likely than a token+problem because this probe intentionally runs before OAuth authorization.+### `/mcp` or OAuth discovery returns 404`OS_MCP_ENABLED=1` is not active in the running service (or demo mode forced MCP off).diff --git a/frontend/slices/os-settings/components/mcp-client-core.ts b/frontend/slices/os-settings/components/mcp-client-core.tsnew file mode 100644index 00000000..5c91bb6f--- /dev/null+++ b/frontend/slices/os-settings/components/mcp-client-core.ts@@ -0,0 +1,91 @@+export type McpClientId =+ | "chatgpt"+ | "codex"+ | "claude-code"+ | "cursor"+ | "gemini"+ | "vscode"+ | "other";++export type McpEndpointSet = {+ origin: string;+ mcp: string;+ authorize: string;+ token: string;+ register: string;+ protectedResource: string;+ authorizationServer: string;+};++export type McpGuideStep = {+ title: string;+ body: string;+ copy?: { label: string; value: string; multiline?: boolean };+};++export type McpProbeCheckId = "mcp" | "challenge" | "resource" | "oauth";++export type McpProbeResult = {+ ready: boolean;+ checks: Array<{ id: McpProbeCheckId; ok: boolean }>;+};++export const MCP_CLIENTS: Array<{+ id: McpClientId;+ label: string;+ description: string;+ kind: "hosted" | "desktop" | "cli" | "editor" | "generic";+}> = [+ { id: "chatgpt", label: "ChatGPT", description: "Apps / Plugins with OAuth", kind: "hosted" },+ { id: "codex", label: "Codex", description: "CLI, desktop, and IDE", kind: "cli" },+ { id: "claude-code", label: "Claude Code", description: "Remote HTTP + browser OAuth", kind: "cli" },+ { id: "cursor", label: "Cursor", description: "Remote MCP in mcp.json", kind: "editor" },+ { id: "gemini", label: "Gemini CLI", description: "Remote HTTP server", kind: "cli" },+ { id: "vscode", label: "VS Code", description: "MCP: Add Server / mcp.json", kind: "editor" },+ { id: "other", label: "Other MCP", description: "Any Streamable HTTP client", kind: "generic" },+];++export const MCP_PROBE_LABELS: Record<McpProbeCheckId, string> = {+ mcp: "MCP endpoint",+ challenge: "OAuth challenge",+ resource: "Protected resource",+ oauth: "OAuth metadata",+};++export function mcpEndpoints(rawOrigin: string): McpEndpointSet {+ const origin = new URL(rawOrigin).origin;+ return {+ origin,+ mcp: `${origin}/mcp`,+ authorize: `${origin}/oauth/authorize`,+ token: `${origin}/oauth/token`,+ register: `${origin}/oauth/register`,+ protectedResource: `${origin}/.well-known/oauth-protected-resource`,+ authorizationServer: `${origin}/.well-known/oauth-authorization-server`,+ };+}++export function isRemoteMcpOrigin(rawOrigin: string): boolean {+ try {+ const url = new URL(rawOrigin);+ const host = url.hostname.toLowerCase();+ return url.protocol === "https:" && host !== "localhost" && host !== "::1" && host !== "[::1]" && !host.startsWith("127.");+ } catch {+ return false;+ }+}++export function cursorMcpConfig(rawOrigin: string): string {+ const { mcp } = mcpEndpoints(rawOrigin);+ return JSON.stringify({ mcpServers: { mso: { url: mcp } } }, null, 2);+}++export function vscodeMcpConfig(rawOrigin: string): string {+ const { mcp } = mcpEndpoints(rawOrigin);+ return JSON.stringify({ servers: { mso: { type: "http", url: mcp } } }, null, 2);+}++export function codexMcpConfig(rawOrigin: string): string {+ const { mcp } = mcpEndpoints(rawOrigin);+ return `[mcp_servers.mso]\nurl = "${mcp}"`;+}diff --git a/frontend/slices/os-settings/components/mcp-client-guides.test.ts b/frontend/slices/os-settings/components/mcp-client-guides.test.tsnew file mode 100644index 00000000..cf7933cb--- /dev/null+++ b/frontend/slices/os-settings/components/mcp-client-guides.test.ts@@ -0,0 +1,85 @@+import { describe, expect, it, vi } from "vitest";+import {+ codexMcpConfig,+ cursorMcpConfig,+ isRemoteMcpOrigin,+ mcpEndpoints,+ vscodeMcpConfig,+} from "./mcp-client-core";+import { probeMcpConnection } from "./mcp-probe";+import { mcpClientSteps } from "./mcp-client-steps";++describe("MCP client setup guides", () => {+ it("derives every endpoint from one normalized origin", () => {+ const endpoints = mcpEndpoints("https://mso.example.test/path");+ expect(endpoints.origin).toBe("https://mso.example.test");+ expect(endpoints.mcp).toBe("https://mso.example.test/mcp");+ expect(endpoints.protectedResource).toContain("/.well-known/oauth-protected-resource");+ });++ it("distinguishes a remotely reachable HTTPS origin from local loopback", () => {+ expect(isRemoteMcpOrigin("https://mso.example.test")).toBe(true);+ expect(isRemoteMcpOrigin("https://localhost:4005")).toBe(false);+ expect(isRemoteMcpOrigin("http://127.0.0.1:4005")).toBe(false);+ });++ it("builds client configs with no credential material", () => {+ const cursor = JSON.parse(cursorMcpConfig("https://mso.example.test"));+ const vscode = JSON.parse(vscodeMcpConfig("https://mso.example.test"));+ const codex = codexMcpConfig("https://mso.example.test");+ expect(cursor).toEqual({ mcpServers: { mso: { url: "https://mso.example.test/mcp" } } });+ expect(vscode).toEqual({ servers: { mso: { type: "http", url: "https://mso.example.test/mcp" } } });+ expect(codex).toContain('url = "https://mso.example.test/mcp"');+ expect(JSON.stringify({ cursor, vscode, codex })).not.toMatch(/password|client_secret|bearer\s+[a-z0-9]/i);+ });++ it("keeps ChatGPT setup explicit about Developer Mode, OAuth and tool scanning", () => {+ const text = mcpClientSteps("chatgpt", "https://mso.example.test").map((step) => `${step.title} ${step.body}`).join(" ");+ expect(text).toMatch(/Developer Mode/);+ expect(text).toMatch(/OAuth/);+ expect(text).toMatch(/Scan Tools/);+ expect(text).toMatch(/lowest scope/);+ });++ it("provides direct remote HTTP commands for major CLI clients", () => {+ const codex = mcpClientSteps("codex", "https://mso.example.test").flatMap((step) => step.copy?.value ?? []).join(" ");+ const claude = mcpClientSteps("claude-code", "https://mso.example.test").flatMap((step) => step.copy?.value ?? []).join(" ");+ const gemini = mcpClientSteps("gemini", "https://mso.example.test").flatMap((step) => step.copy?.value ?? []).join(" ");+ expect(codex).toContain("codex mcp add mso --url https://mso.example.test/mcp");+ expect(codex).toContain("codex mcp login mso");+ expect(claude).toContain("claude mcp add --transport http mso https://mso.example.test/mcp");+ expect(gemini).toContain("gemini mcp add --transport http mso https://mso.example.test/mcp");+ });++ it("accepts only matching endpoint, challenge and OAuth discovery metadata", async () => {+ const fetcher = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ if (url.endsWith("/mcp") && init?.method === "POST") {+ return new Response(JSON.stringify({ error: "unauthorized" }), {+ status: 401,+ headers: { "www-authenticate": 'Bearer realm="mso", resource_metadata="https://mso.example.test/.well-known/oauth-protected-resource"' },+ });+ }+ if (url.endsWith("/mcp")) return Response.json({ name: "mso MCP", authorization_servers: ["https://mso.example.test"] });+ if (url.endsWith("oauth-protected-resource")) return Response.json({ resource: "https://mso.example.test/mcp", authorization_servers: ["https://mso.example.test"] });+ return Response.json({+ issuer: "https://mso.example.test",+ authorization_endpoint: "https://mso.example.test/oauth/authorize",+ token_endpoint: "https://mso.example.test/oauth/token",+ registration_endpoint: "https://mso.example.test/oauth/register",+ code_challenge_methods_supported: ["S256"],+ token_endpoint_auth_methods_supported: ["none"],+ });+ });+ await expect(probeMcpConnection("https://mso.example.test", fetcher)).resolves.toMatchObject({ ready: true });+ });++ it("fails the probe when discovery points at another deployment", async () => {+ const fetcher = vi.fn(async (input: RequestInfo | URL) => {+ const url = String(input);+ if (url.endsWith("/mcp")) return Response.json({ name: "mso MCP", authorization_servers: ["https://other.test"] });+ return Response.json({});+ });+ await expect(probeMcpConnection("https://mso.example.test", fetcher)).resolves.toMatchObject({ ready: false });+ });+});diff --git a/frontend/slices/os-settings/components/mcp-client-setup.tsx b/frontend/slices/os-settings/components/mcp-client-setup.tsxnew file mode 100644index 00000000..49ffe4cb--- /dev/null+++ b/frontend/slices/os-settings/components/mcp-client-setup.tsx@@ -0,0 +1,65 @@+"use client";++import { Bot, TerminalSquare } from "lucide-react";+import { cn } from "@/lib/utils";+import { MCP_CLIENTS, type McpClientId, type McpGuideStep } from "./mcp-client-core";+import { McpCopyField } from "./mcp-copy-field";++type ClientRow = (typeof MCP_CLIENTS)[number];++function StepRow({ number, title, body, copy }: McpGuideStep & { number: number }) {+ return (+ <div className="flex gap-3">+ <div className="flex size-7 shrink-0 items-center justify-center rounded-full border bg-secondary text-[11px] font-semibold">{number}</div>+ <div className="min-w-0 flex-1 space-y-2">+ <div><p className="text-[13px] font-medium">{title}</p><p className="mt-0.5 text-xs leading-relaxed text-muted-foreground">{body}</p></div>+ {copy && <McpCopyField label={copy.label} value={copy.value} multiline={copy.multiline} />}+ </div>+ </div>+ );+}++export function McpClientSetup({+ client,+ onClientChange,+ selected,+ steps,+}: {+ client: McpClientId;+ onClientChange: (client: McpClientId) => void;+ selected: ClientRow;+ steps: McpGuideStep[];+}) {+ return (+ <>+ <div>+ <p className="text-[13px] font-medium">Client setup</p>+ <p className="mt-0.5 text-[11px] text-muted-foreground">Choose a client to get its remote-MCP shape. Use Other MCP only for clients that explicitly support a Streamable HTTP URL.</p>+ </div>+ <div className="grid grid-cols-2 gap-2 sm:grid-cols-3">+ {MCP_CLIENTS.map((item) => (+ <button key={item.id} type="button" aria-pressed={client === item.id} onClick={() => onClientChange(item.id)} className={cn(+ "min-h-16 rounded-lg border p-2.5 text-left transition-colors [@media(pointer:coarse)]:min-h-[72px]",+ client === item.id ? "border-primary/45 bg-primary/10" : "border-border/70 bg-secondary/25 hover:bg-secondary/50",+ )}>+ <span className="block text-xs font-medium">{item.label}</span>+ <span className="mt-0.5 block text-[10px] leading-snug text-muted-foreground">{item.description}</span>+ </button>+ ))}+ </div>+ <div className="flex items-center gap-2 rounded-lg bg-secondary/35 px-3 py-2">+ {selected.kind === "cli" ? <TerminalSquare className="size-3.5 shrink-0" /> : <Bot className="size-3.5 shrink-0" />}+ <p className="text-[11px] text-muted-foreground">{selected.label} · {selected.description}</p>+ </div>+ {client === "chatgpt" && (+ <div className="grid gap-3 rounded-lg border border-border/70 bg-secondary/20 p-3 sm:grid-cols-2">+ <McpCopyField label="Name" value="MSO" />+ <McpCopyField label="Description" value="Control this MSO host with scoped MCP tools" />+ <McpCopyField label="Connection" value="Server URL · Streamable HTTP" />+ <McpCopyField label="Authentication" value="OAuth" />+ </div>+ )}+ <div className="space-y-5">{steps.map((step, index) => <StepRow key={`${client}-${step.title}`} number={index + 1} {...step} />)}</div>+ </>+ );+}diff --git a/frontend/slices/os-settings/components/mcp-client-steps.ts b/frontend/slices/os-settings/components/mcp-client-steps.tsnew file mode 100644index 00000000..3540780e--- /dev/null+++ b/frontend/slices/os-settings/components/mcp-client-steps.ts@@ -0,0 +1,148 @@+import {+ codexMcpConfig,+ cursorMcpConfig,+ mcpEndpoints,+ vscodeMcpConfig,+ type McpClientId,+ type McpGuideStep,+} from "./mcp-client-core";++export function mcpClientSteps(client: McpClientId, rawOrigin: string): McpGuideStep[] {+ const endpoints = mcpEndpoints(rawOrigin);++ if (client === "chatgpt") {+ return [+ {+ title: "Enable Developer Mode when required",+ body: "On ChatGPT web, enable Developer Mode if your plan or workspace requires it. Workspace admins can restrict who may create custom MCP apps.",+ },+ {+ title: "Create the MSO app / MCP plugin",+ body: "Open ChatGPT Settings → Plugins → New Plugin. If your workspace still shows Apps → Create, use that equivalent flow. Choose Server URL / Streamable HTTP and paste this endpoint.",+ copy: { label: "Server URL", value: endpoints.mcp },+ },+ {+ title: "Choose OAuth",+ body: "Set Authentication to OAuth. MSO publishes protected-resource and authorization-server discovery, uses PKCE S256, and does not require a client secret.",+ },+ {+ title: "Authorize and scan tools",+ body: "Continue in the browser, sign in to MSO on an approved owner device, choose the lowest scope you need, then return to ChatGPT and run Scan Tools before creating the app.",+ },+ {+ title: "Enable MSO in the chat",+ body: "Enable the MSO app/plugin from ChatGPT's tools or + menu. Start with a read-only request before authorizing write or exec workflows.",+ },+ ];+ }++ if (client === "codex") {+ return [+ {+ title: "Add the remote server",+ body: "Codex CLI, desktop, and the IDE extension share MCP configuration. Add MSO as a Streamable HTTP server.",+ copy: { label: "Codex CLI", value: `codex mcp add mso --url ${endpoints.mcp}`, multiline: true },+ },+ {+ title: "Authenticate with OAuth",+ body: "Run the OAuth login after the URL is registered. Codex opens the browser flow and stores its client-side credential separately from config.toml.",+ copy: { label: "OAuth login", value: "codex mcp login mso" },+ },+ {+ title: "Optional config.toml form",+ body: "Use this when you prefer editing ~/.codex/config.toml directly. Keep secrets out of the file; MSO does not need a static bearer token.",+ copy: { label: "~/.codex/config.toml", value: codexMcpConfig(endpoints.origin), multiline: true },+ },+ ];+ }++ if (client === "claude-code") {+ return [+ {+ title: "Add a remote HTTP MCP server",+ body: "Claude Code supports remote HTTP MCP servers. Register MSO at user or project scope as appropriate.",+ copy: { label: "Claude Code CLI", value: `claude mcp add --transport http mso ${endpoints.mcp}` },+ },+ {+ title: "Complete OAuth from /mcp",+ body: "Open /mcp in Claude Code, choose MSO, and follow the browser authorization flow. Do not put your MSO password or bearer token in the command.",+ },+ {+ title: "Verify the connection",+ body: "Use claude mcp get mso or claude mcp list, then test a read-only MSO operation before granting broader authority.",+ copy: { label: "Verify", value: "claude mcp get mso" },+ },+ ];+ }++ if (client === "cursor") {+ return [+ {+ title: "Add a remote MCP server",+ body: "Open Cursor MCP settings or edit ~/.cursor/mcp.json. This URL form lets Cursor negotiate remote OAuth without embedding credentials.",+ copy: { label: "Cursor mcp.json", value: cursorMcpConfig(endpoints.origin), multiline: true },+ },+ {+ title: "Complete OAuth",+ body: "Let Cursor discover MSO's OAuth metadata and complete the browser authorization flow. MSO also supports Dynamic Client Registration for clients that use it.",+ },+ {+ title: "Verify and refresh tools",+ body: "Confirm MSO is enabled and its tool list is current. Reconnect or refresh the server after the MSO toolset signature changes.",+ },+ ];+ }++ if (client === "gemini") {+ return [+ {+ title: "Add the remote HTTP server",+ body: "Gemini CLI stores MCP servers in settings.json and can add an HTTP endpoint from the command line.",+ copy: { label: "Gemini CLI", value: `gemini mcp add --transport http mso ${endpoints.mcp}` },+ },+ {+ title: "Authorize if prompted",+ body: "Use the client's OAuth flow when it detects MSO's protected-resource metadata. Never hardcode a standing token in a shared project settings file.",+ },+ {+ title: "Verify",+ body: "List MCP servers and make a read-only request first so you can confirm discovery, scope, and tool availability before using mutations.",+ copy: { label: "Verify", value: "gemini mcp list" },+ },+ ];+ }++ if (client === "vscode") {+ return [+ {+ title: "Add an HTTP server",+ body: "Run MCP: Add Server from the Command Palette, choose HTTP, or add this to your user/workspace mcp.json. VS Code tries Streamable HTTP first.",+ copy: { label: "VS Code mcp.json", value: vscodeMcpConfig(endpoints.origin), multiline: true },+ },+ {+ title: "Trust and authenticate",+ body: "Review the MCP trust prompt. VS Code can perform OAuth/Dynamic Client Registration when the remote server advertises it, so no secret belongs in this config.",+ },+ {+ title: "Reset cached tools after updates",+ body: "If MSO's toolset signature changes, run MCP: Reset Cached Tools or restart the server before assuming a newly added tool is unavailable.",+ },+ ];+ }++ return [+ {+ title: "Add a remote Streamable HTTP server",+ body: "In any MCP client that supports Streamable HTTP, add this remote endpoint. Cloud clients need a reachable HTTPS origin or a supported private tunnel.",+ copy: { label: "MCP Server URL", value: endpoints.mcp },+ },+ {+ title: "Use OAuth discovery",+ body: "Prefer protected-resource + authorization-server discovery and PKCE. MSO also exposes Dynamic Client Registration for clients that still use it.",+ },+ {+ title: "Authorize the minimum scope",+ body: "Complete the MSO consent flow and start with read. Raise to write or exec only when the client genuinely needs that authority.",+ },+ ];+}diff --git a/frontend/slices/os-settings/components/mcp-connection-mode.tsx b/frontend/slices/os-settings/components/mcp-connection-mode.tsxnew file mode 100644index 00000000..c166fbb8--- /dev/null+++ b/frontend/slices/os-settings/components/mcp-connection-mode.tsx@@ -0,0 +1,59 @@+"use client";++import { useState } from "react";+import { CloudCog, Globe2 } from "lucide-react";+import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";+import { cn } from "@/lib/utils";+import { McpCopyField } from "./mcp-copy-field";+import type { McpEndpointSet } from "./mcp-client-core";++type ConnectionMode = "server" | "tunnel";++export function McpConnectionMode({ endpoints, remote }: { endpoints: McpEndpointSet; remote: boolean }) {+ const [mode, setMode] = useState<ConnectionMode>("server");+ return (+ <div className="space-y-3">+ <div className="flex items-center justify-between gap-3">+ <div>+ <p className="text-[13px] font-medium">Connection</p>+ <p className="mt-0.5 text-[11px] text-muted-foreground">Use the direct HTTPS URL when this MSO host is reachable; use a tunnel for private or developer-machine deployments.</p>+ </div>+ <Globe2 className="size-4 shrink-0 text-muted-foreground" />+ </div>+ <Tabs>+ <TabsList className="w-full sm:w-auto">+ <TabsTrigger active={mode === "server"} onClick={() => setMode("server")} className="min-h-9 flex-1 sm:flex-none [@media(pointer:coarse)]:min-h-[44px]">Server URL</TabsTrigger>+ <TabsTrigger active={mode === "tunnel"} onClick={() => setMode("tunnel")} className="min-h-9 flex-1 sm:flex-none [@media(pointer:coarse)]:min-h-[44px]">Tunnel</TabsTrigger>+ </TabsList>+ </Tabs>+ {mode === "server" ? (+ <div className="space-y-3">+ <McpCopyField label="MCP Server URL · Streamable HTTP" value={endpoints.mcp} />+ <div className={cn("rounded-lg border px-3 py-2.5 text-xs leading-relaxed", remote ? "border-success/30 bg-success/10" : "border-warning/30 bg-warning/10")}>+ {remote ? (+ <><strong>Remote HTTPS origin detected.</strong> Cloud clients can use this URL directly, subject to your reverse proxy/firewall and workspace policy.</>+ ) : (+ <><strong>Local-only origin detected.</strong> A cloud client such as ChatGPT cannot connect directly to {endpoints.origin}. Switch to Tunnel for the supported options.</>+ )}+ </div>+ </div>+ ) : (+ <div className="grid gap-3 sm:grid-cols-2">+ <div className="rounded-lg border border-border/70 bg-secondary/25 p-3">+ <div className="flex items-center gap-2"><CloudCog className="size-4" /><p className="text-xs font-medium">MSO Gateway</p></div>+ <p className="mt-1.5 text-[11px] leading-relaxed text-muted-foreground">Keep local/WSL MSO on loopback and create an outbound HTTPS gateway. A named tunnel/custom domain is the stable production choice.</p>+ <div className="mt-3 space-y-2">+ <McpCopyField label="Temporary gateway" value={'mso gateway start\nmso gateway url'} multiline />+ <McpCopyField label="Stable origin" value={`mso gateway domain set ${remote ? endpoints.origin : "https://mso.example.com"}`} />+ </div>+ </div>+ <div className="rounded-lg border border-border/70 bg-secondary/25 p-3">+ <div className="flex items-center gap-2"><Globe2 className="size-4" /><p className="text-xs font-medium">Custom domain / reverse proxy</p></div>+ <p className="mt-1.5 text-[11px] leading-relaxed text-muted-foreground">For a stable URL, route an HTTPS hostname to the loopback MSO runtime through your trusted tunnel or reverse proxy, then set that same origin in MSO.</p>+ <p className="mt-3 text-[10px] leading-relaxed text-muted-foreground">Keep the raw Next listener loopback-only. OAuth discovery, redirect validation, cookies, and MCP resource metadata must agree on one public origin.</p>+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/frontend/slices/os-settings/components/mcp-connection-section.tsx b/frontend/slices/os-settings/components/mcp-connection-section.tsxindex b28933d4..89a8bf2e 100644--- a/frontend/slices/os-settings/components/mcp-connection-section.tsx+++ b/frontend/slices/os-settings/components/mcp-connection-section.tsx@@ -1,38 +1,10 @@"use client";-import { useState } from "react";-import { Check, Copy, Plug, Wrench } from "lucide-react";-import { Button } from "@/components/ui/button";-import { SettingsBlock, SettingsSection } from "@/features/shell-settings";+import { Wrench } from "lucide-react";+import { SettingsSection } from "@/features/shell-settings";+import { McpSetupGuide } from "./mcp-setup-guide";import { McpToolsetCard, type McpToolsetInfo } from "./mcp-toolset-card";-function CopyRow({ label, value }: { label: string; value: string }) {- const [copied, setCopied] = useState(false);- return (- <SettingsBlock className="flex flex-col gap-2.5 sm:flex-row sm:items-center">- <span className="shrink-0 text-[13px] font-medium sm:w-32">{label}</span>- <div className="min-w-0 flex-1 rounded-lg bg-secondary/60 px-3 py-2">- <code className="block break-all font-mono text-[11px] leading-relaxed text-secondary-foreground sm:text-xs">{value}</code>- </div>- <Button- type="button"- variant="ghost"- size="icon"- aria-label={`Copy ${label}`}- className="size-9 shrink-0 self-end sm:self-auto [@media(pointer:coarse)]:size-11"- onClick={() => {- void navigator.clipboard.writeText(value).then(() => {- setCopied(true);- window.setTimeout(() => setCopied(false), 1500);- });- }}- >- {copied ? <Check className="size-4" /> : <Copy className="size-4" />}- </Button>- </SettingsBlock>- );-}-export function McpConnectionSection({origin,maxScope,@@ -44,30 +16,7 @@ export function McpConnectionSection({}) {return (<div className="space-y-4 sm:space-y-5">- <SettingsSection- icon={<Plug />}- title="Connection"- footnote={<>Highest scope this server will mint: <strong>{maxScope}</strong> (<code className="font-mono">OS_MCP_MAX_SCOPE</code>).</>}- >- <SettingsBlock className="space-y-1.5 py-4">- <p className="text-sm font-medium">Connect ChatGPT with User-Defined OAuth</p>- <p className="text-xs leading-relaxed text-muted-foreground">- In ChatGPT open Settings → Connectors → New App. Use OAuth, leave Client Secret empty, and set token endpoint authentication to none.- </p>- </SettingsBlock>- <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" />- <SettingsBlock className="space-y-1.5 py-4">- <p className="text-[13px] font-medium">Other MCP clients</p>- <p className="text-xs leading-relaxed text-muted-foreground">- Claude.ai, Cursor and mcp-remote register themselves. Give them <code className="break-all font-mono">{origin}/mcp</code> and nothing else.- </p>- </SettingsBlock>- </SettingsSection>-+ <McpSetupGuide origin={origin} maxScope={maxScope} /><SettingsSection icon={<Wrench />} title="Toolset status" bare><McpToolsetCard info={toolset} /></SettingsSection>diff --git a/frontend/slices/os-settings/components/mcp-copy-field.tsx b/frontend/slices/os-settings/components/mcp-copy-field.tsxnew file mode 100644index 00000000..fe59dc32--- /dev/null+++ b/frontend/slices/os-settings/components/mcp-copy-field.tsx@@ -0,0 +1,31 @@+"use client";++import { useState } from "react";+import { Check, Copy } from "lucide-react";+import { Button } from "@/components/ui/button";+import { cn } from "@/lib/utils";++export function McpCopyField({ label, value, multiline = false }: { label: string; value: string; multiline?: boolean }) {+ const [copied, setCopied] = useState(false);+ return (+ <div className="space-y-1.5">+ <span className="text-[11px] font-medium text-muted-foreground">{label}</span>+ <div className="flex items-start gap-2 rounded-lg border border-border/70 bg-secondary/45 p-2.5">+ <code className={cn("min-w-0 flex-1 break-all font-mono text-[11px] leading-relaxed text-secondary-foreground", multiline && "whitespace-pre-wrap break-words")}>{value}</code>+ <Button+ type="button"+ variant="ghost"+ size="icon"+ className="size-8 shrink-0 [@media(pointer:coarse)]:size-11"+ aria-label={`Copy ${label}`}+ onClick={() => void navigator.clipboard.writeText(value).then(() => {+ setCopied(true);+ window.setTimeout(() => setCopied(false), 1500);+ })}+ >+ {copied ? <Check className="size-4" /> : <Copy className="size-4" />}+ </Button>+ </div>+ </div>+ );+}diff --git a/frontend/slices/os-settings/components/mcp-probe-status.tsx b/frontend/slices/os-settings/components/mcp-probe-status.tsxnew file mode 100644index 00000000..32317029--- /dev/null+++ b/frontend/slices/os-settings/components/mcp-probe-status.tsx@@ -0,0 +1,32 @@+"use client";++import { CheckCircle2, CircleAlert } from "lucide-react";+import { cn } from "@/lib/utils";+import { MCP_PROBE_LABELS, type McpProbeResult } from "./mcp-client-core";++export type ProbeState = "checking" | "ready" | "error";++export function McpProbeStatus({ state, result, endpoint }: { state: ProbeState; result: McpProbeResult | null; endpoint: string }) {+ const ready = state === "ready";+ return (+ <div className={cn(+ "space-y-2 rounded-lg border px-3 py-2.5",+ ready ? "border-success/30 bg-success/10" : state === "error" ? "border-destructive/30 bg-destructive/10" : "border-border bg-secondary/35",+ )}>+ <div className="flex items-start gap-2">+ {ready ? <CheckCircle2 className="mt-0.5 size-4 shrink-0 text-success" /> : <CircleAlert className="mt-0.5 size-4 shrink-0 text-muted-foreground" />}+ <div className="min-w-0">+ <p className="text-xs font-medium">{ready ? "MCP + OAuth discovery ready" : state === "error" ? "One or more connection checks failed" : "Checking MCP + OAuth discovery…"}</p>+ <p className="mt-0.5 break-all font-mono text-[10px] text-muted-foreground">{endpoint}</p>+ </div>+ </div>+ {result && (+ <div className="flex flex-wrap gap-1.5 pl-6">+ {result.checks.map((check) => (+ <span key={check.id} className={cn("rounded-md px-2 py-1 text-[10px] font-medium", check.ok ? "bg-success/10 text-success" : "bg-destructive/10 text-destructive")}>{MCP_PROBE_LABELS[check.id]}</span>+ ))}+ </div>+ )}+ </div>+ );+}diff --git a/frontend/slices/os-settings/components/mcp-probe.ts b/frontend/slices/os-settings/components/mcp-probe.tsnew file mode 100644index 00000000..9a4e3192--- /dev/null+++ b/frontend/slices/os-settings/components/mcp-probe.ts@@ -0,0 +1,61 @@+import { mcpEndpoints, type McpProbeResult } from "./mcp-client-core";++type FetchLike = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;++async function jsonOrNull(response: Response): Promise<Record<string, unknown> | null> {+ if (!response.ok) return null;+ try {+ return (await response.json()) as Record<string, unknown>;+ } catch {+ return null;+ }+}++function headerHasResourceMetadata(response: Response, expectedUrl: string) {+ if (response.status !== 401) return false;+ const challenge = response.headers.get("www-authenticate") ?? "";+ return challenge.toLowerCase().startsWith("bearer ") && challenge.includes(`resource_metadata=\"${expectedUrl}\"`);+}++export async function probeMcpConnection(rawOrigin: string, fetcher: FetchLike = fetch): Promise<McpProbeResult> {+ const endpoints = mcpEndpoints(rawOrigin);+ const [mcpResponse, challengeResponse, resourceResponse, oauthResponse] = await Promise.all([+ fetcher(endpoints.mcp, { cache: "no-store" }).catch(() => new Response(null, { status: 599 })),+ fetcher(endpoints.mcp, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ jsonrpc: "2.0", id: "settings-probe", method: "initialize", params: {} }),+ cache: "no-store",+ }).catch(() => new Response(null, { status: 599 })),+ fetcher(endpoints.protectedResource, { cache: "no-store" }).catch(() => new Response(null, { status: 599 })),+ fetcher(endpoints.authorizationServer, { cache: "no-store" }).catch(() => new Response(null, { status: 599 })),+ ]);++ const [mcp, resource, oauth] = await Promise.all([+ jsonOrNull(mcpResponse),+ jsonOrNull(resourceResponse),+ jsonOrNull(oauthResponse),+ ]);++ const authServers = (mcp?.authorization_servers as unknown[]) ?? [];+ const resourceAuthServers = (resource?.authorization_servers as unknown[]) ?? [];+ const pkceMethods = (oauth?.code_challenge_methods_supported as unknown[]) ?? [];+ const tokenMethods = (oauth?.token_endpoint_auth_methods_supported as unknown[]) ?? [];++ const checks: McpProbeResult["checks"] = [+ { id: "mcp", ok: mcp?.name === "mso MCP" && authServers.includes(endpoints.origin) },+ { id: "challenge", ok: headerHasResourceMetadata(challengeResponse, endpoints.protectedResource) },+ { id: "resource", ok: resource?.resource === endpoints.mcp && resourceAuthServers.includes(endpoints.origin) },+ {+ id: "oauth",+ ok:+ oauth?.issuer === endpoints.origin &&+ oauth.authorization_endpoint === endpoints.authorize &&+ oauth.token_endpoint === endpoints.token &&+ oauth.registration_endpoint === endpoints.register &&+ pkceMethods.includes("S256") &&+ tokenMethods.includes("none"),+ },+ ];+ return { ready: checks.every((check) => check.ok), checks };+}diff --git a/frontend/slices/os-settings/components/mcp-section.tsx b/frontend/slices/os-settings/components/mcp-section.tsxindex 86ce0f82..df7bc52e 100644--- a/frontend/slices/os-settings/components/mcp-section.tsx+++ b/frontend/slices/os-settings/components/mcp-section.tsx@@ -9,25 +9,25 @@ import { McpAuditSection, type McpAuditRow } from "./mcp-audit-section";import { McpConnectionSection } from "./mcp-connection-section";import { McpTokenSection, type McpTokenRow } from "./mcp-token-section";import type { McpToolsetInfo } from "./mcp-toolset-card";+import { McpCopyField } from "./mcp-copy-field";type McpState = {enabled: boolean;maxScope: string;toolset: McpToolsetInfo;tokens: McpTokenRow[];+ origin: string;};export function McpSection() {const [state, setState] = useState<McpState | null>(null);const [trail, setTrail] = useState<McpAuditRow[]>([]);- const [origin, setOrigin] = useState("");const load = useCallback(() => {if (IS_DEMO) return;fetch("/api/mcp/tokens", { cache: "no-store" }).then((response) => (response.ok ? response.json() : Promise.reject(new Error(`HTTP ${response.status}`)))).then((next: McpState) => {- setOrigin(window.location.origin);setState(next);}).catch(() => toast("Couldn't load MCP tokens", { tone: "error" }));@@ -81,10 +81,16 @@ export function McpSection() {title="MCP connection"footnote="When disabled, the MCP endpoint and OAuth discovery documents return 404, so no unauthenticated MCP surface remains exposed.">- <SettingsBlock className="space-y-2 py-4">- <p className="text-sm font-medium">MCP is disabled</p>+ <SettingsBlock className="space-y-3 py-4">+ <div>+ <p className="text-sm font-medium">Turn on MCP first</p>+ <p className="mt-1 text-xs leading-relaxed text-muted-foreground">+ Add these values to <code className="font-mono">.env.local</code>. Start with read access; raise the ceiling only when you actually need writes or host execution.+ </p>+ </div>+ <McpCopyField label="Recommended starting config" value={"OS_MCP_ENABLED=1\nOS_MCP_MAX_SCOPE=read"} multiline /><p className="text-xs leading-relaxed text-muted-foreground">- Set <code className="font-mono">OS_MCP_ENABLED=1</code> in <code className="font-mono">.env.local</code> and restart <code className="font-mono">mso.service</code>.+ Apply it with <code className="font-mono">mso update --rebuild</code>. On WSL without systemd, MSO still rebuilds locally; reopen with <code className="font-mono">mso web</code> afterward.</p></SettingsBlock></SettingsSection>@@ -93,7 +99,7 @@ export function McpSection() {return (<div className="space-y-4 sm:space-y-5">- <McpConnectionSection origin={origin} maxScope={state.maxScope} toolset={state.toolset} />+ <McpConnectionSection origin={state.origin} maxScope={state.maxScope} toolset={state.toolset} /><McpTokenSection tokens={state.tokens} onRevoke={revoke} /><McpAuditSection trail={trail} /></div>diff --git a/frontend/slices/os-settings/components/mcp-setup-guide.tsx b/frontend/slices/os-settings/components/mcp-setup-guide.tsxnew file mode 100644index 00000000..30cce6ba--- /dev/null+++ b/frontend/slices/os-settings/components/mcp-setup-guide.tsx@@ -0,0 +1,96 @@+"use client";++import { useCallback, useEffect, useMemo, useState } from "react";+import { Bot, PlugZap, RefreshCw, ShieldCheck, TerminalSquare } from "lucide-react";+import { Button } from "@/components/ui/button";+import { SettingsBlock, SettingsSection } from "@/features/shell-settings";+import { cn } from "@/lib/utils";+import { McpClientSetup } from "./mcp-client-setup";+import { MCP_CLIENTS, isRemoteMcpOrigin, mcpEndpoints, type McpClientId, type McpProbeResult } from "./mcp-client-core";+import { probeMcpConnection } from "./mcp-probe";+import { mcpClientSteps } from "./mcp-client-steps";+import { McpConnectionMode } from "./mcp-connection-mode";+import { McpCopyField } from "./mcp-copy-field";+import { McpProbeStatus, type ProbeState } from "./mcp-probe-status";++function sameOriginFetch(input: RequestInfo | URL, init?: RequestInit) {+ const target = new URL(String(input));+ return fetch(`${target.pathname}${target.search}`, init);+}++export function McpSetupGuide({ origin, maxScope }: { origin: string; maxScope: string }) {+ const [client, setClient] = useState<McpClientId>("chatgpt");+ const [probeState, setProbeState] = useState<ProbeState>("checking");+ const [probeResult, setProbeResult] = useState<McpProbeResult | null>(null);+ const endpoints = useMemo(() => mcpEndpoints(origin), [origin]);+ const steps = useMemo(() => mcpClientSteps(client, origin), [client, origin]);+ const selected = MCP_CLIENTS.find((item) => item.id === client) ?? MCP_CLIENTS[0];++ const applyProbe = useCallback((result: McpProbeResult | null) => {+ setProbeResult(result);+ setProbeState(result?.ready ? "ready" : "error");+ }, []);++ const testConnection = useCallback(async () => {+ setProbeState("checking");+ setProbeResult(null);+ applyProbe(await probeMcpConnection(origin, sameOriginFetch).catch(() => null));+ }, [applyProbe, origin]);++ useEffect(() => {+ let current = true;+ void probeMcpConnection(origin, sameOriginFetch).then((result) => { if (current) applyProbe(result); }).catch(() => { if (current) applyProbe(null); });+ return () => { current = false; };+ }, [applyProbe, origin]);++ return (+ <SettingsSection+ icon={<PlugZap />}+ title="Connect an AI client"+ footnote={<>MSO uses remote Streamable HTTP + OAuth/PKCE. The server ceiling is <strong>{maxScope}</strong>; each authorization can choose a lower scope.</>}+ >+ <SettingsBlock className="space-y-3 py-4">+ <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">+ <div className="min-w-0">+ <div className="flex items-center gap-2"><Bot className="size-4 shrink-0" /><p className="text-sm font-medium">Connect MSO to ChatGPT, coding agents, and MCP-capable editors</p></div>+ <p className="mt-1 text-xs leading-relaxed text-muted-foreground">The client receives only the scope you approve. MSO keeps host boundaries, revocation, rate limits, and audit server-side.</p>+ </div>+ <Button type="button" variant="secondary" size="sm" className="min-h-9 shrink-0 [@media(pointer:coarse)]:min-h-[44px]" onClick={() => void testConnection()}>+ <RefreshCw className={cn("mr-1.5 size-3.5", probeState === "checking" && "animate-spin")} />Test connection+ </Button>+ </div>+ <McpProbeStatus state={probeState} result={probeResult} endpoint={endpoints.mcp} />+ </SettingsBlock>++ <SettingsBlock className="py-4"><McpConnectionMode endpoints={endpoints} remote={isRemoteMcpOrigin(origin)} /></SettingsBlock>++ <SettingsBlock className="space-y-4 py-4">+ <McpClientSetup client={client} onClientChange={setClient} selected={selected} steps={steps} />+ </SettingsBlock>++ <SettingsBlock className="space-y-3 py-4">+ <details className="group rounded-lg border border-border/70 bg-secondary/25 px-3 py-2.5">+ <summary className="cursor-pointer select-none text-xs font-medium">Advanced OAuth settings</summary>+ <div className="mt-3 grid gap-3 sm:grid-cols-2">+ <McpCopyField label="MCP Server URL / Resource" value={endpoints.mcp} />+ <McpCopyField label="Authorization URL" value={endpoints.authorize} />+ <McpCopyField label="Token URL" value={endpoints.token} />+ <McpCopyField label="Dynamic registration" value={endpoints.register} />+ <McpCopyField label="Protected-resource metadata" value={endpoints.protectedResource} />+ <McpCopyField label="Authorization-server metadata" value={endpoints.authorizationServer} />+ <McpCopyField label="Public Client ID (manual fallback)" value="chatgpt-mso" />+ <McpCopyField label="Authentication" value="OAuth · authorization_code · PKCE S256" />+ </div>+ <p className="mt-3 text-[11px] leading-relaxed text-muted-foreground">Client secret: none · token endpoint auth: none · refresh token: not issued · access tokens require authorization again after expiry/revocation.</p>+ </details>+ <div className="flex gap-2 rounded-lg border border-warning/30 bg-warning/10 px-3 py-2.5">+ <ShieldCheck className="mt-0.5 size-4 shrink-0" />+ <div className="text-xs leading-relaxed">+ <p className="font-medium">Choose the lowest authority that works</p>+ <p className="mt-0.5 text-muted-foreground"><strong>read</strong> inspects data, <strong>write</strong> can change files/apps, and <strong>exec</strong> can execute host commands as the MSO service user. Treat exec like remote shell access.</p>+ </div>+ </div>+ </SettingsBlock>+ </SettingsSection>+ );+}diff --git a/frontend/slices/os-settings/lib/sections.ts b/frontend/slices/os-settings/lib/sections.tsindex d82cbd75..aa7e4e0c 100644--- a/frontend/slices/os-settings/lib/sections.ts+++ b/frontend/slices/os-settings/lib/sections.ts@@ -31,7 +31,7 @@ export const SECTIONS: ReadonlyArray<SettingsSectionMeta> = [{ 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: "mcp", label: "MCP", blurb: "Connect ChatGPT, Cursor & MCP clients", 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" },