Open-source SEO, GEO, and marketing skills for AI agents.
feat(notfair-cmo): user-configurable MCP catalog (0.3.1)
Yuting Zhong5309acc1043b
diff --git a/notfair-cmo/CHANGELOG.md b/notfair-cmo/CHANGELOG.mdindex 8ebf124b..ad81b2a8 100644--- a/notfair-cmo/CHANGELOG.md+++ b/notfair-cmo/CHANGELOG.md@@ -1,5 +1,15 @@# notfair-cmo+## 0.3.1 — 2026-05-31++User-configurable MCP catalog. The Connections page is no longer limited to the curated preset list — users can register any OAuth-2.0 MCP server (Stripe, Vercel, Supabase, or their own) by pasting a resource URL. The portal probes RFC 9728 protected-resource discovery + RFC 8414 AS metadata before persisting, so only servers that actually support dynamic client registration get past the form.++- New `user_mcp_servers` SQLite table (migration `011`), project-scoped, joined with `MCP_CATALOG_PRESETS` by the new `getMcpCatalog(project_slug)` helper.+- `mcpSpecByKey` is now project-scoped (`(project_slug, key)`); all call sites updated.+- New server actions: `probeMcpDiscovery`, `addUserMcpServerAction`, `removeUserMcpServerAction`.+- New "Add an MCP server" card on the Connections page; user-added cards get a "Remove server" affordance presets don't have.+- `cascadeDeleteProjectArtifacts` cleans up `user_mcp_servers` rows on project deletion and unregisters the adapter rows for both presets and user-added entries.+## 0.3.0 — 2026-06-01End-to-end wiring + reliability pass on top of the 0.2.0 harness-agnostic rewrite. Every surface in the app is now driven by a real, persisted code path; no more half-finished stubs.diff --git a/notfair-cmo/package.json b/notfair-cmo/package.jsonindex f8472648..974c5626 100644--- a/notfair-cmo/package.json+++ b/notfair-cmo/package.json@@ -1,6 +1,6 @@{"name": "notfair-cmo",- "version": "0.3.0",+ "version": "0.3.1","description": "Open-source AI marketing CMO portal. Run locally; orchestrates marketing agents (Google Ads, SEO, and more) on top of Claude Code, Codex, or other local AI coding agents.","license": "MIT","bin": {diff --git a/notfair-cmo/src/app/(app)/[project]/connections/page.tsx b/notfair-cmo/src/app/(app)/[project]/connections/page.tsxindex 8084477f..ecadaecc 100644--- a/notfair-cmo/src/app/(app)/[project]/connections/page.tsx+++ b/notfair-cmo/src/app/(app)/[project]/connections/page.tsx@@ -1,12 +1,13 @@import { notFound } from "next/navigation";import { Card, CardContent } from "@/components/ui/card";import { getProject } from "@/server/db/projects";-import { MCP_CATALOG } from "@/server/mcp-catalog";+import { getMcpCatalog } from "@/server/mcp-catalog";import { getMcpStatus } from "@/server/mcp/state";import { summarizeBuiltinTools } from "@/server/mcp-server/tool-summaries";import { McpCard } from "@/components/mcp-card";import { BuiltinMcpCard } from "@/components/builtin-mcp-card";import { McpFlashBanner } from "@/components/mcp-flash-banner";+import { AddMcpServerCard } from "@/components/add-mcp-server-card";type Search = { mcp_connected?: string; mcp_error?: string };@@ -22,10 +23,11 @@ export default async function ConnectionsPage({const { mcp_connected, mcp_error } = await searchParams;if (!project || project.archived_at) notFound();+ const catalog = getMcpCatalog(project.slug);// Status probes happen in parallel — each has its own 2s timeout so a// flaky upstream doesn't gate the whole page.const statuses = await Promise.all(- MCP_CATALOG.map((s) => getMcpStatus(project.slug, s.key)),+ catalog.map((s) => getMcpStatus(project.slug, s.key)),);// Built-in MCP: notfair-orchestration ships with the platform and serves@@ -55,17 +57,19 @@ export default async function ConnectionsPage({tools={builtinTools}/>- {MCP_CATALOG.length === 0 ? (+ {catalog.length === 0 ? (<Card><CardContent className="py-12 text-center text-sm text-muted-foreground">No external MCP servers in the catalog yet.</CardContent></Card>) : (- MCP_CATALOG.map((spec, i) => (+ catalog.map((spec, i) => (<McpCard key={spec.key} spec={spec} status={statuses[i]} />)))}++ <AddMcpServerCard /></div></div>);diff --git a/notfair-cmo/src/components/add-mcp-server-card.tsx b/notfair-cmo/src/components/add-mcp-server-card.tsxnew file mode 100644index 00000000..c78ba8a8--- /dev/null+++ b/notfair-cmo/src/components/add-mcp-server-card.tsx@@ -0,0 +1,166 @@+"use client";++import { useState } from "react";+import { useRouter } from "next/navigation";+import { Plus, Loader2 } from "lucide-react";++import { Card, CardContent } from "@/components/ui/card";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { toast } from "sonner";+import { addUserMcpServerAction } from "@/server/actions/mcp";++/**+ * Connections-page card that opens an "Add MCP server" dialog. Any+ * server that publishes RFC 9728 discovery + a DCR-capable AS metadata+ * doc can be added — Stripe, Vercel, Supabase, etc.+ *+ * No bearer-paste path: OAuth 2.0 only. The form submits to+ * `addUserMcpServerAction`, which probes discovery before persisting+ * the row, so a server that won't connect is rejected before the user+ * even sees a Connect button.+ */+export function AddMcpServerCard() {+ const [open, setOpen] = useState(false);+ const [submitting, setSubmitting] = useState(false);+ const [displayName, setDisplayName] = useState("");+ const [resourceUrl, setResourceUrl] = useState("");+ const [error, setError] = useState<string | null>(null);+ const router = useRouter();++ function reset() {+ setDisplayName("");+ setResourceUrl("");+ setError(null);+ }++ async function onSubmit(e: React.FormEvent) {+ e.preventDefault();+ setError(null);+ setSubmitting(true);+ try {+ const result = await addUserMcpServerAction({+ display_name: displayName,+ resource_url: resourceUrl,+ });+ if (!result.ok) {+ setError(result.error);+ return;+ }+ toast.success(`Added MCP server '${result.key}'. Click Connect to authorize.`);+ setOpen(false);+ reset();+ router.refresh();+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setSubmitting(false);+ }+ }++ return (+ <>+ <Card>+ <CardContent className="flex items-center justify-between gap-4 py-4">+ <div className="space-y-0.5">+ <p className="text-sm font-medium">Add an MCP server</p>+ <p className="text-xs text-muted-foreground">+ Connect any OAuth 2.0 MCP server — Stripe, Vercel, Supabase, or+ your own.+ </p>+ </div>+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => setOpen(true)}+ >+ <Plus className="size-3.5" />+ Add server+ </Button>+ </CardContent>+ </Card>++ <Dialog+ open={open}+ onOpenChange={(next) => {+ setOpen(next);+ if (!next) reset();+ }}+ >+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Add MCP server</DialogTitle>+ <DialogDescription>+ Paste the MCP server's resource URL. We'll verify it+ advertises OAuth 2.0 dynamic client registration before saving.+ </DialogDescription>+ </DialogHeader>+ <form onSubmit={onSubmit} className="space-y-4">+ <div className="space-y-1.5">+ <Label htmlFor="mcp-display-name">Name</Label>+ <Input+ id="mcp-display-name"+ placeholder="Stripe"+ value={displayName}+ onChange={(e) => setDisplayName(e.target.value)}+ disabled={submitting}+ required+ autoFocus+ />+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="mcp-resource-url">Remote MCP server URL</Label>+ <Input+ id="mcp-resource-url"+ type="url"+ placeholder="https://mcp.stripe.com/"+ value={resourceUrl}+ onChange={(e) => setResourceUrl(e.target.value)}+ disabled={submitting}+ required+ />+ <p className="text-xs text-muted-foreground">+ The HTTPS endpoint your agents will call. We derive the OAuth+ discovery URL from this automatically.+ </p>+ </div>+ {error ? (+ <p+ className="rounded border border-destructive/30 bg-destructive/5 p-2 text-xs text-destructive"+ role="alert"+ >+ {error}+ </p>+ ) : null}+ <DialogFooter>+ <Button+ type="button"+ variant="ghost"+ onClick={() => setOpen(false)}+ disabled={submitting}+ >+ Cancel+ </Button>+ <Button type="submit" disabled={submitting}>+ {submitting ? (+ <Loader2 className="size-3.5 animate-spin" />+ ) : null}+ Add server+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ </>+ );+}diff --git a/notfair-cmo/src/components/mcp-card.test.tsx b/notfair-cmo/src/components/mcp-card.test.tsxindex d26d70f2..dd70fc7c 100644--- a/notfair-cmo/src/components/mcp-card.test.tsx+++ b/notfair-cmo/src/components/mcp-card.test.tsx@@ -43,6 +43,7 @@ const spec: McpSpec = {resource_url: "https://notfair.co/api/mcp/google_ads",discovery_url:"https://notfair.co/.well-known/oauth-protected-resource/api/mcp/google_ads",+ source: "preset",};function connected(overrides: Partial<Extract<McpRuntimeStatus, { state: "connected" }>> = {}): McpRuntimeStatus {diff --git a/notfair-cmo/src/components/mcp-card.tsx b/notfair-cmo/src/components/mcp-card.tsxindex 449a7cc8..8027a57b 100644--- a/notfair-cmo/src/components/mcp-card.tsx+++ b/notfair-cmo/src/components/mcp-card.tsx@@ -10,6 +10,7 @@ import {Unplug,XCircle,BookOpenText,+ Trash2,} from "lucide-react";import { Card, CardContent } from "@/components/ui/card";import { Button } from "@/components/ui/button";@@ -19,6 +20,7 @@ import {startMcpConnect,disconnectMcpAction,listMcpToolsAction,+ removeUserMcpServerAction,} from "@/server/actions/mcp";import type { McpSpec } from "@/server/mcp-catalog";import type { McpRuntimeStatus } from "@/server/mcp/state";@@ -31,7 +33,7 @@ type Props = {export function McpCard({ spec, status }: Props) {const [pending, startTransition] = useTransition();- const [busy, setBusy] = useState<"connect" | "disconnect" | null>(null);+ const [busy, setBusy] = useState<"connect" | "disconnect" | "remove" | null>(null);const [toolsOpen, setToolsOpen] = useState(false);const router = useRouter();@@ -70,8 +72,23 @@ export function McpCard({ spec, status }: Props) {});}+ function onRemove() {+ setBusy("remove");+ startTransition(async () => {+ const result = await removeUserMcpServerAction({ mcp_key: spec.key });+ if (!result.ok) {+ toast.error(result.error);+ } else {+ toast.success(`${spec.display_name} removed`);+ router.refresh();+ }+ setBusy(null);+ });+ }+const isBusy = busy !== null || pending;const canViewTools = status.state === "connected";+ const canRemove = spec.source === "user";return (<>@@ -79,9 +96,7 @@ export function McpCard({ spec, status }: Props) {<CardContent className="space-y-4 p-5"><div className="flex items-start justify-between gap-3"><div className="flex items-start gap-3 min-w-0">- <div className="flex size-9 shrink-0 items-center justify-center rounded-md bg-muted">- <Plug className="size-4" />- </div>+ <McpIcon resourceUrl={spec.resource_url} alt={spec.display_name} /><div className="min-w-0"><div className="flex items-center gap-2"><h3 className="text-sm font-medium">{spec.display_name}</h3>@@ -126,18 +141,37 @@ export function McpCard({ spec, status }: Props) {<div className="flex items-center justify-between gap-3"><StatusDetail status={status} />- {canViewTools && (- <Button- type="button"- variant="ghost"- size="sm"- className="h-7 shrink-0 px-2 text-xs text-muted-foreground hover:text-foreground"- onClick={() => setToolsOpen(true)}- >- <BookOpenText className="size-3.5" />- View tools- </Button>- )}+ <div className="flex shrink-0 items-center gap-1">+ {canViewTools && (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="h-7 px-2 text-xs text-muted-foreground hover:text-foreground"+ onClick={() => setToolsOpen(true)}+ >+ <BookOpenText className="size-3.5" />+ View tools+ </Button>+ )}+ {canRemove && (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="h-7 px-2 text-xs text-muted-foreground hover:text-destructive"+ disabled={isBusy}+ onClick={onRemove}+ >+ {busy === "remove" ? (+ <Loader2 className="size-3.5 animate-spin" />+ ) : (+ <Trash2 className="size-3.5" />+ )}+ Remove server+ </Button>+ )}+ </div></div></CardContent></Card>@@ -153,6 +187,58 @@ export function McpCard({ spec, status }: Props) {);}+/**+ * Renders the MCP server's brand favicon via Google's `faviconV2` service.+ *+ * We strip subdomains down to the registrable domain (`mcp.stripe.com` →+ * `stripe.com`) so the icon reflects the company's brand, not the API+ * subdomain — Google rarely has a real favicon indexed for `mcp.*` or+ * `api.*` hosts. Falls back to a Plug glyph on malformed URLs.+ */+function McpIcon({ resourceUrl, alt }: { resourceUrl: string; alt: string }) {+ const [errored, setErrored] = useState(false);+ let host: string | null = null;+ try {+ host = new URL(resourceUrl).hostname;+ } catch {+ host = null;+ }+ const brandHost = host ? brandDomain(host) : null;+ const showImg = !!brandHost && !errored;+ return (+ <div className="flex size-9 shrink-0 items-center justify-center overflow-hidden rounded-md bg-muted">+ {showImg ? (+ // eslint-disable-next-line @next/next/no-img-element+ <img+ src={`https://t3.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&url=http://${brandHost}&size=32`}+ alt={alt}+ width={20}+ height={20}+ className="size-5"+ referrerPolicy="no-referrer"+ onError={() => setErrored(true)}+ />+ ) : (+ <Plug className="size-4" />+ )}+ </div>+ );+}++/**+ * Reduce a hostname to a "brand" host for favicon lookup. The Public+ * Suffix List is the only fully correct answer here; the simple last-2-+ * labels heuristic is wrong for some multipart TLDs (`example.co.uk`),+ * but it's right for ~all consumer SaaS the connections page targets.+ * Hosts that are already 2 labels or fewer (`notfair.co`, `localhost`)+ * pass through unchanged.+ */+function brandDomain(host: string): string {+ const parts = host.split(".").filter(Boolean);+ if (parts.length <= 2) return host;+ return parts.slice(-2).join(".");+}+function StatusBadge({ status }: { status: McpRuntimeStatus }) {switch (status.state) {case "connected":diff --git a/notfair-cmo/src/server/actions/mcp.ts b/notfair-cmo/src/server/actions/mcp.tsindex 105562f7..cdd39bcc 100644--- a/notfair-cmo/src/server/actions/mcp.ts+++ b/notfair-cmo/src/server/actions/mcp.ts@@ -4,9 +4,16 @@ import { randomBytes, createHash } from "node:crypto";import { revalidatePath } from "next/cache";import { headers } from "next/headers";import { getActiveProject } from "@/server/active-project";-import { mcpSpecByKey } from "@/server/mcp-catalog";+import { isPresetKey, mcpSpecByKey } from "@/server/mcp-catalog";import { setPending } from "@/server/mcp-pending";import { disconnectMcp as runDisconnect } from "@/server/mcp/state";+import {+ insertUserMcpServer,+ findUserMcpServer,+ deleteUserMcpServer,+} from "@/server/db/user-mcp-servers";+import { slugify } from "@/lib/slug";+import { deriveDiscoveryUrl } from "@/server/mcp/discovery-url";export type StartMcpConnectResult =| { ok: true; authorize_url: string }@@ -28,14 +35,14 @@ export async function startMcpConnect(input: {*/return_to?: string;}): Promise<StartMcpConnectResult> {- const spec = mcpSpecByKey(input.mcp_key);- if (!spec) return { ok: false, error: `Unknown MCP key: ${input.mcp_key}` };-const project = await getActiveProject();if (!project) {return { ok: false, error: "No active project. Pick one before connecting an MCP." };}+ const spec = mcpSpecByKey(project.slug, input.mcp_key);+ if (!spec) return { ok: false, error: `Unknown MCP key: ${input.mcp_key}` };+let resolved: ResolvedAuthServer;try {resolved = await resolveAuthServer(spec.discovery_url);@@ -170,6 +177,161 @@ export async function listMcpToolsAction(input: {return { ok: true, tools };}+export type ProbeMcpDiscoveryResult =+ | {+ ok: true;+ discovery_url: string;+ issuer: string;+ registration_endpoint: string;+ }+ | { ok: false; error: string; kind: ProbeFailureKind };++type ProbeFailureKind =+ | "bad_url"+ | "no_discovery_doc"+ | "no_authorization_servers"+ | "as_metadata_missing_endpoints"+ | "dcr_unsupported";++/**+ * Validate that a candidate MCP resource URL is OAuth-2.0 connectable.+ *+ * Derives the RFC 9728 discovery URL from the resource URL, fetches it,+ * follows the first `authorization_servers` issuer, fetches its RFC 8414+ * metadata, and asserts the AS publishes a `registration_endpoint` (DCR).+ *+ * Returns the resolved discovery URL on success so the caller can stash+ * it on the user_mcp_servers row — the connect flow reuses that URL+ * verbatim, so we don't re-derive it later.+ */+export async function probeMcpDiscovery(input: {+ resource_url: string;+}): Promise<ProbeMcpDiscoveryResult> {+ const discovery_url = deriveDiscoveryUrl(input.resource_url);+ if (!discovery_url) {+ return {+ ok: false,+ kind: "bad_url",+ error: "Resource URL must be an https URL.",+ };+ }+ try {+ const resolved = await resolveAuthServer(discovery_url);+ return {+ ok: true,+ discovery_url,+ issuer: resolved.issuer,+ registration_endpoint: resolved.registration_endpoint,+ };+ } catch (err) {+ return classifyProbeError(err);+ }+}++export type AddUserMcpServerResult =+ | { ok: true; key: string }+ | { ok: false; error: string; kind: AddFailureKind };++type AddFailureKind = ProbeFailureKind | "no_project" | "name_unusable" | "key_in_use";++/**+ * Register a user-added MCP server for the active project.+ *+ * Slugs the display name into a stable `key` (also used as+ * `mcp_tokens.server_name` post-connect), probes discovery to confirm the+ * server is OAuth-2.0-with-DCR connectable, and writes a row to+ * `user_mcp_servers`. The user then clicks Connect on the resulting card+ * to drive the existing OAuth flow.+ */+export async function addUserMcpServerAction(input: {+ display_name: string;+ description?: string;+ resource_url: string;+}): Promise<AddUserMcpServerResult> {+ const project = await getActiveProject();+ if (!project) {+ return {+ ok: false,+ kind: "no_project",+ error: "No active project. Pick one before adding an MCP server.",+ };+ }+ const slug = slugify(input.display_name);+ if (!slug.ok) {+ return {+ ok: false,+ kind: "name_unusable",+ error: `Can't derive a key from this name: ${slug.reason}.`,+ };+ }+ if (isPresetKey(slug.slug) || findUserMcpServer(project.slug, slug.slug)) {+ return {+ ok: false,+ kind: "key_in_use",+ error: `An MCP server named '${slug.slug}' already exists in this project.`,+ };+ }+ const probe = await probeMcpDiscovery({ resource_url: input.resource_url });+ if (!probe.ok) return probe;+ insertUserMcpServer({+ project_slug: project.slug,+ key: slug.slug,+ display_name: input.display_name.trim(),+ description: input.description?.trim() ?? "",+ resource_url: input.resource_url.trim(),+ discovery_url: probe.discovery_url,+ });+ revalidatePath("/", "layout");+ return { ok: true, key: slug.slug };+}++/**+ * Remove a user-added MCP server from the active project. Drops the+ * stored bearer (if any), unregisters from every agent's harness config,+ * and deletes the catalog row.+ *+ * Presets cannot be removed this way — the action refuses unknown or+ * preset keys.+ */+export async function removeUserMcpServerAction(input: {+ mcp_key: string;+}): Promise<{ ok: true } | { ok: false; error: string }> {+ const project = await getActiveProject();+ if (!project) {+ return { ok: false, error: "No active project." };+ }+ if (isPresetKey(input.mcp_key)) {+ return { ok: false, error: "Preset MCP servers can't be removed." };+ }+ const row = findUserMcpServer(project.slug, input.mcp_key);+ if (!row) {+ return { ok: false, error: `Unknown MCP key: ${input.mcp_key}.` };+ }+ try {+ await runDisconnect(project.slug, input.mcp_key);+ const { listProjectAgents } = await import("@/server/agent-meta");+ const { getProject } = await import("@/server/db/projects");+ const { requireAdapter } = await import("@/server/adapters/registry");+ const proj = getProject(project.slug);+ if (proj) {+ const adapter = requireAdapter(proj.harness_adapter);+ const agents = await listProjectAgents(project.slug);+ for (const agent of agents) {+ try {+ await adapter.unregisterMcp(input.mcp_key, agent.agent_id);+ } catch {+ // best-effort+ }+ }+ }+ deleteUserMcpServer(project.slug, input.mcp_key);+ } catch (err) {+ return { ok: false, error: humanError(err) };+ }+ revalidatePath("/", "layout");+ return { ok: true };+}+// ─── helpers ────────────────────────────────────────────────────────type ResolvedAuthServer = {@@ -179,30 +341,70 @@ type ResolvedAuthServer = {registration_endpoint: string;};+class ProbeError extends Error {+ kind: ProbeFailureKind;+ constructor(kind: ProbeFailureKind, message: string) {+ super(message);+ this.kind = kind;+ }+}+async function resolveAuthServer(resourceDiscoveryUrl: string,): Promise<ResolvedAuthServer> {// RFC 9728: GET .well-known/oauth-protected-resource → carries the// `authorization_servers` array. We pick the first and then fetch its// RFC 8414 AS metadata to learn registration/token/authorize endpoints.- const r1 = await fetchJson(resourceDiscoveryUrl, 8000);+ let r1: unknown;+ try {+ r1 = await fetchJson(resourceDiscoveryUrl, 8000);+ } catch (err) {+ throw new ProbeError(+ "no_discovery_doc",+ err instanceof Error ? err.message : String(err),+ );+ }const servers = (r1 as { authorization_servers?: unknown }).authorization_servers;if (!Array.isArray(servers) || servers.length === 0) {- throw new Error("no authorization_servers in discovery doc");+ throw new ProbeError(+ "no_authorization_servers",+ "no authorization_servers in discovery doc",+ );}const issuer = String(servers[0]).replace(/\/$/, "");- // Standard AS metadata path; some notfair-style servers also accept a- // path-suffixed variant. Try the standard first — the path-suffixed- // variant is a hint for clients that skip RFC 9728, which we just- // didn't.- const asMetaUrl = `${issuer}/.well-known/oauth-authorization-server`;- const meta = (await fetchJson(asMetaUrl, 8000)) as Partial<ResolvedAuthServer>;- if (- !meta.authorization_endpoint- || !meta.token_endpoint- || !meta.registration_endpoint- ) {- throw new Error("AS metadata missing endpoints");+ // RFC 8414 §3.1 says the well-known suffix is inserted between the+ // issuer's host and path (the "inserted" form). The OIDC Discovery and+ // some MCP servers also accept the issuer-suffix variant ("appended"+ // form). Try each in order until one returns valid metadata.+ const candidates = asMetadataCandidates(issuer);+ const attempts: string[] = [];+ let meta: Partial<ResolvedAuthServer> | null = null;+ for (const url of candidates) {+ attempts.push(url);+ try {+ meta = (await fetchJson(url, 8000)) as Partial<ResolvedAuthServer>;+ break;+ } catch {+ // try the next candidate+ }+ }+ if (!meta) {+ throw new ProbeError(+ "as_metadata_missing_endpoints",+ `Couldn't fetch AS metadata. Tried: ${attempts.join(", ")}`,+ );+ }+ if (!meta.authorization_endpoint || !meta.token_endpoint) {+ throw new ProbeError(+ "as_metadata_missing_endpoints",+ "AS metadata missing authorize/token endpoints",+ );+ }+ if (!meta.registration_endpoint) {+ throw new ProbeError(+ "dcr_unsupported",+ "AS metadata is missing registration_endpoint — dynamic client registration is required.",+ );}return {issuer,@@ -212,6 +414,49 @@ async function resolveAuthServer(};}+/**+ * Build the AS-metadata URLs to probe, in priority order, for a given+ * issuer. The "inserted" variants are spec-correct (RFC 8414 §3.1 / OIDC+ * Discovery §4); the "appended" variants are a common deviation a number+ * of real-world MCP servers still ship — including, ironically, the+ * issuer URL Stripe advertises (`https://access.stripe.com/mcp`), which+ * resolves only via the inserted form.+ */+function asMetadataCandidates(issuer: string): string[] {+ const out: string[] = [];+ let u: URL;+ try {+ u = new URL(issuer);+ } catch {+ return out;+ }+ const path = u.pathname === "/" ? "" : u.pathname.replace(/\/+$/, "");+ const origin = u.origin;+ // RFC 8414: inserted between host and path.+ out.push(`${origin}/.well-known/oauth-authorization-server${path}`);+ // OIDC Discovery: same insertion shape with a different suffix.+ out.push(`${origin}/.well-known/openid-configuration${path}`);+ // Appended-form fallbacks for servers that don't follow the insertion+ // rule. Only worth trying when the issuer has a non-root path; for a+ // root issuer the appended form equals the inserted form.+ if (path) {+ out.push(`${issuer.replace(/\/$/, "")}/.well-known/oauth-authorization-server`);+ out.push(`${issuer.replace(/\/$/, "")}/.well-known/openid-configuration`);+ }+ return out;+}++function classifyProbeError(err: unknown): ProbeMcpDiscoveryResult {+ if (err instanceof ProbeError) {+ return { ok: false, kind: err.kind, error: err.message };+ }+ return {+ ok: false,+ kind: "no_discovery_doc",+ error: err instanceof Error ? err.message : String(err),+ };+}+type DcrResponse = {client_id: string;client_secret?: string;diff --git a/notfair-cmo/src/server/agents/cascade-delete.ts b/notfair-cmo/src/server/agents/cascade-delete.tsindex bf02ccb0..d8100176 100644--- a/notfair-cmo/src/server/agents/cascade-delete.ts+++ b/notfair-cmo/src/server/agents/cascade-delete.ts@@ -2,7 +2,7 @@ import { existsSync } from "node:fs";import { rm } from "node:fs/promises";import type { AgentTemplate } from "@/server/agent-templates";import { listProjectAgents } from "@/server/agent-meta";-import { MCP_CATALOG } from "@/server/mcp-catalog";+import { getMcpCatalog } from "@/server/mcp-catalog";import { listCronsForProject } from "@/server/scheduler/display";import { listProjectMcpTokens, deleteProjectMcpTokens } from "@/server/mcp/tokens";import { listAgentSessions } from "@/server/sessions";@@ -72,12 +72,14 @@ export async function getProjectDeletionSummary(// pair.const tokens = listProjectMcpTokens(project_slug);const tokenServers = new Set(tokens.map((t) => t.server_name));- const mcps: ProjectDeletionMcpSummary[] = MCP_CATALOG.map((spec) => ({- catalog_key: spec.key,- display_name: spec.display_name,- stored_key: `${project_slug}-${spec.key}`,- configured: tokenServers.has(spec.key),- }));+ const mcps: ProjectDeletionMcpSummary[] = getMcpCatalog(project_slug).map(+ (spec) => ({+ catalog_key: spec.key,+ display_name: spec.display_name,+ stored_key: `${project_slug}-${spec.key}`,+ configured: tokenServers.has(spec.key),+ }),+ );return {project_slug,@@ -107,8 +109,9 @@ export async function cascadeDeleteProjectArtifacts(project_slug: string): Promi// Unregister any MCP servers the adapter wrote into its config (so codex// global config doesn't leak agent-namespaced rows for deleted agents).if (adapter) {+ const catalog = getMcpCatalog(project_slug);for (const agent of agents) {- for (const spec of MCP_CATALOG) {+ for (const spec of catalog) {try {await adapter.unregisterMcp(spec.key, agent.agent_id);} catch {@@ -139,4 +142,9 @@ export async function cascadeDeleteProjectArtifacts(project_slug: string): Promi// Drop MCP tokens.deleteProjectMcpTokens(project_slug);++ // Drop user-added MCP catalog entries for the project.+ getDb()+ .prepare("DELETE FROM user_mcp_servers WHERE project_slug = ?")+ .run(project_slug);}diff --git a/notfair-cmo/src/server/db/migrations.ts b/notfair-cmo/src/server/db/migrations.tsindex 941e5505..c5040575 100644--- a/notfair-cmo/src/server/db/migrations.ts+++ b/notfair-cmo/src/server/db/migrations.ts@@ -476,6 +476,35 @@ CREATE TABLE IF NOT EXISTS scheduled_job_runs (error_message TEXT);CREATE INDEX IF NOT EXISTS idx_scheduled_job_runs_job ON scheduled_job_runs(scheduled_job_id, started_at);+`,+ },+ {+ name: "011_user_mcp_servers.sql",+ sql: `+-- Migration 011: user-added MCP servers.+--+-- The Connections page used to render a hardcoded preset catalog+-- (notfair-googleads). Users now register arbitrary OAuth-2.0 MCP servers+-- (Stripe, Vercel, Supabase, etc.) from the UI. Each row is project-scoped+-- and joined alongside the preset list in \`getMcpCatalog\`.+--+-- The \`key\` column carries the same identifier that mcp_tokens.server_name+-- uses, so the OAuth callback + token storage + adapter registration paths+-- work without changes.++CREATE TABLE IF NOT EXISTS user_mcp_servers (+ id TEXT PRIMARY KEY,+ project_slug TEXT NOT NULL REFERENCES projects(slug),+ key TEXT NOT NULL,+ display_name TEXT NOT NULL,+ description TEXT NOT NULL DEFAULT '',+ resource_url TEXT NOT NULL,+ discovery_url TEXT NOT NULL,+ created_at TEXT NOT NULL,+ updated_at TEXT NOT NULL,+ UNIQUE(project_slug, key)+);+CREATE INDEX IF NOT EXISTS idx_user_mcp_servers_project ON user_mcp_servers(project_slug);`,},];diff --git a/notfair-cmo/src/server/db/migrations/011_user_mcp_servers.sql b/notfair-cmo/src/server/db/migrations/011_user_mcp_servers.sqlnew file mode 100644index 00000000..8e06b2d7--- /dev/null+++ b/notfair-cmo/src/server/db/migrations/011_user_mcp_servers.sql@@ -0,0 +1,24 @@+-- Migration 011: user-added MCP servers.+--+-- The Connections page used to render a hardcoded preset catalog+-- (notfair-googleads). Users now register arbitrary OAuth-2.0 MCP servers+-- (Stripe, Vercel, Supabase, etc.) from the UI. Each row is project-scoped+-- and joined alongside the preset list in `getMcpCatalog`.+--+-- The `key` column carries the same identifier that mcp_tokens.server_name+-- uses, so the OAuth callback + token storage + adapter registration paths+-- work without changes.++CREATE TABLE IF NOT EXISTS user_mcp_servers (+ id TEXT PRIMARY KEY,+ project_slug TEXT NOT NULL REFERENCES projects(slug),+ key TEXT NOT NULL,+ display_name TEXT NOT NULL,+ description TEXT NOT NULL DEFAULT '',+ resource_url TEXT NOT NULL,+ discovery_url TEXT NOT NULL,+ created_at TEXT NOT NULL,+ updated_at TEXT NOT NULL,+ UNIQUE(project_slug, key)+);+CREATE INDEX IF NOT EXISTS idx_user_mcp_servers_project ON user_mcp_servers(project_slug);diff --git a/notfair-cmo/src/server/db/user-mcp-servers.test.ts b/notfair-cmo/src/server/db/user-mcp-servers.test.tsnew file mode 100644index 00000000..303eee3a--- /dev/null+++ b/notfair-cmo/src/server/db/user-mcp-servers.test.ts@@ -0,0 +1,135 @@+import Database from "better-sqlite3";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { MIGRATIONS } from "./migrations";++let testDb: Database.Database;++vi.mock("./db", () => ({+ getDb: () => testDb,+ getDbPath: () => ":memory:",+}));++import {+ insertUserMcpServer,+ findUserMcpServer,+ listUserMcpServers,+ deleteUserMcpServer,+} from "./user-mcp-servers";+import { createProject } from "./projects";++function makeProject(display_name: string) {+ const r = createProject({ display_name });+ if (!r.ok) throw new Error(`createProject failed: ${r.reason}`);+ return r.project;+}++function createDb(): Database.Database {+ const db = new Database(":memory:");+ db.pragma("foreign_keys = ON");+ for (const m of MIGRATIONS) db.exec(m.sql);+ return db;+}++beforeEach(() => {+ testDb = createDb();+});++afterEach(() => {+ testDb.close();+});++describe("user_mcp_servers CRUD", () => {+ it("insertUserMcpServer + findUserMcpServer round-trips a row", () => {+ const project = makeProject("Acme Co");+ const row = insertUserMcpServer({+ project_slug: project.slug,+ key: "stripe",+ display_name: "Stripe",+ description: "Payments",+ resource_url: "https://mcp.stripe.com/",+ discovery_url:+ "https://mcp.stripe.com/.well-known/oauth-protected-resource",+ });+ expect(row.id).toBeTruthy();+ expect(row.created_at).toBe(row.updated_at);++ const hit = findUserMcpServer(project.slug, "stripe");+ expect(hit?.display_name).toBe("Stripe");+ expect(hit?.resource_url).toBe("https://mcp.stripe.com/");+ });++ it("findUserMcpServer returns null for unknown rows", () => {+ const project = makeProject("Acme Co");+ expect(findUserMcpServer(project.slug, "nope")).toBeNull();+ });++ it("listUserMcpServers filters by project", () => {+ const a = makeProject("Acme A");+ const b = makeProject("Acme B");+ insertUserMcpServer({+ project_slug: a.slug,+ key: "stripe",+ display_name: "Stripe",+ resource_url: "https://mcp.stripe.com/",+ discovery_url: "https://mcp.stripe.com/.well-known/oauth-protected-resource",+ });+ insertUserMcpServer({+ project_slug: b.slug,+ key: "vercel",+ display_name: "Vercel",+ resource_url: "https://mcp.vercel.com/",+ discovery_url: "https://mcp.vercel.com/.well-known/oauth-protected-resource",+ });+ expect(listUserMcpServers(a.slug)).toHaveLength(1);+ expect(listUserMcpServers(b.slug)).toHaveLength(1);+ expect(listUserMcpServers(a.slug)[0]?.key).toBe("stripe");+ });++ it("(project_slug, key) is unique", () => {+ const project = makeProject("Acme Co");+ insertUserMcpServer({+ project_slug: project.slug,+ key: "stripe",+ display_name: "Stripe",+ resource_url: "https://mcp.stripe.com/",+ discovery_url: "https://mcp.stripe.com/.well-known/oauth-protected-resource",+ });+ expect(() =>+ insertUserMcpServer({+ project_slug: project.slug,+ key: "stripe",+ display_name: "Stripe v2",+ resource_url: "https://mcp.stripe.com/v2",+ discovery_url:+ "https://mcp.stripe.com/.well-known/oauth-protected-resource/v2",+ }),+ ).toThrow(/UNIQUE constraint/);+ });++ it("deleteUserMcpServer removes the row", () => {+ const project = makeProject("Acme Co");+ insertUserMcpServer({+ project_slug: project.slug,+ key: "stripe",+ display_name: "Stripe",+ resource_url: "https://mcp.stripe.com/",+ discovery_url: "https://mcp.stripe.com/.well-known/oauth-protected-resource",+ });+ deleteUserMcpServer(project.slug, "stripe");+ expect(findUserMcpServer(project.slug, "stripe")).toBeNull();+ });++ it("FK rejects an insert against an unknown project", () => {+ expect(() =>+ insertUserMcpServer({+ project_slug: "ghost",+ key: "stripe",+ display_name: "Stripe",+ resource_url: "https://mcp.stripe.com/",+ discovery_url:+ "https://mcp.stripe.com/.well-known/oauth-protected-resource",+ }),+ ).toThrow(/FOREIGN KEY/);+ });+});diff --git a/notfair-cmo/src/server/db/user-mcp-servers.ts b/notfair-cmo/src/server/db/user-mcp-servers.tsnew file mode 100644index 00000000..2411d2cc--- /dev/null+++ b/notfair-cmo/src/server/db/user-mcp-servers.ts@@ -0,0 +1,93 @@+import { randomUUID } from "node:crypto";+import { getDb } from "@/server/db/db";++/**+ * Project-scoped storage for user-added MCP servers.+ *+ * Companion to `mcp_tokens` — the catalog row says "this MCP exists for+ * this project" (slug, name, URLs); the token row says "we have a bearer+ * for it." `getMcpCatalog` joins this table with the static preset list+ * so both surfaces render the same `McpSpec` shape.+ *+ * `key` is the same identifier used as `mcp_tokens.server_name`, so the+ * OAuth callback + adapter registration paths don't care whether the+ * MCP came from presets or this table.+ */+export interface UserMcpServer {+ id: string;+ project_slug: string;+ key: string;+ display_name: string;+ description: string;+ resource_url: string;+ discovery_url: string;+ created_at: string;+ updated_at: string;+}++export interface UpsertUserMcpServerInput {+ project_slug: string;+ key: string;+ display_name: string;+ description?: string;+ resource_url: string;+ discovery_url: string;+}++export function insertUserMcpServer(input: UpsertUserMcpServerInput): UserMcpServer {+ const now = new Date().toISOString();+ const row: UserMcpServer = {+ id: randomUUID(),+ project_slug: input.project_slug,+ key: input.key,+ display_name: input.display_name,+ description: input.description ?? "",+ resource_url: input.resource_url,+ discovery_url: input.discovery_url,+ created_at: now,+ updated_at: now,+ };+ getDb()+ .prepare(+ "INSERT INTO user_mcp_servers (id, project_slug, key, display_name, description, resource_url, discovery_url, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",+ )+ .run(+ row.id,+ row.project_slug,+ row.key,+ row.display_name,+ row.description,+ row.resource_url,+ row.discovery_url,+ row.created_at,+ row.updated_at,+ );+ return row;+}++export function findUserMcpServer(+ project_slug: string,+ key: string,+): UserMcpServer | null {+ return (+ (getDb()+ .prepare(+ "SELECT * FROM user_mcp_servers WHERE project_slug = ? AND key = ?",+ )+ .get(project_slug, key) as UserMcpServer | undefined) ?? null+ );+}++export function listUserMcpServers(project_slug: string): UserMcpServer[] {+ return getDb()+ .prepare(+ "SELECT * FROM user_mcp_servers WHERE project_slug = ? ORDER BY created_at",+ )+ .all(project_slug) as UserMcpServer[];+}++export function deleteUserMcpServer(project_slug: string, key: string): void {+ getDb()+ .prepare("DELETE FROM user_mcp_servers WHERE project_slug = ? AND key = ?")+ .run(project_slug, key);+}diff --git a/notfair-cmo/src/server/mcp-catalog.test.ts b/notfair-cmo/src/server/mcp-catalog.test.tsindex 0cbf7157..ffb06ca3 100644--- a/notfair-cmo/src/server/mcp-catalog.test.ts+++ b/notfair-cmo/src/server/mcp-catalog.test.ts@@ -1,14 +1,53 @@-import { describe, expect, it } from "vitest";+import Database from "better-sqlite3";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { MCP_CATALOG, mcpSpecByKey } from "./mcp-catalog";+import { MIGRATIONS } from "./db/migrations";-describe("MCP_CATALOG", () => {- it("contains at least one spec", () => {- expect(MCP_CATALOG.length).toBeGreaterThan(0);+let testDb: Database.Database;++vi.mock("./db/db", () => ({+ getDb: () => testDb,+ getDbPath: () => ":memory:",+}));++import {+ MCP_CATALOG_PRESETS,+ getMcpCatalog,+ getMcpPresets,+ isPresetKey,+ mcpSpecByKey,+} from "./mcp-catalog";+import { createProject } from "./db/projects";+import { insertUserMcpServer } from "./db/user-mcp-servers";++function createDb(): Database.Database {+ const db = new Database(":memory:");+ db.pragma("foreign_keys = ON");+ for (const m of MIGRATIONS) db.exec(m.sql);+ return db;+}++function makeProject(display_name: string) {+ const r = createProject({ display_name });+ if (!r.ok) throw new Error(`createProject failed: ${r.reason}`);+ return r.project;+}++beforeEach(() => {+ testDb = createDb();+});++afterEach(() => {+ testDb.close();+});++describe("MCP_CATALOG_PRESETS", () => {+ it("contains at least one preset", () => {+ expect(MCP_CATALOG_PRESETS.length).toBeGreaterThan(0);});- it("includes the notfair-googleads spec with all required fields", () => {- const ga = MCP_CATALOG.find((m) => m.key === "notfair-googleads");+ it("includes the notfair-googleads preset with all required fields", () => {+ const ga = MCP_CATALOG_PRESETS.find((m) => m.key === "notfair-googleads");expect(ga).toBeDefined();expect(ga).toMatchObject({key: "notfair-googleads",@@ -16,44 +55,130 @@ describe("MCP_CATALOG", () => {description: expect.any(String),resource_url: expect.stringMatching(/^https:\/\//),discovery_url: expect.stringMatching(/^https:\/\//),+ source: "preset",});});- it("every spec has all required fields populated", () => {- for (const spec of MCP_CATALOG) {- expect(typeof spec.key).toBe("string");- expect(spec.key.length).toBeGreaterThan(0);- expect(typeof spec.display_name).toBe("string");- expect(typeof spec.description).toBe("string");- expect(typeof spec.resource_url).toBe("string");- expect(typeof spec.discovery_url).toBe("string");+ it("every preset is tagged source: 'preset' with required fields", () => {+ for (const spec of MCP_CATALOG_PRESETS) {+ expect(spec.source).toBe("preset");+ expect(spec.key).toMatch(/^[a-z0-9][a-z0-9-]*$/);+ expect(spec.resource_url).toMatch(/^https?:\/\//);+ expect(spec.discovery_url).toMatch(/^https?:\/\//);}});- it("every spec key is unique", () => {- const keys = MCP_CATALOG.map((m) => m.key);- const uniq = new Set(keys);- expect(uniq.size).toBe(keys.length);+ it("every preset key is unique", () => {+ const keys = MCP_CATALOG_PRESETS.map((m) => m.key);+ expect(new Set(keys).size).toBe(keys.length);+ });+});++describe("isPresetKey", () => {+ it("returns true for preset keys", () => {+ expect(isPresetKey("notfair-googleads")).toBe(true);+ });++ it("returns false for unknown keys", () => {+ expect(isPresetKey("stripe")).toBe(false);+ expect(isPresetKey("")).toBe(false);+ });+});++describe("getMcpCatalog", () => {+ it("returns presets when the project has no user rows", () => {+ const project = makeProject("Acme Co");+ const catalog = getMcpCatalog(project.slug);+ expect(catalog).toHaveLength(MCP_CATALOG_PRESETS.length);+ expect(catalog.every((s) => s.source === "preset")).toBe(true);+ });++ it("appends user-added rows tagged source: 'user' after presets", () => {+ const project = makeProject("Acme Co");+ insertUserMcpServer({+ project_slug: project.slug,+ key: "stripe",+ display_name: "Stripe",+ description: "Payments",+ resource_url: "https://mcp.stripe.com/",+ discovery_url:+ "https://mcp.stripe.com/.well-known/oauth-protected-resource",+ });+ const catalog = getMcpCatalog(project.slug);+ expect(catalog).toHaveLength(MCP_CATALOG_PRESETS.length + 1);+ const stripe = catalog.find((s) => s.key === "stripe");+ expect(stripe?.source).toBe("user");+ expect(catalog[catalog.length - 1]?.key).toBe("stripe");+ });++ it("does not leak user rows from one project to another", () => {+ const a = makeProject("Acme A");+ const b = makeProject("Acme B");+ insertUserMcpServer({+ project_slug: a.slug,+ key: "stripe",+ display_name: "Stripe",+ resource_url: "https://mcp.stripe.com/",+ discovery_url: "https://mcp.stripe.com/.well-known/oauth-protected-resource",+ });+ expect(getMcpCatalog(a.slug).map((s) => s.key)).toContain("stripe");+ expect(getMcpCatalog(b.slug).map((s) => s.key)).not.toContain("stripe");+ });++ it("filters out user rows that collide with a preset key", () => {+ const project = makeProject("Acme Co");+ insertUserMcpServer({+ project_slug: project.slug,+ key: "notfair-googleads",+ display_name: "Bogus shadow",+ resource_url: "https://evil.example/",+ discovery_url:+ "https://evil.example/.well-known/oauth-protected-resource",+ });+ const ga = getMcpCatalog(project.slug).filter(+ (s) => s.key === "notfair-googleads",+ );+ expect(ga).toHaveLength(1);+ expect(ga[0]?.source).toBe("preset");});});describe("mcpSpecByKey", () => {- it("returns the spec when key matches", () => {- const spec = mcpSpecByKey("notfair-googleads");- expect(spec).toBeDefined();+ it("returns the preset when key matches", () => {+ const project = makeProject("Acme Co");+ const spec = mcpSpecByKey(project.slug, "notfair-googleads");expect(spec?.key).toBe("notfair-googleads");+ expect(spec?.source).toBe("preset");});- it("returns undefined for an unknown key", () => {- expect(mcpSpecByKey("does-not-exist")).toBeUndefined();+ it("returns a user-added spec when key matches", () => {+ const project = makeProject("Acme Co");+ insertUserMcpServer({+ project_slug: project.slug,+ key: "stripe",+ display_name: "Stripe",+ resource_url: "https://mcp.stripe.com/",+ discovery_url: "https://mcp.stripe.com/.well-known/oauth-protected-resource",+ });+ const spec = mcpSpecByKey(project.slug, "stripe");+ expect(spec?.source).toBe("user");+ expect(spec?.display_name).toBe("Stripe");});- it("returns undefined for an empty key", () => {- expect(mcpSpecByKey("")).toBeUndefined();+ it("returns undefined for unknown / empty keys", () => {+ const project = makeProject("Acme Co");+ expect(mcpSpecByKey(project.slug, "does-not-exist")).toBeUndefined();+ expect(mcpSpecByKey(project.slug, "")).toBeUndefined();});- it("is case-sensitive — uppercase variant does not match", () => {- expect(mcpSpecByKey("NOTFAIR-GOOGLEADS")).toBeUndefined();+ it("is case-sensitive", () => {+ const project = makeProject("Acme Co");+ expect(mcpSpecByKey(project.slug, "NOTFAIR-GOOGLEADS")).toBeUndefined();});});+describe("getMcpPresets", () => {+ it("returns the preset list", () => {+ expect(getMcpPresets()).toEqual(MCP_CATALOG_PRESETS);+ });+});diff --git a/notfair-cmo/src/server/mcp-catalog.ts b/notfair-cmo/src/server/mcp-catalog.tsindex b8197d8b..15a028fb 100644--- a/notfair-cmo/src/server/mcp-catalog.ts+++ b/notfair-cmo/src/server/mcp-catalog.ts@@ -1,18 +1,24 @@/**- * Static catalog of MCP servers the notfair-cmo UI knows how to connect.+ * Project-scoped catalog of MCP servers the notfair-cmo UI knows about.*- * "Known" means we have a stable URL + OAuth discovery doc the server-side- * connect flow can drive end-to-end with zero LLM in the loop. Arbitrary- * MCPs (user describes one in chat) still go through the agent — the- * catalog is just the fast path for the ones we ship with.+ * Two sources merge into one list:*- * MCPs are managed at the project level (the Connections page). Tokens live- * in the `mcp_tokens` SQLite table, scoped by (project_slug, server_name).- * Per-agent visibility is enforced by the harness adapter's `registerMcp`- * hook, which writes the chosen agent's MCP config to point at the right- * token row.+ * - Static **presets** (this file): curated entries we ship with —+ * server URL + OAuth discovery doc are stable, so the connect flow+ * can drive end-to-end with zero LLM in the loop.+ * - **User-added** servers (`user_mcp_servers` SQLite table): anything+ * the user registers from the Connections page. Same `McpSpec` shape;+ * distinguished by `source: 'user'` so the UI can offer a "Remove"+ * action.+ *+ * Everything downstream of the catalog (OAuth callback, token storage in+ * `mcp_tokens`, harness adapter `registerMcp`) is keyed off `spec.key`,+ * which doubles as `mcp_tokens.server_name`. So both kinds of entries+ * flow through the same code paths once registered.*/+import { listUserMcpServers } from "@/server/db/user-mcp-servers";+export type McpSpec = {/** Stable catalog identifier (used by the UI + mcp_tokens.server_name). */key: string;@@ -22,9 +28,11 @@ export type McpSpec = {resource_url: string;/** RFC 9728 protected-resource discovery endpoint. */discovery_url: string;+ /** Where this entry came from — presets are immutable from the UI. */+ source: "preset" | "user";};-export const MCP_CATALOG: McpSpec[] = [+export const MCP_CATALOG_PRESETS: McpSpec[] = [{key: "notfair-googleads",display_name: "NotFair Google Ads",@@ -33,9 +41,43 @@ export const MCP_CATALOG: McpSpec[] = [resource_url: "https://notfair.co/api/mcp/google_ads",discovery_url:"https://notfair.co/.well-known/oauth-protected-resource/api/mcp/google_ads",+ source: "preset",},];-export function mcpSpecByKey(key: string): McpSpec | undefined {- return MCP_CATALOG.find((m) => m.key === key);+/** True if any preset reserves this key. Presets win over user rows. */+export function isPresetKey(key: string): boolean {+ return MCP_CATALOG_PRESETS.some((p) => p.key === key);+}++export function getMcpPresets(): McpSpec[] {+ return MCP_CATALOG_PRESETS;+}++/**+ * Return the merged catalog for a project: presets first, then user-added+ * rows. A preset key shadows any colliding user row (which the add-server+ * action prevents at insert time, but we double-check on read too).+ */+export function getMcpCatalog(project_slug: string): McpSpec[] {+ const presets = MCP_CATALOG_PRESETS;+ const presetKeys = new Set(presets.map((p) => p.key));+ const userRows = listUserMcpServers(project_slug)+ .filter((row) => !presetKeys.has(row.key))+ .map<McpSpec>((row) => ({+ key: row.key,+ display_name: row.display_name,+ description: row.description,+ resource_url: row.resource_url,+ discovery_url: row.discovery_url,+ source: "user",+ }));+ return [...presets, ...userRows];+}++export function mcpSpecByKey(+ project_slug: string,+ key: string,+): McpSpec | undefined {+ return getMcpCatalog(project_slug).find((m) => m.key === key);}diff --git a/notfair-cmo/src/server/mcp-server/registration.ts b/notfair-cmo/src/server/mcp-server/registration.tsindex b2f81272..a2009af4 100644--- a/notfair-cmo/src/server/mcp-server/registration.ts+++ b/notfair-cmo/src/server/mcp-server/registration.ts@@ -78,7 +78,7 @@ export async function registerCatalogMcpForAgent(catalog_key: string,agent_id: string,): Promise<InstallResult> {- const spec = mcpSpecByKey(catalog_key);+ const spec = mcpSpecByKey(project_slug, catalog_key);if (!spec) {return {ok: false,diff --git a/notfair-cmo/src/server/mcp/discovery-url.test.ts b/notfair-cmo/src/server/mcp/discovery-url.test.tsnew file mode 100644index 00000000..25de40b7--- /dev/null+++ b/notfair-cmo/src/server/mcp/discovery-url.test.ts@@ -0,0 +1,59 @@+import { describe, expect, it } from "vitest";++import { deriveDiscoveryUrl } from "./discovery-url";++describe("deriveDiscoveryUrl", () => {+ it("inserts the well-known suffix between origin and path", () => {+ expect(deriveDiscoveryUrl("https://notfair.co/api/mcp/google_ads")).toBe(+ "https://notfair.co/.well-known/oauth-protected-resource/api/mcp/google_ads",+ );+ });++ it("handles path-less origins (trailing /)", () => {+ expect(deriveDiscoveryUrl("https://mcp.stripe.com/")).toBe(+ "https://mcp.stripe.com/.well-known/oauth-protected-resource",+ );+ });++ it("handles bare origins (no path)", () => {+ expect(deriveDiscoveryUrl("https://mcp.stripe.com")).toBe(+ "https://mcp.stripe.com/.well-known/oauth-protected-resource",+ );+ });++ it("strips trailing slashes from the resource path", () => {+ expect(deriveDiscoveryUrl("https://example.com/api/v1/")).toBe(+ "https://example.com/.well-known/oauth-protected-resource/api/v1",+ );+ });++ it("strips multiple trailing slashes", () => {+ expect(deriveDiscoveryUrl("https://example.com/api///")).toBe(+ "https://example.com/.well-known/oauth-protected-resource/api",+ );+ });++ it("preserves non-default ports", () => {+ expect(deriveDiscoveryUrl("https://example.com:8443/mcp")).toBe(+ "https://example.com:8443/.well-known/oauth-protected-resource/mcp",+ );+ });++ it("accepts http origins (for local dev)", () => {+ expect(deriveDiscoveryUrl("http://localhost:3326/api/mcp")).toBe(+ "http://localhost:3326/.well-known/oauth-protected-resource/api/mcp",+ );+ });++ it("returns null for malformed URLs", () => {+ expect(deriveDiscoveryUrl("")).toBeNull();+ expect(deriveDiscoveryUrl("not a url")).toBeNull();+ expect(deriveDiscoveryUrl("/api/mcp")).toBeNull();+ });++ it("rejects non-http(s) schemes", () => {+ expect(deriveDiscoveryUrl("ftp://example.com/mcp")).toBeNull();+ expect(deriveDiscoveryUrl("file:///tmp/mcp")).toBeNull();+ expect(deriveDiscoveryUrl("javascript:alert(1)")).toBeNull();+ });+});diff --git a/notfair-cmo/src/server/mcp/discovery-url.ts b/notfair-cmo/src/server/mcp/discovery-url.tsnew file mode 100644index 00000000..46cde053--- /dev/null+++ b/notfair-cmo/src/server/mcp/discovery-url.ts@@ -0,0 +1,21 @@+/**+ * Derive the RFC 9728 protected-resource discovery URL from a resource URL.+ *+ * Spec rule: the well-known suffix `.well-known/oauth-protected-resource`+ * is inserted between the origin and the resource path. For root-only+ * resources (path `/` or empty) the suffix sits directly under the origin+ * with no trailing path.+ *+ * Returns `null` for malformed input or non-HTTP(S) schemes.+ */+export function deriveDiscoveryUrl(resource_url: string): string | null {+ let u: URL;+ try {+ u = new URL(resource_url);+ } catch {+ return null;+ }+ if (u.protocol !== "https:" && u.protocol !== "http:") return null;+ const path = u.pathname === "/" ? "" : u.pathname.replace(/\/+$/, "");+ return `${u.origin}/.well-known/oauth-protected-resource${path}`;+}diff --git a/notfair-cmo/src/server/mcp/rpc.ts b/notfair-cmo/src/server/mcp/rpc.tsindex b4116026..5b3c090a 100644--- a/notfair-cmo/src/server/mcp/rpc.ts+++ b/notfair-cmo/src/server/mcp/rpc.ts@@ -42,7 +42,7 @@ export function readMcpConfigRow(project_slug: string,catalog_key: string,): McpConfigRow | null {- const spec = mcpSpecByKey(catalog_key);+ const spec = mcpSpecByKey(project_slug, catalog_key);if (!spec) return null;const token = findMcpToken(project_slug, catalog_key);if (!token) return { url: spec.resource_url };diff --git a/notfair-cmo/src/server/mcp/state.ts b/notfair-cmo/src/server/mcp/state.tsindex 228e1e10..fbb2f18a 100644--- a/notfair-cmo/src/server/mcp/state.ts+++ b/notfair-cmo/src/server/mcp/state.ts@@ -37,7 +37,7 @@ export async function getMcpStatus(project_slug: string,catalog_key: string,): Promise<McpRuntimeStatus> {- const spec = mcpSpecByKey(catalog_key);+ const spec = mcpSpecByKey(project_slug, catalog_key);if (!spec) return { state: "not_configured" };const token = findMcpToken(project_slug, catalog_key);if (!token) return { state: "not_configured" };