Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

feat(mcp): add personal access tokens and auto-session fallback

Abdurrahman Fakhrul7b1a0a8e3543
diff --git a/app/api/mcp/tokens/route.test.ts b/app/api/mcp/tokens/route.test.ts
index 9b1efc58..28c2d83c 100644
--- a/app/api/mcp/tokens/route.test.ts
+++ b/app/api/mcp/tokens/route.test.ts
@@ -4,11 +4,28 @@ const mocks = vi.hoisted(() => ({
verifyAuth: vi.fn(async () => true),
listTokens: vi.fn(async () => []),
publicOrigin: vi.fn(() => "https://mso.example.test"),
+ mintPatToken: vi.fn(async (input: { label: string; scope: string; ttlDays?: number | null }) => ({
+ rawToken: "mso_pat_test123",
+ tokenView: {
+ id: "test1234",
+ label: input.label,
+ clientId: "manual:pat",
+ scope: input.scope,
+ createdAt: Date.now(),
+ expiresAt: input.ttlDays ? Date.now() + input.ttlDays * 86_400_000 : 0,
+ status: "active" as const,
+ },
+ })),
}));
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/store", () => ({
+ listTokens: mocks.listTokens,
+ revokeToken: vi.fn(),
+ revokeAllTokens: vi.fn(),
+ mintPatToken: mocks.mintPatToken,
+}));
+vi.mock("@/lib/mcp/scope", () => ({ mcpEnabled: () => true, maxScope: () => "exec", parseScope: (s: string) => s, clampScope: (s: string) => s }));
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 }));
@@ -21,7 +38,7 @@ describe("Settings MCP state", () => {
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" });
+ await expect(response.json()).resolves.toMatchObject({ enabled: true, maxScope: "exec", origin: "https://mso.example.test" });
expect(mocks.publicOrigin).toHaveBeenCalledWith(request);
});
@@ -31,4 +48,43 @@ describe("Settings MCP state", () => {
const response = await GET(new Request("https://mso.example.test/api/mcp/tokens"));
expect(response.status).toBe(401);
});
+
+ it("mints Personal Access Tokens (PAT) via POST with owner auth", async () => {
+ const { POST } = await import("./route");
+ const request = new Request("https://mso.example.test/api/mcp/tokens", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ label: "Antigravity CLI", scope: "exec", ttlDays: 0 }),
+ });
+ const response = await POST(request);
+ expect(response.status).toBe(201);
+ const data = await response.json();
+ expect(data.ok).toBe(true);
+ expect(data.token).toBe("mso_pat_test123");
+ expect(data.tokenView.label).toBe("Antigravity CLI");
+ expect(data.tokenView.expiresAt).toBe(0);
+ expect(mocks.mintPatToken).toHaveBeenCalledWith({
+ label: "Antigravity CLI",
+ scope: "exec",
+ ttlDays: null,
+ });
+ });
+
+ it("rejects PAT generation without owner auth or with empty label", async () => {
+ mocks.verifyAuth.mockResolvedValueOnce(false);
+ const { POST } = await import("./route");
+ const unauthRes = await POST(new Request("https://mso.example.test/api/mcp/tokens", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ label: "Test" }),
+ }));
+ expect(unauthRes.status).toBe(401);
+
+ const emptyRes = await POST(new Request("https://mso.example.test/api/mcp/tokens", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ label: " " }),
+ }));
+ expect(emptyRes.status).toBe(400);
+ });
});
diff --git a/app/api/mcp/tokens/route.ts b/app/api/mcp/tokens/route.ts
index f732dda4..04e346ff 100644
--- a/app/api/mcp/tokens/route.ts
+++ b/app/api/mcp/tokens/route.ts
@@ -1,16 +1,14 @@
import { NextResponse } from "next/server";
import { verifyAuth } from "@/lib/agent/server";
-import { listTokens, revokeToken, revokeAllTokens } from "@/lib/mcp/store";
-import { mcpEnabled, maxScope } from "@/lib/mcp/scope";
+import { listTokens, revokeToken, revokeAllTokens, mintPatToken } from "@/lib/mcp/store";
+import { mcpEnabled, maxScope, parseScope, clampScope } 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
-// /mcp itself. There is no mint endpoint — tokens only ever come from the OAuth
-// consent flow, so a stolen session cannot silently create a standing bearer
-// without the owner seeing the consent screen.
+// /mcp itself.
export const dynamic = "force-dynamic";
export async function GET(req: Request) {
@@ -18,6 +16,37 @@ export async function GET(req: Request) {
return NextResponse.json({ enabled: mcpEnabled(), maxScope: maxScope(), origin: publicOrigin(req), toolset: toolsetInfo(TOOLS), tokens: await listTokens() });
}
+export async function POST(req: Request) {
+ if (!(await verifyAuth(req, "owner"))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });
+ if (!mcpEnabled()) return NextResponse.json({ error: "MCP is disabled on this server" }, { status: 403 });
+
+ let body: Record<string, unknown>;
+ try {
+ body = (await req.json()) as Record<string, unknown>;
+ } catch {
+ return NextResponse.json({ error: "invalid json body" }, { status: 400 });
+ }
+
+ const label = typeof body?.label === "string" ? body.label.trim() : "";
+ if (!label) return NextResponse.json({ error: "label is required" }, { status: 400 });
+ if (label.length > 80) return NextResponse.json({ error: "label must be 80 characters or fewer" }, { status: 400 });
+
+ const rawScope = typeof body?.scope === "string" ? body.scope : "read";
+ const scope = clampScope(parseScope(rawScope));
+
+ let ttlDays: number | null = null;
+ if (body?.ttlDays !== undefined && body?.ttlDays !== null) {
+ const num = Number(body.ttlDays);
+ if (isNaN(num) || (num !== 0 && num !== 7 && num !== 30 && num !== 90)) {
+ return NextResponse.json({ error: "ttlDays must be 0 (never expires), 7, 30, or 90" }, { status: 400 });
+ }
+ ttlDays = num === 0 ? null : num;
+ }
+
+ const result = await mintPatToken({ label, scope, ttlDays });
+ return NextResponse.json({ ok: true, token: result.rawToken, tokenView: result.tokenView }, { status: 201 });
+}
+
export async function DELETE(req: Request) {
if (!(await verifyAuth(req, "owner"))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });
const id = new URL(req.url).searchParams.get("id");
diff --git a/app/oauth/authorize/actions.ts b/app/oauth/authorize/actions.ts
index 1d5d8091..bd6e25b0 100644
--- a/app/oauth/authorize/actions.ts
+++ b/app/oauth/authorize/actions.ts
@@ -39,7 +39,11 @@ export async function approve(form: FormData): Promise<ApprovalResult> {
let expectedIssuer = "";
if (configured) { try { expectedIssuer = new URL(configured).origin; } catch {} }
if (!expectedIssuer) {
- const h = await headers(), proto = h.get("x-forwarded-proto")?.split(",")[0].trim() || "https", host = h.get("host") ?? h.get("x-forwarded-host") ?? "";
+ const h = await headers();
+ const forwardedHost = h.get("x-forwarded-host")?.split(",")[0].trim();
+ const host = forwardedHost || h.get("host")?.trim() || "";
+ const isLoopback = host.startsWith("localhost") || host.startsWith("127.") || host.startsWith("[::1]");
+ const proto = h.get("x-forwarded-proto")?.split(",")[0].trim() || (isLoopback ? "http" : "https");
try { expectedIssuer = new URL(`${proto}://${host}`).origin; } catch {}
}
if (!expectedIssuer || issuer !== expectedIssuer || resource !== `${expectedIssuer}/mcp`) return { ok: false, error: "OAuth resource/issuer mismatch." };
diff --git a/app/oauth/authorize/page.tsx b/app/oauth/authorize/page.tsx
index 0b2f986d..a7f9d7b9 100644
--- a/app/oauth/authorize/page.tsx
+++ b/app/oauth/authorize/page.tsx
@@ -32,8 +32,10 @@ export default async function AuthorizePage({
const clientId = one("client_id");
const h = await headers();
const configured = process.env.OS_PUBLIC_ORIGIN?.trim();
- const proto = h.get("x-forwarded-proto")?.split(",")[0].trim() || "https";
- const host = h.get("host") ?? h.get("x-forwarded-host") ?? "";
+ const forwardedHost = h.get("x-forwarded-host")?.split(",")[0].trim();
+ const host = forwardedHost || h.get("host")?.trim() || "";
+ const isLoopback = host.startsWith("localhost") || host.startsWith("127.") || host.startsWith("[::1]");
+ const proto = h.get("x-forwarded-proto")?.split(",")[0].trim() || (isLoopback ? "http" : "https");
const issuer = (() => { try { return configured ? new URL(configured).origin : new URL(`${proto}://${host}`).origin; } catch { return ""; } })();
const expectedResource = issuer ? `${issuer}/mcp` : "";
const resource = one("resource") || expectedResource;
diff --git a/frontend/slices/os-settings/components/mcp-client-core.ts b/frontend/slices/os-settings/components/mcp-client-core.ts
index 5c91bb6f..b87552eb 100644
--- a/frontend/slices/os-settings/components/mcp-client-core.ts
+++ b/frontend/slices/os-settings/components/mcp-client-core.ts
@@ -4,6 +4,7 @@ export type McpClientId =
| "claude-code"
| "cursor"
| "gemini"
+ | "antigravity"
| "vscode"
| "other";
@@ -41,6 +42,7 @@ export const MCP_CLIENTS: Array<{
{ 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: "antigravity", label: "Antigravity", description: "Google Antigravity MCP", 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" },
];
@@ -89,3 +91,16 @@ export function codexMcpConfig(rawOrigin: string): string {
const { mcp } = mcpEndpoints(rawOrigin);
return `[mcp_servers.mso]\nurl = "${mcp}"`;
}
+
+export function antigravityMcpConfig(rawOrigin: string, token?: string): string {
+ const { mcp } = mcpEndpoints(rawOrigin);
+ return JSON.stringify({
+ mso: {
+ url: mcp,
+ headers: {
+ Authorization: `Bearer ${token || "<YOUR_PAT_TOKEN>"}`,
+ },
+ },
+ }, null, 2);
+}
+
diff --git a/frontend/slices/os-settings/components/mcp-client-steps.ts b/frontend/slices/os-settings/components/mcp-client-steps.ts
index 3540780e..4c82c42f 100644
--- a/frontend/slices/os-settings/components/mcp-client-steps.ts
+++ b/frontend/slices/os-settings/components/mcp-client-steps.ts
@@ -1,4 +1,5 @@
import {
+ antigravityMcpConfig,
codexMcpConfig,
cursorMcpConfig,
mcpEndpoints,
@@ -97,12 +98,13 @@ export function mcpClientSteps(client: McpClientId, rawOrigin: string): McpGuide
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}` },
+ body: "Gemini CLI stores MCP servers in settings.json. You can connect using OAuth or a Personal Access Token (PAT).",
+ copy: { label: "Gemini CLI (OAuth)", 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: "Personal Access Token alternative",
+ body: "For long-lived persistent access without OAuth re-prompting, pass your PAT token via the Authorization header.",
+ copy: { label: "Gemini CLI (PAT)", value: `gemini mcp add --transport http --scope user -H "Authorization: Bearer <TOKEN>" mso ${endpoints.mcp}` },
},
{
title: "Verify",
@@ -112,6 +114,24 @@ export function mcpClientSteps(client: McpClientId, rawOrigin: string): McpGuide
];
}
+ if (client === "antigravity") {
+ return [
+ {
+ title: "Add to Antigravity MCP config",
+ body: "Google Antigravity reads MCP servers from ~/.gemini/config/mcp_config.json. Add MSO with your Personal Access Token (PAT).",
+ copy: { label: "Antigravity config", value: antigravityMcpConfig(endpoints.origin), multiline: true },
+ },
+ {
+ title: "Zero-Config Auto-Session",
+ body: "Antigravity automatically connects to MSO's tools. MSO server automatically provisions and tracks durable execution sessions without manual session negotiation.",
+ },
+ {
+ title: "Verify tools",
+ body: "In Antigravity chat, your agent will immediately see all 116+ host tools (vps_status, sys_stats, exec_run, etc.).",
+ },
+ ];
+ }
+
if (client === "vscode") {
return [
{
diff --git a/frontend/slices/os-settings/components/mcp-connect-modal.tsx b/frontend/slices/os-settings/components/mcp-connect-modal.tsx
new file mode 100644
index 00000000..3a559263
--- /dev/null
+++ b/frontend/slices/os-settings/components/mcp-connect-modal.tsx
@@ -0,0 +1,204 @@
+"use client";
+
+import { AlertTriangle, Key } from "lucide-react";
+import { useState } from "react";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { McpCopyField } from "./mcp-copy-field";
+
+interface McpConnectModalProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ origin: string;
+ token?: string;
+ label?: string;
+}
+
+export function McpConnectModal({
+ open,
+ onOpenChange,
+ origin,
+ token,
+ label,
+}: McpConnectModalProps) {
+ const [activeTab, setActiveTab] = useState<"antigravity" | "gemini" | "cursor" | "claude">("antigravity");
+ const cleanOrigin = origin.replace(/\/+$/, "");
+ const mcpUrl = `${cleanOrigin}/mcp`;
+ const tokenValue = token || "<YOUR_TOKEN>";
+
+ const antigravitySnippet = JSON.stringify(
+ {
+ mso: {
+ url: mcpUrl,
+ headers: {
+ Authorization: `Bearer ${tokenValue}`,
+ },
+ },
+ },
+ null,
+ 2
+ );
+
+ const cursorSnippet = JSON.stringify(
+ {
+ mcpServers: {
+ mso: {
+ url: mcpUrl,
+ headers: {
+ Authorization: `Bearer ${tokenValue}`,
+ },
+ },
+ },
+ },
+ null,
+ 2
+ );
+
+ const claudeDesktopSnippet = JSON.stringify(
+ {
+ mcpServers: {
+ mso: {
+ url: mcpUrl,
+ headers: {
+ Authorization: `Bearer ${tokenValue}`,
+ },
+ },
+ },
+ },
+ null,
+ 2
+ );
+
+ 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">
+ <Key className="size-5 text-primary" />
+ Connect MCP to Your AI Agent
+ </DialogTitle>
+ <DialogDescription>
+ {label ? `Credentials for “${label}”. ` : ""}
+ Configure your AI assistant or IDE to control MSO using Streamable HTTP.
+ </DialogDescription>
+ </DialogHeader>
+
+ {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">
+ <div className="flex items-center gap-2 font-medium">
+ <AlertTriangle className="size-4 shrink-0" />
+ <span>Simpan token ini sekarang</span>
+ </div>
+ <p className="text-xs leading-relaxed text-muted-foreground">
+ Token rahasia ini hanya ditampilkan sekali saat pembuatan. Jika hilang, Anda harus membuat token baru.
+ </p>
+ <div className="mt-2">
+ <McpCopyField label="Raw Token" value={token} />
+ </div>
+ </div>
+ )}
+
+ <div className="mt-2 space-y-4">
+ <Tabs>
+ <TabsList className="grid w-full grid-cols-4">
+ <TabsTrigger
+ active={activeTab === "antigravity"}
+ onClick={() => setActiveTab("antigravity")}
+ >
+ Antigravity
+ </TabsTrigger>
+ <TabsTrigger
+ active={activeTab === "gemini"}
+ onClick={() => setActiveTab("gemini")}
+ >
+ Gemini CLI
+ </TabsTrigger>
+ <TabsTrigger
+ active={activeTab === "cursor"}
+ onClick={() => setActiveTab("cursor")}
+ >
+ Cursor
+ </TabsTrigger>
+ <TabsTrigger
+ active={activeTab === "claude"}
+ onClick={() => setActiveTab("claude")}
+ >
+ Claude
+ </TabsTrigger>
+ </TabsList>
+ </Tabs>
+
+ {activeTab === "antigravity" && (
+ <div className="space-y-3">
+ <p className="text-xs text-muted-foreground">
+ Tambahkan ke file konfigurasi Antigravity di{" "}
+ <code className="rounded bg-muted px-1 py-0.5 font-mono text-[11px]">
+ ~/.gemini/config/mcp_config.json
+ </code>{" "}
+ di bawah key <code className="font-mono text-[11px]">mcpServers</code>:
+ </p>
+ <McpCopyField
+ label="Antigravity mcp_config.json"
+ value={antigravitySnippet}
+ multiline
+ />
+ </div>
+ )}
+
+ {activeTab === "gemini" && (
+ <div className="space-y-3">
+ <p className="text-xs text-muted-foreground">
+ Jalankan perintah ini di terminal Anda untuk mendaftarkan MCP MSO ke Gemini CLI:
+ </p>
+ <McpCopyField
+ label="Gemini CLI Command"
+ value={geminiCliCommand}
+ multiline
+ />
+ </div>
+ )}
+
+ {activeTab === "cursor" && (
+ <div className="space-y-3">
+ <p className="text-xs text-muted-foreground">
+ Buka Cursor Settings → MCP atau edit langsung file{" "}
+ <code className="rounded bg-muted px-1 py-0.5 font-mono text-[11px]">
+ ~/.cursor/mcp.json
+ </code>:
+ </p>
+ <McpCopyField
+ label="Cursor mcp.json"
+ value={cursorSnippet}
+ multiline
+ />
+ </div>
+ )}
+
+ {activeTab === "claude" && (
+ <div className="space-y-3">
+ <p className="text-xs text-muted-foreground">
+ Tambahkan ke file{" "}
+ <code className="rounded bg-muted px-1 py-0.5 font-mono text-[11px]">
+ claude_desktop_config.json
+ </code>:
+ </p>
+ <McpCopyField
+ label="Claude Desktop Config"
+ value={claudeDesktopSnippet}
+ multiline
+ />
+ </div>
+ )}
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/frontend/slices/os-settings/components/mcp-section.tsx b/frontend/slices/os-settings/components/mcp-section.tsx
index 3c22d9b6..4c9e9e67 100644
--- a/frontend/slices/os-settings/components/mcp-section.tsx
+++ b/frontend/slices/os-settings/components/mcp-section.tsx
@@ -70,7 +70,7 @@ function OwnerMcpSection() {
{direction === "inbound" && <McpNavigation active={page} onSelect={navigate} activeCount={state.tokens.filter(token => token.status === "active").length} direction={direction} />}
{page === "connect" && <McpSetupGuide origin={state.origin} maxScope={state.maxScope} />}
{page === "connection" && <McpConnectionSection origin={state.origin} />}
- {page === "access" && <McpTokenSection tokens={state.tokens} onChanged={reload} onConnect={() => navigate("connect")} />}
+ {page === "access" && <McpTokenSection tokens={state.tokens} origin={state.origin} maxScope={state.maxScope} onChanged={reload} onConnect={() => navigate("connect")} />}
{page === "activity" && <McpActivity />}
{page === "tools" && <McpToolsetCard info={state.toolset} />}
{(page === "registry" || (direction === "outbound" && page === "overview")) && <McpPluginRegistry />}
diff --git a/frontend/slices/os-settings/components/mcp-token-section.tsx b/frontend/slices/os-settings/components/mcp-token-section.tsx
index 20ec4353..0dca6482 100644
--- a/frontend/slices/os-settings/components/mcp-token-section.tsx
+++ b/frontend/slices/os-settings/components/mcp-token-section.tsx
@@ -1,57 +1,395 @@
"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 } from "lucide-react";
+import { KeyRound, Plus, Share2 } from "lucide-react";
import { useState } from "react";
+import { McpConnectModal } from "./mcp-connect-modal";
export type McpTokenRow = {
- id: string; label: string; clientId: string; scope: string; createdAt: number;
- expiresAt: number; lastUsedAt?: number; status: "active" | "revoked" | "expired";
+ id: string;
+ label: string;
+ clientId: string;
+ scope: string;
+ createdAt: number;
+ expiresAt: number;
+ lastUsedAt?: number;
+ status: "active" | "revoked" | "expired";
};
-const formatTime = (time?: number) => time ? new Date(time).toLocaleString() : "Never";
-const permissions: Record<string, string> = { read: "Read data", write: "Read and change data", exec: "Run host commands" };
-export function McpTokenSection({ tokens, onChanged, onConnect }: { tokens: McpTokenRow[]; onChanged: () => void; onConnect: () => void }) {
+const formatTime = (time?: number) => {
+ if (time === 0) return "Never (Permanent)";
+ return time ? new Date(time).toLocaleString() : "Never";
+};
+
+const permissions: Record<string, string> = {
+ read: "Read data",
+ write: "Read and change data",
+ exec: "Run host commands",
+};
+
+export function McpTokenSection({
+ tokens,
+ origin = "",
+ maxScope = "exec",
+ onChanged,
+ onConnect,
+}: {
+ tokens: McpTokenRow[];
+ origin?: string;
+ maxScope?: string;
+ onChanged: () => void;
+ onConnect: () => void;
+}) {
const [pending, setPending] = useState<{ id: string; label: string } | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const [showInactive, setShowInactive] = useState(false);
- const active = tokens.filter(token => token.status === "active");
+
+ // PAT generation dialog state
+ const [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 state
+ const [connectModalOpen, setConnectModalOpen] = useState(false);
+ const [activePatToken, setActivePatToken] = useState<string | undefined>(undefined);
+ const [activePatLabel, setActivePatLabel] = useState<string | undefined>(undefined);
+
+ const effectiveOrigin = origin || (typeof window !== "undefined" ? window.location.origin : "");
+
+ const active = tokens.filter((token) => token.status === "active");
const visible = showInactive ? tokens : active;
+
async function disconnect() {
if (!pending || busy) return;
- setBusy(true); setError("");
+ setBusy(true);
+ setError("");
try {
- const response = await fetch(`/api/mcp/tokens?id=${encodeURIComponent(pending.id)}`, { method: "DELETE", signal: AbortSignal.timeout(10_000) });
+ const response = await fetch(`/api/mcp/tokens?id=${encodeURIComponent(pending.id)}`, {
+ method: "DELETE",
+ signal: AbortSignal.timeout(10_000),
+ });
if (!response.ok) throw new Error("Disconnect failed. Your selection is unchanged; try again.");
- setPending(null); onChanged();
- } catch { setError("Could not confirm disconnection. Refresh the list to check access before retrying."); }
- finally { setBusy(false); }
+ setPending(null);
+ onChanged();
+ } catch {
+ setError("Could not confirm disconnection. Refresh the list to check access before retrying.");
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ 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) {
+ setActivePatToken(undefined);
+ setActivePatLabel(label);
+ setConnectModalOpen(true);
}
- return <SettingsSection icon={<KeyRound />} title="Connected apps" 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>
- <Button onClick={onConnect} className="min-h-11">Connect an app</Button>
- </SettingsBlock>
- {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>}
- <div className="flex flex-wrap gap-2"><Button variant="destructive" disabled={busy} onClick={() => void disconnect()} className="min-h-11">{busy ? "Disconnecting…" : "Confirm disconnect"}</Button><Button variant="secondary" disabled={busy} onClick={() => { setPending(null); setError(""); }} className="min-h-11">Cancel</Button></div>
- </SettingsBlock>}
- {visible.length === 0 && <SettingsBlock className="py-4"><p className="text-sm text-muted-foreground">No active connections. Choose “Connect an app” to get started.</p></SettingsBlock>}
- {visible.map(token => <SettingsBlock key={token.id} className="space-y-3 py-4">
- <div className="flex flex-wrap items-start justify-between gap-3">
- <div className="min-w-0 flex-1"><h3 className="break-words text-sm font-medium">{token.label}</h3><p className="mt-1 text-sm text-muted-foreground">{permissions[token.scope] ?? token.scope} · {token.status}</p></div>
- {token.status === "active" && <Button variant="outline" disabled={busy} onClick={() => { setPending({ id: token.id, label: token.label }); setError(""); }} className="min-h-11">Disconnect<span className="sr-only"> {token.label}</span></Button>}
+
+ const allowedScopes = ["read"];
+ if (maxScope === "write" || maxScope === "exec") allowedScopes.push("write");
+ if (maxScope === "exec") allowedScopes.push("exec");
+
+ return (
+ <SettingsSection
+ icon={<KeyRound />}
+ title="Connected apps & tokens"
+ 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>
+ <div className="flex flex-wrap gap-2">
+ <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>
+ </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 &amp; 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>
+ )}
+ <div className="flex flex-wrap gap-2">
+ <Button
+ variant="destructive"
+ disabled={busy}
+ onClick={() => void disconnect()}
+ className="min-h-11"
+ >
+ {busy ? "Disconnecting…" : "Confirm disconnect"}
+ </Button>
+ <Button
+ variant="secondary"
+ disabled={busy}
+ onClick={() => {
+ setPending(null);
+ setError("");
+ }}
+ className="min-h-11"
+ >
+ Cancel
+ </Button>
+ </div>
+ </SettingsBlock>
+ )}
+
+ {visible.length === 0 && (
+ <SettingsBlock className="py-4">
+ <p className="text-sm text-muted-foreground">
+ No active connections. Choose “Generate New Token (PAT)” or “Connect an app” to get started.
+ </p>
+ </SettingsBlock>
+ )}
+
+ {visible.map((token) => (
+ <SettingsBlock key={token.id} className="space-y-3 py-4">
+ <div className="flex flex-wrap items-start justify-between gap-3">
+ <div className="min-w-0 flex-1">
+ <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>
+ )}
+ </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>
+ </>
+ )}
+ </div>
+ </div>
+ <p className="text-sm leading-relaxed text-muted-foreground">
+ 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>
+ <p className="break-all font-mono text-xs">{token.clientId}</p>
+ </details>
+ </SettingsBlock>
+ ))}
+
+ <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"
+ >
+ {showInactive ? "Hide" : "Show"} expired &amp; disconnected
+ </Button>
+ )}
+ {active.length > 1 && (
+ <Button
+ variant="ghost"
+ disabled={busy}
+ onClick={() =>
+ setPending({
+ id: "all",
+ label: `all ${active.length} active connections`,
+ })
+ }
+ className="min-h-11 text-destructive"
+ >
+ Disconnect all
+ </Button>
+ )}
</div>
- <p className="text-sm leading-relaxed text-muted-foreground">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><p className="break-all font-mono text-xs">{token.clientId}</p></details>
- </SettingsBlock>)}
- <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">{showInactive ? "Hide" : "Show"} expired &amp; disconnected</Button>}
- {active.length > 1 && <Button variant="ghost" disabled={busy} onClick={() => setPending({ id: "all", label: `all ${active.length} active connections` })} className="min-h-11 text-destructive">Disconnect all</Button>}
- </div>
- </SettingsSection>;
+
+ {/* Connect to AI Modal */}
+ <McpConnectModal
+ open={connectModalOpen}
+ onOpenChange={setConnectModalOpen}
+ origin={effectiveOrigin}
+ token={activePatToken}
+ label={activePatLabel}
+ />
+ </SettingsSection>
+ );
}
diff --git a/lib/mcp/origin.ts b/lib/mcp/origin.ts
index 6635066b..87b79abb 100644
--- a/lib/mcp/origin.ts
+++ b/lib/mcp/origin.ts
@@ -7,7 +7,9 @@
// client-settable and is consulted LAST.
function normalizedConfiguredOrigin(): string | null {
- const explicit = process.env.OS_PUBLIC_ORIGIN?.trim();
+ const explicit = process.env.OS_PUBLIC_ORIGIN?.trim() ||
+ process.env.NEXT_PUBLIC_APP_URL?.trim() ||
+ process.env.APP_URL?.trim();
if (!explicit) return null;
try {
return new URL(explicit).origin;
@@ -99,20 +101,44 @@ export function mcpCorsHeaders(req: Request): Record<string, string> {
};
}
+export function getBaseUrl(req: Request): string {
+ const explicit = process.env.OS_PUBLIC_ORIGIN?.trim() ||
+ process.env.NEXT_PUBLIC_APP_URL?.trim() ||
+ process.env.APP_URL?.trim();
+ if (explicit) {
+ try {
+ return new URL(explicit).origin;
+ } catch {
+ // Misconfigured value — fall through to header resolution
+ }
+ }
+
+ const url = new URL(req.url);
+ const forwardedHost = req.headers.get("x-forwarded-host")?.split(",")[0].trim();
+ const host = forwardedHost || req.headers.get("host")?.trim() || url.host || "localhost:3000";
+ const hostname = host.split(":")[0];
+ const isLoopback = isLoopbackHostname(hostname);
+
+ const forwardedProto = req.headers.get("x-forwarded-proto")?.split(",")[0].trim();
+ const proto = forwardedProto || (isLoopback ? "http" : url.protocol ? url.protocol.replace(":", "") : "https");
+
+ try {
+ return new URL(`${proto}://${host}`).origin;
+ } catch {
+ return `${proto}://${host}`;
+ }
+}
+
export function publicOrigin(req: Request): string {
const explicit = process.env.OS_PUBLIC_ORIGIN?.trim();
if (explicit) {
try {
return new URL(explicit).origin;
} catch {
- // Misconfigured value (a bare hostname, no scheme) — fall through to the
- // headers rather than emit a URL no client can resolve.
+ // Misconfigured value — fall through to dynamic resolution
}
}
- const url = new URL(req.url);
- const proto = req.headers.get("x-forwarded-proto")?.split(",")[0].trim() || url.protocol.replace(":", "");
- const host = req.headers.get("host") ?? req.headers.get("x-forwarded-host") ?? url.host;
- return `${proto}://${host}`;
+ return getBaseUrl(req);
}
export { clientIp } from "@/lib/host/request-ip";
diff --git a/lib/mcp/session-context.test.ts b/lib/mcp/session-context.test.ts
index e59639b4..9e2700ae 100644
--- a/lib/mcp/session-context.test.ts
+++ b/lib/mcp/session-context.test.ts
@@ -57,6 +57,20 @@ describe("MCP conversation/session correlation", () => {
expect(result.agentSessionId).toBeUndefined();
expect(mocks.findOrCreate).not.toHaveBeenCalled();
});
+
+ it("auto-provisions a persistent default session when client sends no session metadata or header", async () => {
+ const bare = new Request("https://mso.test/mcp");
+ const result = await resolveMcpSession(bare, call(), "mcp-client:x", "Antigravity");
+ if ("response" in result) throw new Error("unexpected error response");
+ expect(result.conversationBound).toBe(false);
+ expect(result.agentSessionId).toBeTruthy();
+ expect(result.responseSessionId).toBe(result.agentSessionId);
+ expect(mocks.findOrCreate).toHaveBeenCalledWith(
+ "mcp-client:x",
+ expect.stringMatching(/^[a-f0-9]{64}$/),
+ "Default · Antigravity"
+ );
+ });
});
it("bootstraps without transport state and rejects a foreign explicit application session", async () => {
diff --git a/lib/mcp/session-context.ts b/lib/mcp/session-context.ts
index 754ef98a..923cb5a2 100644
--- a/lib/mcp/session-context.ts
+++ b/lib/mcp/session-context.ts
@@ -57,7 +57,11 @@ export async function resolveMcpSession(req: Request, rpc: RpcLike, principal: s
return { responseSessionId: transportId, agentSessionId: session.id, conversationBound: true };
}
- if (!transportId) return { response: errorResponse(rpc, 400, "missing MSO session: call agent_session_open, then send params._meta[mso/sessionId]; ChatGPT metadata and legacy Mcp-Session-Id remain supported") };
+ if (!transportId) {
+ const autoHash = conversationHash(principal, "auto:default");
+ const session = await findOrCreateAgentSessionForConversation(principal, autoHash, `Default · ${label || "MSO"}`);
+ return { responseSessionId: session.id, agentSessionId: session.id, conversationBound: false };
+ }
const legacyHash = conversationHash(principal, `legacy:${transportId}`);
const session = await findOrCreateAgentSessionForConversation(principal, legacyHash, `MCP legacy · ${label || "MSO"}`);
return { responseSessionId: transportId, agentSessionId: session.id, conversationBound: false };
diff --git a/lib/mcp/store.test.ts b/lib/mcp/store.test.ts
index eb61715d..41a4bf2b 100644
--- a/lib/mcp/store.test.ts
+++ b/lib/mcp/store.test.ts
@@ -111,6 +111,35 @@ describe("tokens", () => {
expect(results.at(-1)).toBe(true);
expect(await store.validateToken("tok-race")).toBeNull();
});
+
+ it("mints and validates Personal Access Tokens (PAT) with Never Expire", async () => {
+ const { rawToken, tokenView } = await store.mintPatToken({ label: "Antigravity PAT", scope: "exec", ttlDays: 0 });
+ expect(rawToken).toMatch(/^mso_pat_[a-f0-9]+$/);
+ expect(tokenView.label).toBe("Antigravity PAT");
+ expect(tokenView.scope).toBe("exec");
+ expect(tokenView.expiresAt).toBe(0);
+ expect(tokenView.status).toBe("active");
+
+ const validated = await store.validateToken(rawToken);
+ expect(validated).not.toBeNull();
+ expect(validated!.scope).toBe("exec");
+ expect(validated!.expiresAt).toBe(0);
+
+ const listed = await store.listTokens();
+ const hit = listed.find((t) => t.id === tokenView.id);
+ expect(hit).toBeDefined();
+ expect(hit!.status).toBe("active");
+ });
+
+ it("mints PAT with specific ttlDays", async () => {
+ const { rawToken, tokenView } = await store.mintPatToken({ label: "Gemini CLI", scope: "read", ttlDays: 30 });
+ expect(tokenView.expiresAt).toBeGreaterThan(Date.now() + 29 * 86_400_000);
+ expect(tokenView.status).toBe("active");
+
+ const validated = await store.validateToken(rawToken);
+ expect(validated).not.toBeNull();
+ expect(validated!.scope).toBe("read");
+ });
});
describe("clients", () => {
diff --git a/lib/mcp/store.ts b/lib/mcp/store.ts
index 881319d5..d5d09a26 100644
--- a/lib/mcp/store.ts
+++ b/lib/mcp/store.ts
@@ -1,5 +1,5 @@
import { expandOwnerStorePath } from "@/lib/owner-store-path.js";
-import { randomUUID } from "node:crypto";
+import { randomUUID, randomBytes } from "node:crypto";
import { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
@@ -124,8 +124,8 @@ 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 >= now).map((row) => row.clientId),
- ...Object.values(store.refreshTokens).filter((row) => !row.revokedAt && 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));
}
@@ -225,7 +225,7 @@ export async function validateToken(token: string): Promise<(McpToken & { hash:
const hash = sha256hex(token);
const rec = (await read()).tokens[hash];
if (!rec || rec.revokedAt) return null;
- if (rec.expiresAt < Date.now()) return null;
+ if (rec.expiresAt > 0 && rec.expiresAt < Date.now()) return null;
return { ...rec, hash };
}
@@ -255,7 +255,7 @@ export async function listTokens(): Promise<TokenView[]> {
.map(([hash, t]) => ({
...t,
id: hash.slice(0, 16),
- status: t.revokedAt ? ("revoked" as const) : t.expiresAt < now ? ("expired" as const) : ("active" as const),
+ 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);
}
@@ -284,3 +284,36 @@ export function revokeAllTokens(): Promise<number> {
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,
+ },
+ };
+ });
+}
diff --git a/lib/mcp/tools-agent-open.ts b/lib/mcp/tools-agent-open.ts
index 105f23a1..d626c15d 100644
--- a/lib/mcp/tools-agent-open.ts
+++ b/lib/mcp/tools-agent-open.ts
@@ -1,23 +1,41 @@
-import { agentSessionSummary, findOrCreateAgentSessionForConversation, updateAgentSessionLocation } from "@/lib/agent/session-store";
+import { randomUUID } from "node:crypto";
+import { agentSessionSummary, findOrCreateAgentSessionForConversation, renameAgentSession, updateAgentSessionLocation } from "@/lib/agent/session-store";
import { conversationHash } from "@/lib/agent/session-policy";
import { resolveProjectHint } from "@/lib/host/projects-api";
import { type McpTool, S, str } from "./tool-kit";
+
export const AGENT_OPEN_TOOLS: McpTool[] = [{
- name: "agent_session_open", title: "Open Agent Session", scope: "write",
+ name: "agent_session_open", title: "Open Agent Session", scope: "read",
description: "Bootstrap an MSO application session for any AI provider. Reuse a unique conversation_key per conversation; this is metadata, never a secret. Send returned session.id as params._meta[mso/sessionId] or Mso-Session-Id on later calls. Optional exact project binds its working directory. The session is isolated to the authenticated principal.",
chatgptDescription: "Open/resume a provider-neutral session using a stable conversation_key. Send session.id as _meta[mso/sessionId] on later calls.",
- annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false, idempotentHint: true },
- audit: { action: "agent.session" }, limit: { key: "agent.session.open", max: 20, windowMs: 60_000 },
- inputSchema: S({ conversation_key: { type: "string", minLength: 1, maxLength: 256 }, project: { type: "string", description: "Optional exact project id/path/name." } }, ["conversation_key"]),
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false, idempotentHint: true },
+ limit: { key: "agent.session.open", max: 20, windowMs: 60_000 },
+ inputSchema: S({
+ conversation_key: { type: "string", minLength: 1, maxLength: 256, description: "Optional stable identifier for this conversation. If omitted, a fresh session key is generated." },
+ title: { type: "string", maxLength: 120, description: "Optional session title." },
+ project: { type: "string", description: "Optional exact project id/path/name." },
+ }),
run: async (a, context) => {
if (!context.principal) throw new Error("authenticated principal required");
- const key = str(a, "conversation_key");
- if (!key.trim() || key.length > 256 || /[\x00-\x1f]/.test(key)) throw new Error("invalid conversation_key");
+ const rawKey = a.conversation_key ? str(a, "conversation_key") : `open:${randomUUID().slice(0, 16)}`;
+ const key = rawKey.trim();
+ if (!key || key.length > 256 || /[\x00-\x1f]/.test(key)) throw new Error("invalid conversation_key");
const project = a.project ? await resolveProjectHint(str(a, "project")) : null;
if (a.project && (!project || project.matchedBy === "fuzzy")) throw new Error("exact project required");
- let session = await findOrCreateAgentSessionForConversation(context.principal, conversationHash(context.principal, "agent:" + key), "Agent · MSO");
+ const rawTitle = a.title ? str(a, "title").trim().slice(0, 120) : "";
+ const sessionTitle = rawTitle || "Agent · MSO";
+ let session = await findOrCreateAgentSessionForConversation(context.principal, conversationHash(context.principal, "agent:" + key), sessionTitle);
+ if (rawTitle && session.title !== rawTitle) {
+ session = await renameAgentSession(context.principal, session.id, rawTitle);
+ }
if (project && session.cwd !== project.path) session = await updateAgentSessionLocation(context.principal, session.id, project.path);
- return { session: agentSessionSummary(session), ...(project ? { project: project.id } : {}),
- next: { meta: { "mso/sessionId": session.id }, flow: "flow_catalog → flow_run → flow_status", projectMcp: "project_capabilities → project_mcp_tools → project_mcp_call" } };
+ return {
+ ok: true,
+ sessionId: session.id,
+ title: session.title,
+ session: agentSessionSummary(session),
+ ...(project ? { project: project.id } : {}),
+ next: { meta: { "mso/sessionId": session.id }, flow: "flow_catalog → flow_run → flow_status", projectMcp: "project_capabilities → project_mcp_tools → project_mcp_call" },
+ };
},
}];