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
fix(mcp): restore main quality gates
Rahman0b49ae42d335
diff --git a/.env.example b/.env.exampleindex 993e5a02..b488138e 100644--- a/.env.example+++ b/.env.example@@ -138,6 +138,10 @@ OS_SESSION_SECRET=# usable the policy emits `frame-ancestors 'none'` and the window stays blank —# closed, on purpose, rather than naming a guessed origin as a permitted framer.# OS_PUBLIC_ORIGIN=https://mso.example.com+# Compatibility fallbacks for MCP/browser origin discovery when OS_PUBLIC_ORIGIN is unset.+# Prefer OS_PUBLIC_ORIGIN for normal MSO deployments.+# APP_URL=https://mso.example.com+# NEXT_PUBLIC_APP_URL=https://mso.example.com# Optional dedicated origin assigned to ChatGPT MCP Apps. When unset, MSO derives# mso-ui.<rest-of-host> from a leading mso.<rest-of-host>; otherwise it reuses the# sanitized public origin. This is instance configuration, never source-owned.diff --git a/bin/mso b/bin/msoindex 2a722749..fd09fb56 100755--- a/bin/mso+++ b/bin/mso@@ -78,7 +78,7 @@# models * Configure AI providers/auth; inspect model catalog# skills * Discover host skills + curated market: available/install/remove# changelog What shipped, newest first (same text Settings → About shows)-# mcp * MCP tokens + live activity: list | activity [n] | revoke <id> | revoke all+# mcp * MCP tokens + live activity: list | pat <label> [scope] [ttlDays] | activity [n] | revoke <id> | revoke all# oauth <prov> * Provider sign-in (device code): start | poll# audit [n] [prefix] Audit trail, newest first (writes/exec/auth; reads are not logged)# stock <query> [page] Stock-image search (Unsplash key optional, Openverse fallback)diff --git a/docs/CLI.md b/docs/CLI.mdindex d33e1509..330a515a 100644--- a/docs/CLI.md+++ b/docs/CLI.md@@ -118,7 +118,7 @@ Commands:models * Configure AI providers/auth; inspect model catalogskills * Discover host skills + curated market: available/install/removechangelog What shipped, newest first (same text Settings → About shows)- mcp * MCP tokens + live activity: list | activity [n] | revoke <id> | revoke all+ mcp * MCP tokens + live activity: list | pat <label> [scope] [ttlDays] | activity [n] | revoke <id> | revoke alloauth <prov> * Provider sign-in (device code): start | pollaudit [n] [prefix] Audit trail, newest first (writes/exec/auth; reads are not logged)stock <query> [page] Stock-image search (Unsplash key optional, Openverse fallback)diff --git a/docs/generated/MCP-CATALOG.md b/docs/generated/MCP-CATALOG.mdindex 66fde7ef..679328bb 100644--- a/docs/generated/MCP-CATALOG.md+++ b/docs/generated/MCP-CATALOG.md@@ -4,7 +4,7 @@## Full MSO catalog-<!-- mcp-toolset: server=1.15.4 version=2026.09.22.2 tools=114 read=56 write=35 exec=23 -->+<!-- mcp-toolset: server=1.15.4 version=2026.09.22.2 tools=114 read=57 write=34 exec=23 -->| Fact | Current source value ||---|---:|@@ -13,12 +13,12 @@| Toolset changed at | `2026-09-22T10:30:00+07:00` || Transport tools | **116** || Model/operator tools | **114** |-| Read | **56** |-| Write | **35** |+| Read | **57** |+| Write | **34** || Exec | **23** || App-only bridges | **2** |-### Read (56)+### Read (57)- `a2a_agent_discover`- `a2a_agents_list`@@ -28,6 +28,7 @@- `agent_session_action_resolve`- `agent_session_current`- `agent_session_flow`+- `agent_session_open`- `agent_session_resume`- `agent_sessions_list`- `apps_list`@@ -77,14 +78,13 @@- `tool_forge_candidates`- `vps_status`-### Write (35)+### Write (34)- `a2a_agent_register`- `a2a_agent_remove`- `agent_memory_forget`- `agent_memory_remember`- `agent_session_note`-- `agent_session_open`- `agent_session_rename`- `apps_power`- `cloudflare_dns_upsert`@@ -148,7 +148,7 @@## ChatGPT model profile-<!-- mcp-chatgpt-profile: server=1.15.4 version=2026.09.22.2 tools=114 read=56 write=35 exec=23 app-only=2 total=116 -->+<!-- mcp-chatgpt-profile: server=1.15.4 version=2026.09.22.2 tools=114 read=57 write=34 exec=23 app-only=2 total=116 -->The ChatGPT profile automatically projects the complete MSO-owned generic model/operator catalog. OAuth scope is still enforced independently; app-only compatibility bridges stay app-only, and project-owned MCP tool names remain dynamic data behind the generic project bridge.@@ -156,12 +156,12 @@ The ChatGPT profile automatically projects the complete MSO-owned generic model/|---|---:|| ChatGPT transport tools | **116** || ChatGPT model/operator tools | **114** |-| Read | **56** |-| Write | **35** |+| Read | **57** |+| Write | **34** || Exec | **23** || App-only bridges | **2** |-### ChatGPT read (56)+### ChatGPT read (57)- `a2a_agent_discover`- `a2a_agents_list`@@ -171,6 +171,7 @@ The ChatGPT profile automatically projects the complete MSO-owned generic model/- `agent_session_action_resolve`- `agent_session_current`- `agent_session_flow`+- `agent_session_open`- `agent_session_resume`- `agent_sessions_list`- `apps_list`@@ -220,14 +221,13 @@ The ChatGPT profile automatically projects the complete MSO-owned generic model/- `tool_forge_candidates`- `vps_status`-### ChatGPT write (35)+### ChatGPT write (34)- `a2a_agent_register`- `a2a_agent_remove`- `agent_memory_forget`- `agent_memory_remember`- `agent_session_note`-- `agent_session_open`- `agent_session_rename`- `apps_power`- `cloudflare_dns_upsert`diff --git a/frontend/slices/os-settings/components/mcp-connect-modal.tsx b/frontend/slices/os-settings/components/mcp-connect-modal.tsxindex 3a559263..1dd76de8 100644--- a/frontend/slices/os-settings/components/mcp-connect-modal.tsx+++ b/frontend/slices/os-settings/components/mcp-connect-modal.tsx@@ -2,13 +2,7 @@import { AlertTriangle, Key } from "lucide-react";import { useState } from "react";-import {- Dialog,- DialogContent,- DialogDescription,- DialogHeader,- DialogTitle,-} from "@/components/ui/dialog";+import { ResponsiveDialog } from "@/features/appshell";import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";import { McpCopyField } from "./mcp-copy-field";@@ -78,18 +72,18 @@ export function McpConnectModal({const geminiCliCommand = `gemini mcp add --transport http --scope user -H "Authorization: Bearer ${tokenValue}" mso ${mcpUrl}`;return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent className="max-h-[90vh] max-w-2xl overflow-y-auto p-6">- <DialogHeader className="space-y-2">- <DialogTitle className="flex items-center gap-2 text-xl">+ <ResponsiveDialog open={open} onOpenChange={onOpenChange} size="lg" mobileVariant="drawer-bottom">+ <ResponsiveDialog.Header>+ <ResponsiveDialog.Title className="flex items-center gap-2 text-xl"><Key className="size-5 text-primary" />Connect MCP to Your AI Agent- </DialogTitle>- <DialogDescription>+ </ResponsiveDialog.Title>+ <ResponsiveDialog.Description>{label ? `Credentials for “${label}”. ` : ""}Configure your AI assistant or IDE to control MSO using Streamable HTTP.- </DialogDescription>- </DialogHeader>+ </ResponsiveDialog.Description>+ </ResponsiveDialog.Header>+ <ResponsiveDialog.Body className="space-y-4">{token && (<div className="space-y-2 rounded-lg border border-amber-500/30 bg-amber-500/10 p-3.5 text-sm text-amber-600 dark:text-amber-400">@@ -106,7 +100,7 @@ export function McpConnectModal({</div>)}- <div className="mt-2 space-y-4">+ <div className="space-y-4"><Tabs><TabsList className="grid w-full grid-cols-4"><TabsTrigger@@ -198,7 +192,7 @@ export function McpConnectModal({</div>)}</div>- </DialogContent>- </Dialog>+ </ResponsiveDialog.Body>+ </ResponsiveDialog>);}diff --git a/frontend/slices/os-settings/components/mcp-pat-dialog.tsx b/frontend/slices/os-settings/components/mcp-pat-dialog.tsxnew file mode 100644index 00000000..738dfea4--- /dev/null+++ b/frontend/slices/os-settings/components/mcp-pat-dialog.tsx@@ -0,0 +1,114 @@+"use client";++import { Button } from "@/components/ui/button";+import { ResponsiveDialog } from "@/features/appshell";+import { useState } from "react";++export function McpPatDialog({+ open,+ maxScope,+ onOpenChange,+ onMinted,+}: {+ open: boolean;+ maxScope: string;+ onOpenChange: (open: boolean) => void;+ onMinted: (token: string, label: string) => void;+}) {+ const [label, setLabel] = useState("");+ const [scope, setScope] = useState(maxScope === "read" ? "read" : maxScope === "write" ? "write" : "exec");+ const [ttl, setTtl] = useState("0");+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState("");++ const allowedScopes = ["read"];+ if (maxScope === "write" || maxScope === "exec") allowedScopes.push("write");+ if (maxScope === "exec") allowedScopes.push("exec");++ async function submit(event: React.FormEvent) {+ event.preventDefault();+ const cleanLabel = label.trim();+ if (!cleanLabel) {+ setError("Please enter a name for this token.");+ return;+ }+ setBusy(true);+ setError("");+ try {+ const response = await fetch("/api/mcp/tokens", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ label: cleanLabel, scope, ttlDays: Number(ttl) || 0 }),+ });+ const data = await response.json();+ if (!response.ok || !data.ok) throw new Error(data.error || "Failed to generate token");+ setLabel("");+ onOpenChange(false);+ onMinted(data.token, cleanLabel);+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : "Failed to generate token");+ } finally {+ setBusy(false);+ }+ }++ return (+ <ResponsiveDialog open={open} onOpenChange={onOpenChange} size="md" mobileVariant="drawer-bottom">+ <ResponsiveDialog.Header>+ <ResponsiveDialog.Title>Generate Personal Access Token (PAT)</ResponsiveDialog.Title>+ <ResponsiveDialog.Description>+ Create a long-lived or permanent token for Gemini CLI, Antigravity, Cursor, or scripts.+ </ResponsiveDialog.Description>+ </ResponsiveDialog.Header>+ <ResponsiveDialog.Body>+ <form id="mcp-pat-form" onSubmit={submit} className="space-y-4">+ <div className="space-y-1.5">+ <label htmlFor="pat-label" className="text-sm font-medium">Token Name / Description</label>+ <input+ id="pat-label"+ type="text"+ placeholder="e.g. Gemini CLI, Antigravity, Cursor"+ value={label}+ onChange={(event) => setLabel(event.target.value)}+ maxLength={80}+ required+ className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-xs focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"+ />+ </div>+ <div className="space-y-1.5">+ <label htmlFor="pat-ttl" className="text-sm font-medium">Expiration / Masa Aktif</label>+ <select+ id="pat-ttl"+ value={ttl}+ onChange={(event) => setTtl(event.target.value)}+ className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-xs focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"+ >+ <option value="0">Never expires (Permanent)</option>+ <option value="90">90 Days</option>+ <option value="30">30 Days</option>+ <option value="7">7 Days</option>+ </select>+ </div>+ <div className="space-y-1.5">+ <label htmlFor="pat-scope" className="text-sm font-medium">Access Scope</label>+ <select+ id="pat-scope"+ value={scope}+ onChange={(event) => setScope(event.target.value)}+ className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-xs focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"+ >+ {allowedScopes.includes("read") && <option value="read">Read (Read-only data access)</option>}+ {allowedScopes.includes("write") && <option value="write">Write (Read + change data, manage apps)</option>}+ {allowedScopes.includes("exec") && <option value="exec">Exec (Full host commands & workflows)</option>}+ </select>+ </div>+ {error && <p role="alert" className="text-sm text-destructive">{error}</p>}+ </form>+ </ResponsiveDialog.Body>+ <ResponsiveDialog.Footer>+ <Button type="button" variant="secondary" disabled={busy} onClick={() => onOpenChange(false)}>Cancel</Button>+ <Button type="submit" form="mcp-pat-form" disabled={busy}>{busy ? "Generating…" : "Generate Token"}</Button>+ </ResponsiveDialog.Footer>+ </ResponsiveDialog>+ );+}diff --git a/frontend/slices/os-settings/components/mcp-token-section.tsx b/frontend/slices/os-settings/components/mcp-token-section.tsxindex 0dca6482..2ec8f7cf 100644--- a/frontend/slices/os-settings/components/mcp-token-section.tsx+++ b/frontend/slices/os-settings/components/mcp-token-section.tsx@@ -1,17 +1,11 @@"use client";import { Button } from "@/components/ui/button";-import {- Dialog,- DialogContent,- DialogDescription,- DialogHeader,- DialogTitle,-} from "@/components/ui/dialog";import { SettingsBlock, SettingsSection } from "@/features/shell-settings";import { KeyRound, Plus, Share2 } from "lucide-react";import { useState } from "react";import { McpConnectModal } from "./mcp-connect-modal";+import { McpPatDialog } from "./mcp-pat-dialog";export type McpTokenRow = {id: string;@@ -24,11 +18,7 @@ export type McpTokenRow = {status: "active" | "revoked" | "expired";};-const formatTime = (time?: number) => {- if (time === 0) return "Never (Permanent)";- return time ? new Date(time).toLocaleString() : "Never";-};-+const formatTime = (time?: number) => time === 0 ? "Never (Permanent)" : time ? new Date(time).toLocaleString() : "Never";const permissions: Record<string, string> = {read: "Read data",write: "Read and change data",@@ -52,22 +42,11 @@ export function McpTokenSection({const [busy, setBusy] = useState(false);const [error, setError] = useState("");const [showInactive, setShowInactive] = useState(false);-- // PAT generation dialog stateconst [patDialogOpen, setPatDialogOpen] = useState(false);- const [patLabel, setPatLabel] = useState("");- const [patScope, setPatScope] = useState(maxScope === "read" ? "read" : maxScope === "write" ? "write" : "exec");- const [patTtl, setPatTtl] = useState<string>("0");- const [patBusy, setPatBusy] = useState(false);- const [patError, setPatError] = useState("");-- // Connect modal stateconst [connectModalOpen, setConnectModalOpen] = useState(false);- const [activePatToken, setActivePatToken] = useState<string | undefined>(undefined);- const [activePatLabel, setActivePatLabel] = useState<string | undefined>(undefined);-+ const [activePatToken, setActivePatToken] = useState<string>();+ const [activePatLabel, setActivePatLabel] = useState<string>();const effectiveOrigin = origin || (typeof window !== "undefined" ? window.location.origin : "");-const active = tokens.filter((token) => token.status === "active");const visible = showInactive ? tokens : active;@@ -80,7 +59,7 @@ export function McpTokenSection({method: "DELETE",signal: AbortSignal.timeout(10_000),});- if (!response.ok) throw new Error("Disconnect failed. Your selection is unchanged; try again.");+ if (!response.ok) throw new Error("Disconnect failed");setPending(null);onChanged();} catch {@@ -90,53 +69,12 @@ export function McpTokenSection({}}- async function handleGeneratePat(e: React.FormEvent) {- e.preventDefault();- const label = patLabel.trim();- if (!label) {- setPatError("Please enter a name for this token.");- return;- }- setPatBusy(true);- setPatError("");- try {- const response = await fetch("/api/mcp/tokens", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- label,- scope: patScope,- ttlDays: Number(patTtl) || 0,- }),- });- const data = await response.json();- if (!response.ok || !data.ok) {- throw new Error(data.error || "Failed to generate token");- }- setPatDialogOpen(false);- setPatLabel("");- onChanged();- // Show newly minted token in connect modal- setActivePatToken(data.token);- setActivePatLabel(label);- setConnectModalOpen(true);- } catch (err: unknown) {- setPatError(err instanceof Error ? err.message : "Failed to generate token");- } finally {- setPatBusy(false);- }- }-- function handleOpenConnect(label?: string) {+ function openConnect(label?: string) {setActivePatToken(undefined);setActivePatLabel(label);setConnectModalOpen(true);}- const allowedScopes = ["read"];- if (maxScope === "write" || maxScope === "exec") allowedScopes.push("write");- if (maxScope === "exec") allowedScopes.push("exec");-return (<SettingsSectionicon={<KeyRound />}@@ -144,141 +82,29 @@ export function McpTokenSection({footnote="Disconnecting revokes the access token immediately. The app must reconnect to regain access."><SettingsBlock className="flex flex-wrap items-center justify-between gap-3 py-3">- <p className="text-sm">- {active.length} active connection{active.length === 1 ? "" : "s"}- </p>+ <p className="text-sm">{active.length} active connection{active.length === 1 ? "" : "s"}</p><div className="flex flex-wrap gap-2">- <Button- variant="outline"- onClick={() => setPatDialogOpen(true)}- className="min-h-11"- >+ <Button variant="outline" onClick={() => setPatDialogOpen(true)} className="min-h-11"><Plus className="mr-1.5 size-4" />Generate New Token (PAT)</Button>- <Button onClick={onConnect} className="min-h-11">- Connect an app- </Button>+ <Button onClick={onConnect} className="min-h-11">Connect an app</Button></div></SettingsBlock>- {/* PAT Creation Dialog */}- <Dialog open={patDialogOpen} onOpenChange={setPatDialogOpen}>- <DialogContent className="max-w-md p-6">- <DialogHeader className="space-y-1">- <DialogTitle>Generate Personal Access Token (PAT)</DialogTitle>- <DialogDescription>- Create a long-lived or permanent token for Gemini CLI, Antigravity, Cursor, or scripts.- </DialogDescription>- </DialogHeader>-- <form onSubmit={handleGeneratePat} className="space-y-4">- <div className="space-y-1.5">- <label htmlFor="pat-label" className="text-sm font-medium">- Token Name / Description- </label>- <input- id="pat-label"- type="text"- placeholder="e.g. Gemini CLI, Antigravity, Cursor"- value={patLabel}- onChange={(e) => setPatLabel(e.target.value)}- maxLength={80}- required- className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-xs focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"- />- </div>-- <div className="space-y-1.5">- <label htmlFor="pat-ttl" className="text-sm font-medium">- Expiration / Masa Aktif- </label>- <select- id="pat-ttl"- value={patTtl}- onChange={(e) => setPatTtl(e.target.value)}- className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-xs focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"- >- <option value="0">Never expires (Permanent)</option>- <option value="90">90 Days</option>- <option value="30">30 Days</option>- <option value="7">7 Days</option>- </select>- </div>-- <div className="space-y-1.5">- <label htmlFor="pat-scope" className="text-sm font-medium">- Access Scope- </label>- <select- id="pat-scope"- value={patScope}- onChange={(e) => setPatScope(e.target.value)}- className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-xs focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"- >- {allowedScopes.includes("read") && (- <option value="read">Read (Read-only data access)</option>- )}- {allowedScopes.includes("write") && (- <option value="write">Write (Read + change data, manage apps)</option>- )}- {allowedScopes.includes("exec") && (- <option value="exec">Exec (Full host commands & workflows)</option>- )}- </select>- </div>-- {patError && (- <p role="alert" className="text-sm text-destructive">- {patError}- </p>- )}-- <div className="flex justify-end gap-2 pt-2">- <Button- type="button"- variant="secondary"- disabled={patBusy}- onClick={() => setPatDialogOpen(false)}- >- Cancel- </Button>- <Button type="submit" disabled={patBusy}>- {patBusy ? "Generating…" : "Generate Token"}- </Button>- </div>- </form>- </DialogContent>- </Dialog>-- {/* Disconnect Confirmation */}{pending && (<SettingsBlock className="space-y-3 border border-destructive/30 py-4"><p className="text-sm font-medium">Disconnect {pending.label}?</p>- <p className="text-sm text-muted-foreground">- Requests using this access will stop working immediately.- </p>- {error && (- <p role="alert" className="text-sm text-destructive">- {error}- </p>- )}+ <p className="text-sm text-muted-foreground">Requests using this access will stop working immediately.</p>+ {error && <p role="alert" className="text-sm text-destructive">{error}</p>}<div className="flex flex-wrap gap-2">- <Button- variant="destructive"- disabled={busy}- onClick={() => void disconnect()}- className="min-h-11"- >+ <Button variant="destructive" disabled={busy} onClick={() => void disconnect()} className="min-h-11">{busy ? "Disconnecting…" : "Confirm disconnect"}</Button><Buttonvariant="secondary"disabled={busy}- onClick={() => {- setPending(null);- setError("");- }}+ onClick={() => { setPending(null); setError(""); }}className="min-h-11">Cancel@@ -302,53 +128,33 @@ export function McpTokenSection({<div className="flex items-center gap-2"><h3 className="break-words text-sm font-medium">{token.label}</h3>{token.expiresAt === 0 && (- <span className="rounded bg-primary/10 px-1.5 py-0.5 text-[11px] font-medium text-primary">- Never expires- </span>+ <span className="rounded bg-primary/10 px-1.5 py-0.5 text-[11px] font-medium text-primary">Never expires</span>)}</div>- <p className="mt-1 text-sm text-muted-foreground">- {permissions[token.scope] ?? token.scope} · {token.status}- </p>- </div>- <div className="flex items-center gap-2">- {token.status === "active" && (- <>- <Button- variant="ghost"- size="sm"- onClick={() => handleOpenConnect(token.label)}- className="min-h-9"- title="View setup guides"- >- <Share2 className="mr-1.5 size-3.5" />- Connect to AI- </Button>- <Button- variant="outline"- disabled={busy}- onClick={() => {- setPending({ id: token.id, label: token.label });- setError("");- }}- className="min-h-9"- >- Disconnect- <span className="sr-only"> {token.label}</span>- </Button>- </>- )}+ <p className="mt-1 text-sm text-muted-foreground">{permissions[token.scope] ?? token.scope} · {token.status}</p></div>+ {token.status === "active" && (+ <div className="flex items-center gap-2">+ <Button variant="ghost" size="sm" onClick={() => openConnect(token.label)} className="min-h-9" title="View setup guides">+ <Share2 className="mr-1.5 size-3.5" />+ Connect to AI+ </Button>+ <Button+ variant="outline"+ disabled={busy}+ onClick={() => { setPending({ id: token.id, label: token.label }); setError(""); }}+ className="min-h-9"+ >+ Disconnect<span className="sr-only"> {token.label}</span>+ </Button>+ </div>+ )}</div><p className="text-sm leading-relaxed text-muted-foreground">- Last used {formatTime(token.lastUsedAt)}- <br />- Expires {formatTime(token.expiresAt)}+ Last used {formatTime(token.lastUsedAt)}<br />Expires {formatTime(token.expiresAt)}</p><details>- <summary className="cursor-pointer py-2 text-sm text-muted-foreground">- Client details- </summary>+ <summary className="cursor-pointer py-2 text-sm text-muted-foreground">Client details</summary><p className="break-all font-mono text-xs">{token.clientId}</p></details></SettingsBlock>@@ -356,12 +162,7 @@ export function McpTokenSection({<div className="flex flex-wrap gap-2">{tokens.length > active.length && (- <Button- variant="ghost"- aria-pressed={showInactive}- onClick={() => setShowInactive((value) => !value)}- className="min-h-11"- >+ <Button variant="ghost" aria-pressed={showInactive} onClick={() => setShowInactive((value) => !value)} className="min-h-11">{showInactive ? "Hide" : "Show"} expired & disconnected</Button>)}@@ -369,12 +170,7 @@ export function McpTokenSection({<Buttonvariant="ghost"disabled={busy}- onClick={() =>- setPending({- id: "all",- label: `all ${active.length} active connections`,- })- }+ onClick={() => setPending({ id: "all", label: `all ${active.length} active connections` })}className="min-h-11 text-destructive">Disconnect all@@ -382,7 +178,17 @@ export function McpTokenSection({)}</div>- {/* Connect to AI Modal */}+ <McpPatDialog+ open={patDialogOpen}+ maxScope={maxScope}+ onOpenChange={setPatDialogOpen}+ onMinted={(token, label) => {+ onChanged();+ setActivePatToken(token);+ setActivePatLabel(label);+ setConnectModalOpen(true);+ }}+ /><McpConnectModalopen={connectModalOpen}onOpenChange={setConnectModalOpen}diff --git a/lib/mcp/store-state.ts b/lib/mcp/store-state.tsnew file mode 100644index 00000000..bdd835a0--- /dev/null+++ b/lib/mcp/store-state.ts@@ -0,0 +1,78 @@+import { expandOwnerStorePath } from "@/lib/owner-store-path.js";+import { withSecurityStoreLock } from "@/lib/security-store-lock";+import { promises as fs } from "node:fs";+import os from "node:os";+import path from "node:path";+import type { McpStore } from "./store-types";++const STORE_PATH = expandOwnerStorePath(process.env.OS_MCP_STORE ?? path.join(os.homedir(), ".mso", "mcp.json"));+const MAX_CLIENTS = 64;+const empty = (): McpStore => ({ clients: {}, codes: {}, tokens: {}, refreshTokens: {} });++export async function readMcpStore(): Promise<McpStore> {+ let raw: string;+ try {+ raw = await fs.readFile(STORE_PATH, "utf8");+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return empty();+ throw error;+ }+ const parsed = JSON.parse(raw) as Partial<McpStore>;+ return {+ clients: parsed.clients ?? {},+ codes: parsed.codes ?? {},+ tokens: parsed.tokens ?? {},+ refreshTokens: parsed.refreshTokens ?? {},+ };+}++async function writeMcpStore(store: McpStore): Promise<void> {+ await fs.mkdir(path.dirname(STORE_PATH), { recursive: true, mode: 0o700 });+ const tmp = `${STORE_PATH}.${process.pid}.tmp`;+ await fs.writeFile(tmp, JSON.stringify(store, null, 2), { encoding: "utf8", mode: 0o600 });+ await fs.rename(tmp, STORE_PATH);+}++let mutationChain: Promise<unknown> = Promise.resolve();++export function mutateMcpStore<T>(fn: () => Promise<T>): Promise<T> {+ const locked = () => withSecurityStoreLock(STORE_PATH, fn);+ const run = mutationChain.then(locked, locked);+ mutationChain = run.then(() => undefined, () => undefined);+ return run;+}++export function sweepMcpStore(store: McpStore): McpStore {+ const now = Date.now();+ for (const [key, value] of Object.entries(store.codes)) {+ if (value.expiresAt < now) delete store.codes[key];+ }+ for (const [key, value] of Object.entries(store.refreshTokens)) {+ if (value.expiresAt < now || value.revokedAt) delete store.refreshTokens[key];+ }+ return store;+}++function referencedClientIds(store: McpStore): Set<string> {+ const now = Date.now();+ return new Set([+ ...Object.values(store.codes).filter((row) => row.expiresAt >= now).map((row) => row.clientId),+ ...Object.values(store.tokens).filter((row) => !row.revokedAt && (row.expiresAt === 0 || row.expiresAt >= now)).map((row) => row.clientId),+ ...Object.values(store.refreshTokens).filter((row) => !row.revokedAt && (row.expiresAt === 0 || row.expiresAt >= now)).map((row) => row.clientId),+ ].filter(Boolean));+}++export function pruneUnreferencedClients(store: McpStore): void {+ const ids = Object.keys(store.clients);+ if (ids.length < MAX_CLIENTS) return;+ const referenced = referencedClientIds(store);+ const removable = ids+ .filter((id) => !referenced.has(id))+ .sort((a, b) => store.clients[a].createdAt - store.clients[b].createdAt);+ const removeCount = Math.min(removable.length, ids.length - MAX_CLIENTS + 1);+ for (const id of removable.slice(0, removeCount)) delete store.clients[id];+}++export async function commitMcpStore(store: McpStore): Promise<void> {+ await writeMcpStore(store);+}diff --git a/lib/mcp/store-token-admin.ts b/lib/mcp/store-token-admin.tsnew file mode 100644index 00000000..c58bd239--- /dev/null+++ b/lib/mcp/store-token-admin.ts@@ -0,0 +1,80 @@+import { randomBytes, randomUUID } from "node:crypto";+import { sha256hex } from "./pkce";+import type { Scope } from "./scope";+import { commitMcpStore as write, mutateMcpStore as mutate, readMcpStore as read, sweepMcpStore as sweep } from "./store-state";+import type { McpToken, TokenView } from "./store-types";++export async function listTokens(): Promise<TokenView[]> {+ const store = await read();+ const now = Date.now();+ return Object.entries(store.tokens)+ .map(([hash, token]) => ({+ ...token,+ id: hash.slice(0, 16),+ status: token.revokedAt+ ? ("revoked" as const)+ : token.expiresAt > 0 && token.expiresAt < now+ ? ("expired" as const)+ : ("active" as const),+ }))+ .sort((a, b) => b.createdAt - a.createdAt);+}++export function revokeToken(id: string): Promise<boolean> {+ return mutate(async () => {+ const store = await read();+ const hit = Object.keys(store.tokens).find((hash) => hash.startsWith(id));+ if (!hit || store.tokens[hit].revokedAt) return false;+ const now = Date.now();+ const grantId = store.tokens[hit].grantId;+ for (const token of Object.values(store.tokens)) {+ if (token === store.tokens[hit] || (grantId && token.grantId === grantId)) token.revokedAt = now;+ }+ if (grantId) {+ for (const refresh of Object.values(store.refreshTokens)) {+ if (refresh.grantId === grantId) refresh.revokedAt = now;+ }+ }+ await write(store);+ return true;+ });+}++export function revokeAllTokens(): Promise<number> {+ return mutate(async () => {+ const store = await read();+ let count = 0;+ const now = Date.now();+ for (const token of Object.values(store.tokens)) {+ if (!token.revokedAt) {+ token.revokedAt = now;+ count += 1;+ }+ }+ for (const token of Object.values(store.refreshTokens)) {+ if (!token.revokedAt) token.revokedAt = now;+ }+ if (count || Object.keys(store.refreshTokens).length) await write(store);+ return count;+ });+}++export function mintPatToken(input: {+ label: string;+ scope: Scope;+ ttlDays?: number | null;+}): Promise<{ rawToken: string; tokenView: TokenView }> {+ return mutate(async () => {+ const store = sweep(await read());+ const rawToken = "mso_pat_" + randomUUID().replaceAll("-", "") + randomBytes(16).toString("hex");+ const now = Date.now();+ const ttlDays = typeof input.ttlDays === "number" && input.ttlDays > 0 ? input.ttlDays : 0;+ const expiresAt = ttlDays > 0 ? now + ttlDays * 24 * 60 * 60 * 1000 : 0;+ const label = input.label.trim().slice(0, 80) || "Personal Access Token";+ const tokenRec: McpToken = { label, clientId: "manual:pat", scope: input.scope, createdAt: now, expiresAt };+ const hash = sha256hex(rawToken);+ store.tokens[hash] = tokenRec;+ await write(store);+ return { rawToken, tokenView: { ...tokenRec, id: hash.slice(0, 16), status: "active" as const } };+ });+}diff --git a/lib/mcp/store-types.ts b/lib/mcp/store-types.tsnew file mode 100644index 00000000..f26f0469--- /dev/null+++ b/lib/mcp/store-types.ts@@ -0,0 +1,59 @@+import type { Scope } from "./scope";+import type { McpToolProfile } from "./tool-contract";++export interface McpClient {+ name: string;+ redirectUris: string[];+ profile?: McpToolProfile;+ createdAt: number;+}++export interface McpCode {+ clientId: string;+ redirectUri: string;+ codeChallenge: string;+ scope: Scope;+ resource?: string;+ profile?: McpToolProfile;+ offlineAccess?: boolean;+ expiresAt: number;+}++export interface McpToken {+ label: string;+ clientId: string;+ scope: Scope;+ resource?: string;+ profile?: McpToolProfile;+ allowedTools?: string[];+ toolArgumentConstraints?: Record<string, Record<string, string[]>>;+ grantId?: string;+ createdAt: number;+ expiresAt: number;+ lastUsedAt?: number;+ revokedAt?: number;+}++export interface McpRefreshToken {+ grantId: string;+ clientId: string;+ scope: Scope;+ resource: string;+ profile?: McpToolProfile;+ offlineAccess?: boolean;+ createdAt: number;+ expiresAt: number;+ revokedAt?: number;+}++export interface McpStore {+ clients: Record<string, McpClient>;+ codes: Record<string, McpCode>;+ tokens: Record<string, McpToken>;+ refreshTokens: Record<string, McpRefreshToken>;+}++export interface TokenView extends McpToken {+ id: string;+ status: "active" | "revoked" | "expired";+}diff --git a/lib/mcp/store.ts b/lib/mcp/store.tsindex d5d09a26..52d53a32 100644--- a/lib/mcp/store.ts+++ b/lib/mcp/store.ts@@ -1,155 +1,36 @@-import { expandOwnerStorePath } from "@/lib/owner-store-path.js";-import { randomUUID, randomBytes } from "node:crypto";-import { promises as fs } from "node:fs";-import os from "node:os";-import path from "node:path";+import { randomUUID } from "node:crypto";import { sha256hex } from "./pkce";import type { Scope } from "./scope";import type { McpToolProfile } from "./tool-contract";import { detectMcpToolProfile } from "./client-profile";-import { withSecurityStoreLock } from "@/lib/security-store-lock";--// 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[];- profile?: McpToolProfile;- createdAt: number;-}--export interface McpCode {- clientId: string;- redirectUri: string;- codeChallenge: string;- scope: Scope;- resource?: string;- profile?: McpToolProfile;- offlineAccess?: boolean;- expiresAt: number;-}--export interface McpToken {- label: string;- clientId: string;- scope: Scope;- resource?: string;- profile?: McpToolProfile;- /** Optional exact tool allowlist for operator-issued machine tokens. OAuth tokens omit it. */- allowedTools?: string[];- /** Optional exact string argument constraints keyed by MCP tool then argument. */- toolArgumentConstraints?: Record<string, Record<string, string[]>>;- grantId?: string;- createdAt: number;- expiresAt: number;- lastUsedAt?: number;- revokedAt?: number;-}--export interface McpRefreshToken {- grantId: string; clientId: string; scope: Scope; resource: string; profile?: McpToolProfile; offlineAccess?: boolean; createdAt: number; expiresAt: number; revokedAt?: number;-}--interface Store {- clients: Record<string, McpClient>;- codes: Record<string, McpCode>;- tokens: Record<string, McpToken>;- refreshTokens: Record<string, McpRefreshToken>;-}--const STORE_PATH = expandOwnerStorePath(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; // legacy/manual bearer lifetime-export const OAUTH_ACCESS_TOKEN_TTL_MS = 60 * 60 * 1000; // short-lived; refresh token rotates it+import {+ commitMcpStore as write,+ mutateMcpStore as mutate,+ pruneUnreferencedClients,+ readMcpStore as read,+ sweepMcpStore as sweep,+} from "./store-state";+import type { McpClient, McpCode, McpRefreshToken, McpToken } from "./store-types";++export type { McpClient, McpCode, McpRefreshToken, McpToken, TokenView } from "./store-types";++export const CODE_TTL_MS = 60_000;+export const TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000;+export const OAUTH_ACCESS_TOKEN_TTL_MS = 60 * 60 * 1000;export const REFRESH_TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000;-const MAX_CLIENTS = 64;--const empty = (): Store => ({ clients: {}, codes: {}, tokens: {}, refreshTokens: {} });--// 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 ?? {}, refreshTokens: (p as Partial<Store>).refreshTokens ?? {} };-}--async function write(store: Store): Promise<void> {- await fs.mkdir(path.dirname(STORE_PATH), { recursive: true, mode: 0o700 });- // Per-process temp name prevents an operator-side helper / another server process- // from clobbering the exact temp path while this process is committing a write.- const tmp = `${STORE_PATH}.${process.pid}.tmp`;- await fs.writeFile(tmp, JSON.stringify(store, null, 2), { encoding: "utf8", mode: 0o600 });- await fs.rename(tmp, STORE_PATH);-}--// Every credential mutation is a read-modify-write. Atomic rename only makes ONE-// write indivisible; without serialising the whole transaction, concurrent requests-// can both read the same old state and then overwrite each other's decisions. That-// is security-significant here: a token touch must never resurrect a token that a-// concurrent revoke just killed, and an OAuth code must be consumable exactly once.-let mutationChain: Promise<unknown> = Promise.resolve();-function mutate<T>(fn: () => Promise<T>): Promise<T> {- const locked = () => withSecurityStoreLock(STORE_PATH, fn);- const run = mutationChain.then(locked, locked);- mutationChain = run.then(() => undefined, () => undefined);- return run;-}--/** 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];- for (const [k, v] of Object.entries(store.refreshTokens)) if (v.expiresAt < now || v.revokedAt) delete store.refreshTokens[k];- return store;-}--function referencedClientIds(store: Store): Set<string> {- const now = Date.now();- return new Set([- ...Object.values(store.codes).filter((row) => row.expiresAt >= now).map((row) => row.clientId),- ...Object.values(store.tokens).filter((row) => !row.revokedAt && (row.expiresAt === 0 || row.expiresAt >= now)).map((row) => row.clientId),- ...Object.values(store.refreshTokens).filter((row) => !row.revokedAt && (row.expiresAt === 0 || row.expiresAt >= now)).map((row) => row.clientId),- ].filter(Boolean));-}--function pruneUnreferencedClients(store: Store): void {- const ids = Object.keys(store.clients);- if (ids.length < MAX_CLIENTS) return;- const referenced = referencedClientIds(store);- const removable = ids- .filter((id) => !referenced.has(id))- .sort((a, b) => store.clients[a].createdAt - store.clients[b].createdAt);- const removeCount = Math.min(removable.length, ids.length - MAX_CLIENTS + 1);- for (const id of removable.slice(0, removeCount)) delete store.clients[id];-}export function registerClient(name: string, redirectUris: string[]): Promise<string> {return mutate(async () => {const store = sweep(await read());- // RFC 7591 registration represents a client registration instance. Redirect- // URIs are metadata, not client identity: two ChatGPT apps legitimately share- // the same callback host and must not collapse onto one historical client_id.pruneUnreferencedClients(store);const clientId = "mcpc_" + randomUUID().replaceAll("-", "").slice(0, 24);const cleanName = name.slice(0, 80) || "MCP Client";- store.clients[clientId] = { name: cleanName, redirectUris, profile: detectMcpToolProfile({ clientId, name: cleanName, redirectUris }), createdAt: Date.now() };+ store.clients[clientId] = {+ name: cleanName,+ redirectUris,+ profile: detectMcpToolProfile({ clientId, name: cleanName, redirectUris }),+ createdAt: Date.now(),+ };await write(store);return clientId;});@@ -167,11 +48,7 @@ export function storeCode(code: string, rec: McpCode): Promise<void> {});}-/**- * 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.- */+/** Single-use exchange: delete the authorization code before minting anything. */export function consumeCode(code: string): Promise<McpCode | null> {return mutate(async () => {const store = sweep(await read());@@ -193,33 +70,79 @@ export function storeToken(token: string, rec: Omit<McpToken, "createdAt" | "exp});}-export function storeOAuthGrant(input: {- accessToken: string; refreshToken: string; label: string; clientId: string; scope: Scope; resource: string; profile?: McpToolProfile; offlineAccess?: boolean; grantId: string;+ accessToken: string;+ refreshToken: string;+ label: string;+ clientId: string;+ scope: Scope;+ resource: string;+ profile?: McpToolProfile;+ offlineAccess?: boolean;+ grantId: string;}): Promise<void> {return mutate(async () => {- const store = sweep(await read()); const now = Date.now();- store.tokens[sha256hex(input.accessToken)] = { label: input.label, clientId: input.clientId, scope: input.scope, resource: input.resource, profile: input.profile, grantId: input.grantId, createdAt: now, expiresAt: now + OAUTH_ACCESS_TOKEN_TTL_MS };- store.refreshTokens[sha256hex(input.refreshToken)] = { grantId: input.grantId, clientId: input.clientId, scope: input.scope, resource: input.resource, profile: input.profile, offlineAccess: input.offlineAccess, createdAt: now, expiresAt: now + REFRESH_TOKEN_TTL_MS };+ const store = sweep(await read());+ const now = Date.now();+ store.tokens[sha256hex(input.accessToken)] = {+ label: input.label,+ clientId: input.clientId,+ scope: input.scope,+ resource: input.resource,+ profile: input.profile,+ grantId: input.grantId,+ createdAt: now,+ expiresAt: now + OAUTH_ACCESS_TOKEN_TTL_MS,+ };+ store.refreshTokens[sha256hex(input.refreshToken)] = {+ grantId: input.grantId,+ clientId: input.clientId,+ scope: input.scope,+ resource: input.resource,+ profile: input.profile,+ offlineAccess: input.offlineAccess,+ createdAt: now,+ expiresAt: now + REFRESH_TOKEN_TTL_MS,+ };await write(store);});}-export function rotateOAuthGrant(input: { oldRefreshToken: string; accessToken: string; refreshToken: string; label: string; clientId: string; resource: string }): Promise<McpRefreshToken | null> {+export function rotateOAuthGrant(input: {+ oldRefreshToken: string;+ accessToken: string;+ refreshToken: string;+ label: string;+ clientId: string;+ resource: string;+}): Promise<McpRefreshToken | null> {return mutate(async () => {- const store = sweep(await read()), oldHash = sha256hex(input.oldRefreshToken), rec = store.refreshTokens[oldHash];+ const store = sweep(await read());+ const oldHash = sha256hex(input.oldRefreshToken);+ const rec = store.refreshTokens[oldHash];if (!rec || rec.revokedAt || rec.expiresAt < Date.now() || rec.clientId !== input.clientId || rec.resource !== input.resource) return null;delete store.refreshTokens[oldHash];const now = Date.now();- store.tokens[sha256hex(input.accessToken)] = { label: input.label, clientId: rec.clientId, scope: rec.scope, resource: rec.resource, profile: rec.profile, grantId: rec.grantId, createdAt: now, expiresAt: now + OAUTH_ACCESS_TOKEN_TTL_MS };- store.refreshTokens[sha256hex(input.refreshToken)] = { ...rec, createdAt: now, expiresAt: now + REFRESH_TOKEN_TTL_MS };- await write(store); return rec;+ store.tokens[sha256hex(input.accessToken)] = {+ label: input.label,+ clientId: rec.clientId,+ scope: rec.scope,+ resource: rec.resource,+ profile: rec.profile,+ grantId: rec.grantId,+ createdAt: now,+ expiresAt: now + OAUTH_ACCESS_TOKEN_TTL_MS,+ };+ store.refreshTokens[sha256hex(input.refreshToken)] = {+ ...rec,+ createdAt: now,+ expiresAt: now + REFRESH_TOKEN_TTL_MS,+ };+ await write(store);+ return rec;});}-/** 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);@@ -239,81 +162,4 @@ export function touchToken(hash: string): Promise<void> {});}-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 > 0 && t.expiresAt < now) ? ("expired" as const) : ("active" as const),- }))- .sort((a, b) => b.createdAt - a.createdAt);-}--export function revokeToken(id: string): Promise<boolean> {- return mutate(async () => {- const store = await read();- const hit = Object.keys(store.tokens).find((h) => h.startsWith(id));- if (!hit || store.tokens[hit].revokedAt) return false;- const now = Date.now(), grantId = store.tokens[hit].grantId;- for (const token of Object.values(store.tokens)) if (token === store.tokens[hit] || (grantId && token.grantId === grantId)) token.revokedAt = now;- if (grantId) for (const refresh of Object.values(store.refreshTokens)) if (refresh.grantId === grantId) refresh.revokedAt = now;- await write(store); return true;- });-}--/** Panic button — kills every live bearer at once. */-export function revokeAllTokens(): Promise<number> {- return mutate(async () => {- const store = await read();- let n = 0;- const now = Date.now();- for (const t of Object.values(store.tokens)) if (!t.revokedAt) { t.revokedAt = now; n++; }- for (const t of Object.values(store.refreshTokens)) if (!t.revokedAt) t.revokedAt = now;- if (n || Object.keys(store.refreshTokens).length) await write(store);- return n;- });-}--export function mintPatToken(input: {- label: string;- scope: Scope;- ttlDays?: number | null;-}): Promise<{ rawToken: string; tokenView: TokenView }> {- return mutate(async () => {- const store = sweep(await read());- const rawToken = "mso_pat_" + randomUUID().replaceAll("-", "") + randomBytes(16).toString("hex");- const now = Date.now();- const ttlDays = typeof input.ttlDays === "number" && input.ttlDays > 0 ? input.ttlDays : 0;- const expiresAt = ttlDays > 0 ? now + ttlDays * 24 * 60 * 60 * 1000 : 0;- const label = input.label.trim().slice(0, 80) || "Personal Access Token";- const tokenRec: McpToken = {- label,- clientId: "manual:pat",- scope: input.scope,- createdAt: now,- expiresAt,- };- const hash = sha256hex(rawToken);- store.tokens[hash] = tokenRec;- await write(store);- return {- rawToken,- tokenView: {- ...tokenRec,- id: hash.slice(0, 16),- status: "active" as const,- },- };- });-}+export { listTokens, mintPatToken, revokeAllTokens, revokeToken } from "./store-token-admin";diff --git a/scripts/cli/commands-admin.sh b/scripts/cli/commands-admin.shindex b6341fad..62181fe9 100755--- a/scripts/cli/commands-admin.sh+++ b/scripts/cli/commands-admin.sh@@ -38,6 +38,11 @@ case "$cmd" inmcp)case "${1:-list}" inlist) jget "/api/mcp/tokens" ;;+ pat) label="${2-}"; scope="${3:-read}"; ttl_days="${4:-0}"+ [ -n "$label" ] || die "usage: mso mcp pat <label> [read|write|exec] [ttlDays]"+ case "$scope" in read|write|exec) ;; *) die "scope must be read, write, or exec" ;; esac+ [[ "$ttl_days" =~ ^[0-9]+$ ]] || die "ttlDays must be a non-negative integer"+ jpost "/api/mcp/tokens" "$(jq -cn --arg label "$label" --arg scope "$scope" --argjson ttlDays "$ttl_days" '{label:$label,scope:$scope,ttlDays:$ttlDays}')" ;;project) jpost "/api/v1/project-mcp" "${2:?project MCP JSON required}" ;;activity) jget "/api/mcp/activity?limit=${2:-80}" ;;service-token) bun "$ROOT/scripts/mcp-service-token.ts" "${@:2}" ;;diff --git a/scripts/cli/commands.sh b/scripts/cli/commands.shindex e16f33df..1d313e53 100755--- a/scripts/cli/commands.sh+++ b/scripts/cli/commands.sh@@ -49,7 +49,7 @@ U_config="config show|set <json>|key <provider>|style <off|caveman|ponytail>|rmU_prefs="prefs show|set <json>"U_models="models [status|list|add|auth <provider>|rm <provider>|catalog [provider]|test]"U_skills="skills list|read <id>|search <query…>|available|info <id>|install <id…> [-y] [--force]|remove <id…> [-y]|store list|store install|remove <id> <revision>"-U_mcp="mcp project <JSON>|list|activity [n]|service-token --label <label> --client-id <id> --scope <read|write|exec> --tools <name,name> [--constraints-json <json>]|revoke <id>|revoke all"+U_mcp="mcp project <JSON>|list|pat <label> [read|write|exec] [ttlDays]|activity [n]|service-token --label <label> --client-id <id> --scope <read|write|exec> --tools <name,name> [--constraints-json <json>]|revoke <id>|revoke all"U_oauth="oauth <provider> start|poll OAuth currently: openai (ChatGPT Codex)"# Command families are sourced here so bin/mso remains only bootstrap + entrypoint.# shellcheck source=commands-host.sh