Skip to content

Open-source SEO, GEO, and marketing skills for AI agents.

feat(notfair-cmo): multi-MCP onboarding + per-MCP specialist agents (0.5.0)

Yuting Zhong1a2afbd17de8
diff --git a/notfair-cmo/CHANGELOG.md b/notfair-cmo/CHANGELOG.md
index e9bfae68..5c59d4dd 100644
--- a/notfair-cmo/CHANGELOG.md
+++ b/notfair-cmo/CHANGELOG.md
@@ -1,5 +1,17 @@
# notfair-cmo
+## 0.5.0 — 2026-06-03
+
+**Multi-MCP onboarding + per-MCP specialist agents.** The connect step in onboarding is now a four-tile picker: Google Ads, Meta Ads, Google Search Console, and a "More" overflow modal. Each recommended tile is OAuth-wired to its own NotFair MCP and, on successful connect, triggers provisioning of the matching specialist agent — `meta_ads` (Mia) and `gsc` (Sasha) join the existing `cmo` (Greg) and `google_ads` (Ana) templates. CMO is the only template that ships unconditionally; specialists are gated on the user actually connecting their MCP.
+
+After each OAuth callback the user lands back on the connect step so they can wire up the next tool. When a connected MCP exposes more than one account/property, the matching account picker (Meta `act_*` ad accounts, GSC `sc-domain:` / URL properties) auto-selects when only one is reachable and otherwise shows a Google-Ads-style picker. Selections persist as `projects.meta_ads_account_id` and `projects.gsc_property_id` (migration 015) so specialists always target the right entity.
+
+Skip → "Done adding MCPs — next step" once at least one MCP is wired. The setup screen still waits for `ensureProjectAgents` (CMO + any specialists provisioned by the connect-time hooks) before routing the user into the CMO task workspace.
+
+Agent pages now render a **"Connect <Platform> MCP"** blocker in place of the chat/tasks UI when a specialist's required MCP token is missing — both before initial connect and after a later disconnect. The predicate is colocated in `src/server/onboarding/agent-mcp-blocker.ts` for unit-test coverage; the card lives at `src/components/agent-mcp-blocker-card.tsx`.
+
+The trusted-connectors registry promotes Meta Ads and Google Search Console to first-class `MCP_CATALOG_PRESETS` so they're always visible on the Connections page even when not yet connected. The "More" modal on the onboarding step hides the recommended trio (they have first-class tiles already) via a new `hideKeys` prop on `BrowseConnectorsDialog`. **Heads-up:** the GSC MCP listing tool is best-guessed as `listSites` (Search Console API's native term); if the deployed MCP uses a different method name, swap the `GSC_LIST_TOOL` constant in `src/server/onboarding/accounts.ts` — the failure surface is a clean "method not found" RPC error.
+
## 0.4.4 — 2026-06-03
**Cron jobs actually run now.** The Crons calendar was rendering future occurrences from the cron expression and creating `scheduled_jobs` rows, but the tick loop that actually dispatches due jobs was never starting. `ensureSchedulerRunning()` was defined in `src/server/scheduler/tick.ts` and imported from nowhere — no layout, no instrumentation, no CLI. Net effect: clicking a past occurrence on the calendar showed no status badge and the Result section had nothing to render, because `scheduled_job_runs` stayed empty forever.
diff --git a/notfair-cmo/package.json b/notfair-cmo/package.json
index 99cc4142..417dad11 100644
--- a/notfair-cmo/package.json
+++ b/notfair-cmo/package.json
@@ -1,6 +1,6 @@
{
"name": "notfair-cmo",
- "version": "0.4.4",
+ "version": "0.5.0",
"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]/activity/page.tsx b/notfair-cmo/src/app/(app)/[project]/activity/page.tsx
index 2778cf13..89acbfe5 100644
--- a/notfair-cmo/src/app/(app)/[project]/activity/page.tsx
+++ b/notfair-cmo/src/app/(app)/[project]/activity/page.tsx
@@ -27,7 +27,7 @@ export default async function ActivityPage({
<header>
<h1 className="text-2xl font-semibold tracking-tight">Activity</h1>
<p className="text-sm text-muted-foreground">
- Project <span className="font-mono">{project.slug}</span> · {actions.length} actions ·
+ Workspace <span className="font-mono">{project.slug}</span> · {actions.length} actions ·
append-only audit log
</p>
</header>
diff --git a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/layout.tsx b/notfair-cmo/src/app/(app)/[project]/agents/[agent]/layout.tsx
index ea259904..e98bb9fa 100644
--- a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/layout.tsx
+++ b/notfair-cmo/src/app/(app)/[project]/agents/[agent]/layout.tsx
@@ -1,7 +1,9 @@
import { notFound } from "next/navigation";
import { getProject } from "@/server/db/projects";
import { resolveAgentBySlug } from "@/server/agent-meta";
+import { resolveAgentMcpBlocker } from "@/server/onboarding/agent-mcp-blocker";
import { AgentTabs } from "@/components/agent-tabs";
+import { AgentMcpBlockerCard } from "@/components/agent-mcp-blocker-card";
type Params = { agent: string; project: string };
@@ -18,6 +20,19 @@ export default async function AgentLayout({
const resolved = await resolveAgentBySlug(project.slug, agentSlug);
if (!resolved) notFound();
+ // Specialists whose required MCP isn't connected for this project
+ // render a "Connect <platform>" blocker in place of the chat/tasks UI.
+ // The tab strip is suppressed too — there's nothing actionable inside
+ // any of the tabs until the MCP is wired.
+ const blocker = resolveAgentMcpBlocker(project.slug, resolved.template_key);
+ if (blocker) {
+ return (
+ <div className="absolute inset-0 flex flex-col">
+ <AgentMcpBlockerCard projectSlug={projectSlug} blocker={blocker} />
+ </div>
+ );
+ }
+
return (
// Escape parent main's p-6 so the tab strip + content area can own the
// full viewport region. Children pick their own scroll/padding strategy.
diff --git a/notfair-cmo/src/app/(app)/[project]/agents/page.tsx b/notfair-cmo/src/app/(app)/[project]/agents/page.tsx
index cb3dcddb..693299bb 100644
--- a/notfair-cmo/src/app/(app)/[project]/agents/page.tsx
+++ b/notfair-cmo/src/app/(app)/[project]/agents/page.tsx
@@ -40,7 +40,7 @@ export default async function AgentsPage({
<div>
<h1 className="text-2xl font-semibold tracking-tight">Agents</h1>
<p className="text-sm text-muted-foreground">
- Project <span className="font-mono">{project.slug}</span> ·{" "}
+ Workspace <span className="font-mono">{project.slug}</span> ·{" "}
{projectAgents.length} agent
{projectAgents.length === 1 ? "" : "s"} · running on {project.harness_adapter === "codex-local" ? "Codex" : "Claude Code"}
</p>
diff --git a/notfair-cmo/src/app/(app)/[project]/connections/page.tsx b/notfair-cmo/src/app/(app)/[project]/connections/page.tsx
index 1b982b74..f21c6287 100644
--- a/notfair-cmo/src/app/(app)/[project]/connections/page.tsx
+++ b/notfair-cmo/src/app/(app)/[project]/connections/page.tsx
@@ -57,7 +57,7 @@ export default async function ConnectionsPage({
<div className="flex items-start justify-between gap-6">
<div className="min-w-0">
<p className="font-mono text-[11px] uppercase tracking-[0.18em] text-muted-foreground">
- Project · {project.display_name}
+ Workspace · {project.display_name}
</p>
<h1 className="mt-2 text-3xl font-semibold tracking-tight">
Connections
diff --git a/notfair-cmo/src/app/(app)/[project]/crons/page.tsx b/notfair-cmo/src/app/(app)/[project]/crons/page.tsx
index 79b2f2a4..f27db46f 100644
--- a/notfair-cmo/src/app/(app)/[project]/crons/page.tsx
+++ b/notfair-cmo/src/app/(app)/[project]/crons/page.tsx
@@ -107,7 +107,7 @@ export default async function CronsPage({
<div>
<h1 className="text-2xl font-semibold tracking-tight">Crons</h1>
<p className="text-sm text-muted-foreground">
- Project <span className="font-mono">{project.slug}</span> ·{" "}
+ Workspace <span className="font-mono">{project.slug}</span> ·{" "}
{totalActive} active{totalDisabled > 0 ? ` · ${totalDisabled} disabled` : ""}
</p>
</div>
diff --git a/notfair-cmo/src/app/(app)/[project]/page.tsx b/notfair-cmo/src/app/(app)/[project]/page.tsx
index 45e2d13e..2b112637 100644
--- a/notfair-cmo/src/app/(app)/[project]/page.tsx
+++ b/notfair-cmo/src/app/(app)/[project]/page.tsx
@@ -64,7 +64,7 @@ export default async function ProjectHomePage({
<div>
<h1 className="text-2xl font-semibold tracking-tight">{project.display_name}</h1>
<p className="text-sm text-muted-foreground">
- Project home · slug <span className="font-mono">{project.slug}</span>
+ Workspace home · slug <span className="font-mono">{project.slug}</span>
</p>
</div>
<Button asChild>
diff --git a/notfair-cmo/src/app/(app)/[project]/settings/page.tsx b/notfair-cmo/src/app/(app)/[project]/settings/page.tsx
index dfc09769..386c4fb1 100644
--- a/notfair-cmo/src/app/(app)/[project]/settings/page.tsx
+++ b/notfair-cmo/src/app/(app)/[project]/settings/page.tsx
@@ -17,7 +17,7 @@ export default async function SettingsPage({
<header>
<h1 className="text-2xl font-semibold tracking-tight">Settings</h1>
<p className="text-sm text-muted-foreground">
- Project <span className="font-mono">{project.slug}</span>
+ Workspace <span className="font-mono">{project.slug}</span>
</p>
</header>
diff --git a/notfair-cmo/src/app/(app)/projects/page.tsx b/notfair-cmo/src/app/(app)/projects/page.tsx
index da29e016..34621ade 100644
--- a/notfair-cmo/src/app/(app)/projects/page.tsx
+++ b/notfair-cmo/src/app/(app)/projects/page.tsx
@@ -11,18 +11,18 @@ export default function ProjectsListPage() {
<div className="space-y-4">
<div className="flex items-baseline justify-between">
<div>
- <h1 className="text-2xl font-semibold tracking-tight">Projects</h1>
+ <h1 className="text-2xl font-semibold tracking-tight">Workspaces</h1>
<p className="text-sm text-muted-foreground">{projects.length} total</p>
</div>
<Button asChild>
- <Link href="/onboarding">New project</Link>
+ <Link href="/onboarding">New workspace</Link>
</Button>
</div>
{projects.length === 0 ? (
<Card>
<CardContent className="py-12 text-center text-sm text-muted-foreground">
- No projects yet.{" "}
+ No workspaces yet.{" "}
<Link className="underline" href="/onboarding">
Create your first one
</Link>
diff --git a/notfair-cmo/src/app/api/mcp-oauth/callback/route.ts b/notfair-cmo/src/app/api/mcp-oauth/callback/route.ts
index 90bc42a3..e961ff33 100644
--- a/notfair-cmo/src/app/api/mcp-oauth/callback/route.ts
+++ b/notfair-cmo/src/app/api/mcp-oauth/callback/route.ts
@@ -147,9 +147,25 @@ export async function GET(request: Request) {
return NextResponse.redirect(back);
}
- // Token is stored — now wire it into every agent's harness config so
- // running agents actually see the MCP tool surface. Without this step
- // the Connections page reads "Connected" (because the probe finds the
+ // Token is stored — now provision the specialist agent that matches
+ // this MCP (when it's one of the recommended trio: notfair-googleads,
+ // notfair-metaads, notfair-googlesearchconsole). The agent must exist
+ // BEFORE we register the MCP for it: registerCatalogMcpForProject
+ // iterates the project's agents and writes one MCP entry per agent,
+ // so a fresh specialist needs to be on disk first or it gets skipped.
+ // No-op for non-specialist MCPs (Stripe, Supabase, …).
+ try {
+ const { provisionSpecialistForMcp } = await import(
+ "@/server/agent-templates"
+ );
+ await provisionSpecialistForMcp(pending.project_slug, pending.catalog_key);
+ } catch (err) {
+ console.error("[mcp-oauth] provisionSpecialistForMcp threw:", err);
+ }
+
+ // Wire the new token into every agent's harness config so running
+ // agents actually see the MCP tool surface. Without this step the
+ // Connections page reads "Connected" (because the probe finds the
// token) but Greg / Ana can't call any of the catalog's tools because
// the adapter config file was never updated.
try {
diff --git a/notfair-cmo/src/components/agent-mcp-blocker-card.tsx b/notfair-cmo/src/components/agent-mcp-blocker-card.tsx
new file mode 100644
index 00000000..17cf092b
--- /dev/null
+++ b/notfair-cmo/src/components/agent-mcp-blocker-card.tsx
@@ -0,0 +1,41 @@
+import Link from "next/link";
+import { Plug } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { projectHref } from "@/lib/project-href";
+import type { AgentMcpBlocker } from "@/server/onboarding/agent-mcp-blocker";
+
+/**
+ * Card rendered in place of the agent's chat/tasks UI when the agent's
+ * template requires an MCP that isn't connected for this project. Server-
+ * rendered — no client state. The "Connect now" button is just a link
+ * into the Connections page where the existing OAuth flow takes over.
+ */
+export function AgentMcpBlockerCard({
+ projectSlug,
+ blocker,
+}: {
+ projectSlug: string;
+ blocker: AgentMcpBlocker;
+}) {
+ return (
+ <div className="mx-auto flex h-full max-w-md flex-col items-center justify-center px-6 py-12 text-center">
+ <div className="flex size-12 items-center justify-center rounded-full bg-muted">
+ <Plug className="size-5 text-muted-foreground" aria-hidden />
+ </div>
+ <h1 className="mt-4 text-lg font-semibold tracking-tight">
+ Connect {blocker.mcp_display_name} to use this agent
+ </h1>
+ <p className="mt-2 text-sm text-muted-foreground">
+ The {blocker.agent_display_name} agent needs the{" "}
+ {blocker.mcp_display_name} MCP before it can run. Connecting takes a
+ single OAuth round-trip; we&rsquo;ll bring you back here when
+ it&rsquo;s done.
+ </p>
+ <Button asChild className="mt-6">
+ <Link href={projectHref(projectSlug, "/connections")}>
+ Connect {blocker.mcp_display_name}
+ </Link>
+ </Button>
+ </div>
+ );
+}
diff --git a/notfair-cmo/src/components/app-sidebar.tsx b/notfair-cmo/src/components/app-sidebar.tsx
index 4b86891b..4238fa72 100644
--- a/notfair-cmo/src/components/app-sidebar.tsx
+++ b/notfair-cmo/src/components/app-sidebar.tsx
@@ -101,7 +101,7 @@ export async function AppSidebar() {
{active && (
<SidebarGroup>
- <SidebarGroupLabel>Project</SidebarGroupLabel>
+ <SidebarGroupLabel>Workspace</SidebarGroupLabel>
<SidebarGroupContent>
<SidebarMenu>
{NAV.map((item) => (
diff --git a/notfair-cmo/src/components/browse-connectors-dialog.tsx b/notfair-cmo/src/components/browse-connectors-dialog.tsx
index 3eee9b47..f9a7f84f 100644
--- a/notfair-cmo/src/components/browse-connectors-dialog.tsx
+++ b/notfair-cmo/src/components/browse-connectors-dialog.tsx
@@ -31,6 +31,14 @@ type Props = {
/** Normalized resource URLs of connected entries — used to detect
* legacy rows whose key doesn't match the trusted-connector id. */
connectedResourceUrls?: string[];
+ /**
+ * Catalog keys to exclude entirely from the grid. Used by the
+ * onboarding connect step, which surfaces the three recommended
+ * MCPs (Google Ads, Meta Ads, GSC) as first-class tiles and only
+ * uses this dialog for the "More" overflow. Without this filter the
+ * dialog would render duplicates of the tiles the user already sees.
+ */
+ hideKeys?: string[];
};
/**
@@ -50,9 +58,14 @@ export function BrowseConnectorsDialog({
onOpenChange,
connectedKeys = [],
connectedResourceUrls = [],
+ hideKeys = [],
}: Props) {
const connectedKeySet = new Set(connectedKeys);
const connectedUrlSet = new Set(connectedResourceUrls);
+ const hideKeySet = new Set(hideKeys);
+ const visibleConnectors = TRUSTED_CONNECTORS.filter(
+ (c) => !hideKeySet.has(c.id),
+ );
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-2xl">
@@ -64,7 +77,7 @@ export function BrowseConnectorsDialog({
</DialogDescription>
</DialogHeader>
<div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
- {TRUSTED_CONNECTORS.map((c) => {
+ {visibleConnectors.map((c) => {
const alreadyConnected =
connectedKeySet.has(c.id) ||
connectedUrlSet.has(normalizeResourceUrl(c.resource_url));
diff --git a/notfair-cmo/src/components/danger-zone.test.tsx b/notfair-cmo/src/components/danger-zone.test.tsx
index a43a1d63..e9efbe73 100644
--- a/notfair-cmo/src/components/danger-zone.test.tsx
+++ b/notfair-cmo/src/components/danger-zone.test.tsx
@@ -67,11 +67,11 @@ afterEach(() => {
});
describe("DangerZone (project)", () => {
- it("renders the delete-project CTA card", () => {
+ it("renders the delete-workspace CTA card", () => {
render(<DangerZone projectSlug="alpha" projectName="Alpha" />);
- expect(screen.getByText("Delete this project")).toBeInTheDocument();
+ expect(screen.getByText("Delete this workspace")).toBeInTheDocument();
expect(
- screen.getByRole("button", { name: /delete project/i }),
+ screen.getByRole("button", { name: /delete workspace/i }),
).toBeInTheDocument();
});
@@ -80,7 +80,7 @@ describe("DangerZone (project)", () => {
() => new Promise(() => {}),
);
render(<DangerZone projectSlug="alpha" projectName="Alpha" />);
- fireEvent.click(screen.getByRole("button", { name: /delete project/i }));
+ fireEvent.click(screen.getByRole("button", { name: /delete workspace/i }));
expect(
await screen.findByText(/counting what will be removed/i),
).toBeInTheDocument();
@@ -89,7 +89,7 @@ describe("DangerZone (project)", () => {
it("shows summary stats and existing agents in the dialog", async () => {
getProjectDeletionSummaryAction.mockResolvedValue({ ok: true, data: summary });
render(<DangerZone projectSlug="alpha" projectName="Alpha" />);
- fireEvent.click(screen.getByRole("button", { name: /delete project/i }));
+ fireEvent.click(screen.getByRole("button", { name: /delete workspace/i }));
expect(await screen.findByText("3")).toBeInTheDocument();
expect(screen.getByText("Agents")).toBeInTheDocument();
expect(screen.getByText("Threads")).toBeInTheDocument();
@@ -107,7 +107,7 @@ describe("DangerZone (project)", () => {
error: "boom",
});
render(<DangerZone projectSlug="alpha" projectName="Alpha" />);
- fireEvent.click(screen.getByRole("button", { name: /delete project/i }));
+ fireEvent.click(screen.getByRole("button", { name: /delete workspace/i }));
expect(
await screen.findByText(/could not load deletion summary: boom/i),
).toBeInTheDocument();
@@ -125,7 +125,7 @@ describe("DangerZone (project)", () => {
},
});
render(<DangerZone projectSlug="alpha" projectName="Alpha" />);
- fireEvent.click(screen.getByRole("button", { name: /delete project/i }));
+ fireEvent.click(screen.getByRole("button", { name: /delete workspace/i }));
await screen.findByText("CMO");
fireEvent.click(screen.getByRole("button", { name: /delete forever/i }));
await waitFor(() =>
@@ -151,7 +151,7 @@ describe("DangerZone (project)", () => {
},
});
render(<DangerZone projectSlug="alpha" projectName="Alpha" />);
- fireEvent.click(screen.getByRole("button", { name: /delete project/i }));
+ fireEvent.click(screen.getByRole("button", { name: /delete workspace/i }));
await screen.findByText("CMO");
fireEvent.click(screen.getByRole("button", { name: /delete forever/i }));
await waitFor(() =>
@@ -163,7 +163,7 @@ describe("DangerZone (project)", () => {
getProjectDeletionSummaryAction.mockResolvedValue({ ok: true, data: summary });
deleteProjectAction.mockResolvedValue({ ok: false, error: "denied" });
render(<DangerZone projectSlug="alpha" projectName="Alpha" />);
- fireEvent.click(screen.getByRole("button", { name: /delete project/i }));
+ fireEvent.click(screen.getByRole("button", { name: /delete workspace/i }));
await screen.findByText("CMO");
fireEvent.click(screen.getByRole("button", { name: /delete forever/i }));
await waitFor(() => expect(toast.error).toHaveBeenCalledWith("denied"));
@@ -173,7 +173,7 @@ describe("DangerZone (project)", () => {
it("closes the dialog on Cancel", async () => {
getProjectDeletionSummaryAction.mockResolvedValue({ ok: true, data: summary });
render(<DangerZone projectSlug="alpha" projectName="Alpha" />);
- fireEvent.click(screen.getByRole("button", { name: /delete project/i }));
+ fireEvent.click(screen.getByRole("button", { name: /delete workspace/i }));
await screen.findByText("CMO");
fireEvent.click(screen.getByRole("button", { name: /cancel/i }));
await waitFor(() => expect(screen.queryByText("CMO")).not.toBeInTheDocument());
diff --git a/notfair-cmo/src/components/danger-zone.tsx b/notfair-cmo/src/components/danger-zone.tsx
index dce6b868..dc091d23 100644
--- a/notfair-cmo/src/components/danger-zone.tsx
+++ b/notfair-cmo/src/components/danger-zone.tsx
@@ -78,9 +78,9 @@ export function DangerZone({ projectSlug, projectName }: Props) {
<div className="flex items-start gap-3">
<AlertTriangle className="mt-0.5 size-4 shrink-0 text-destructive" />
<div className="min-w-0 flex-1">
- <h3 className="text-sm font-semibold text-destructive">Delete this project</h3>
+ <h3 className="text-sm font-semibold text-destructive">Delete this workspace</h3>
<p className="mt-0.5 text-xs text-muted-foreground">
- Removes all agents created for this project, every scheduled cron job, and
+ Removes all agents created for this workspace, every scheduled cron job, and
every thread of chat history. This cannot be undone.
</p>
</div>
@@ -92,7 +92,7 @@ export function DangerZone({ projectSlug, projectName }: Props) {
className="shrink-0"
>
<Trash2 className="mr-1.5 size-3.5" />
- Delete project
+ Delete workspace
</Button>
</div>
</div>
diff --git a/notfair-cmo/src/components/onboarding-flow.test.tsx b/notfair-cmo/src/components/onboarding-flow.test.tsx
index 34f83271..8ec0ee1b 100644
--- a/notfair-cmo/src/components/onboarding-flow.test.tsx
+++ b/notfair-cmo/src/components/onboarding-flow.test.tsx
@@ -9,6 +9,12 @@ const {
setOnboardingAccountAction,
getOnboardingTaskForSkipAction,
getProvisioningProgressAction,
+ getConnectStepStateAction,
+ listMetaAdsAccounts,
+ setOnboardingMetaAdsAccountAction,
+ listGscProperties,
+ setOnboardingGscPropertyAction,
+ addUserMcpServerAction,
routerPush,
routerReplace,
toastFns,
@@ -20,6 +26,12 @@ const {
setOnboardingAccountAction: vi.fn(),
getOnboardingTaskForSkipAction: vi.fn(),
getProvisioningProgressAction: vi.fn(),
+ getConnectStepStateAction: vi.fn(),
+ listMetaAdsAccounts: vi.fn(),
+ setOnboardingMetaAdsAccountAction: vi.fn(),
+ listGscProperties: vi.fn(),
+ setOnboardingGscPropertyAction: vi.fn(),
+ addUserMcpServerAction: vi.fn(),
routerPush: vi.fn(),
routerReplace: vi.fn(),
toastFns: {
@@ -36,6 +48,7 @@ vi.mock("@/server/actions/projects", () => ({
vi.mock("@/server/actions/mcp", () => ({
startMcpConnect: (...args: unknown[]) => startMcpConnect(...args),
+ addUserMcpServerAction: (...args: unknown[]) => addUserMcpServerAction(...args),
}));
vi.mock("@/server/onboarding/accounts", () => ({
@@ -46,6 +59,14 @@ vi.mock("@/server/onboarding/accounts", () => ({
getOnboardingTaskForSkipAction(...args),
getProvisioningProgressAction: (...args: unknown[]) =>
getProvisioningProgressAction(...args),
+ getConnectStepStateAction: (...args: unknown[]) =>
+ getConnectStepStateAction(...args),
+ listMetaAdsAccounts: (...args: unknown[]) => listMetaAdsAccounts(...args),
+ setOnboardingMetaAdsAccountAction: (...args: unknown[]) =>
+ setOnboardingMetaAdsAccountAction(...args),
+ listGscProperties: (...args: unknown[]) => listGscProperties(...args),
+ setOnboardingGscPropertyAction: (...args: unknown[]) =>
+ setOnboardingGscPropertyAction(...args),
}));
vi.mock("next/navigation", () => ({
@@ -90,11 +111,28 @@ beforeEach(() => {
setOnboardingAccountAction.mockReset();
getOnboardingTaskForSkipAction.mockReset();
getProvisioningProgressAction.mockReset();
+ getConnectStepStateAction.mockReset();
+ listMetaAdsAccounts.mockReset();
+ setOnboardingMetaAdsAccountAction.mockReset();
+ listGscProperties.mockReset();
+ setOnboardingGscPropertyAction.mockReset();
+ addUserMcpServerAction.mockReset();
routerPush.mockReset();
routerReplace.mockReset();
toastFns.success.mockReset();
toastFns.error.mockReset();
searchParamsRef.current = new URLSearchParams();
+ // Sensible default — connect-step renders need this to resolve.
+ getConnectStepStateAction.mockResolvedValue({
+ ok: true,
+ state: {
+ googleads: { connected: false, account_selected: false },
+ metaads: { connected: false, account_selected: false },
+ gsc: { connected: false, account_selected: false },
+ extra_connected_count: 0,
+ website_url: null,
+ },
+ });
});
afterEach(() => {
@@ -140,7 +178,7 @@ describe("OnboardingFlow — NameStep (default step)", () => {
it("renders an inline error alert when the server action returns ok=false", async () => {
createProjectForOnboardingAction.mockResolvedValue({
ok: false,
- error: "Please enter a project name.",
+ error: "Please enter a workspace name.",
});
render(<OnboardingFlow />);
fireEvent.change(screen.getByLabelText(/Name/i), {
@@ -148,7 +186,7 @@ describe("OnboardingFlow — NameStep (default step)", () => {
});
fireEvent.click(screen.getByRole("button", { name: /Continue/i }));
const alert = await screen.findByRole("alert");
- expect(alert).toHaveTextContent("Please enter a project name.");
+ expect(alert).toHaveTextContent("Please enter a workspace name.");
expect(routerPush).not.toHaveBeenCalled();
});
@@ -175,7 +213,7 @@ describe("OnboardingFlow — MissingSlug", () => {
setStep("connect", null);
render(<OnboardingFlow />);
expect(
- screen.getByText(/This step needs a project. Start from the beginning./i),
+ screen.getByText(/This step needs a workspace. Start from the beginning./i),
).toBeInTheDocument();
expect(
screen.getByRole("link", { name: /Start over/i }),
@@ -186,27 +224,36 @@ describe("OnboardingFlow — MissingSlug", () => {
setStep("account", null);
render(<OnboardingFlow />);
expect(
- screen.getByText(/This step needs a project. Start from the beginning./i),
+ screen.getByText(/This step needs a workspace. Start from the beginning./i),
).toBeInTheDocument();
});
});
describe("OnboardingFlow — ConnectStep", () => {
- it("renders the connect headline + Connect/Skip buttons", () => {
+ it("renders the three recommended-MCP tiles + Skip when nothing is connected", async () => {
setStep("connect", "acme");
render(<OnboardingFlow />);
expect(
- screen.getByRole("heading", { name: /Connect your Google Ads/i }),
+ await screen.findByRole("heading", { name: /Connect your tools/i }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: /^Google Ads/i }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: /^Meta Ads/i }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: /Google Search Console/i }),
).toBeInTheDocument();
expect(
- screen.getByRole("button", { name: /Connect Google Ads/i }),
+ screen.getByRole("button", { name: /More tools/i }),
).toBeInTheDocument();
expect(
- screen.getByRole("button", { name: /Skip Google Ads/i }),
+ screen.getByRole("button", { name: /Skip for now/i }),
).toBeInTheDocument();
});
- it("calls startMcpConnect with the onboarding return_to and redirects on success", async () => {
+ it("starts OAuth for Google Ads with a connect-step return_to", async () => {
const loc = setLocationHref();
startMcpConnect.mockResolvedValue({
ok: true,
@@ -214,7 +261,7 @@ describe("OnboardingFlow — ConnectStep", () => {
});
setStep("connect", "acme");
render(<OnboardingFlow />);
- fireEvent.click(screen.getByRole("button", { name: /Connect Google Ads/i }));
+ fireEvent.click(await screen.findByRole("button", { name: /^Google Ads/i }));
await waitFor(() =>
expect(startMcpConnect).toHaveBeenCalledWith({
mcp_key: "notfair-googleads",
@@ -226,36 +273,82 @@ describe("OnboardingFlow — ConnectStep", () => {
);
});
- it("toasts and re-enables the button when startMcpConnect returns ok=false", async () => {
+ it("toasts and re-enables the tile when startMcpConnect returns ok=false", async () => {
startMcpConnect.mockResolvedValue({ ok: false, error: "registration failed" });
setStep("connect", "acme");
render(<OnboardingFlow />);
- const btn = screen.getByRole("button", { name: /Connect Google Ads/i });
- fireEvent.click(btn);
+ const tile = await screen.findByRole("button", { name: /^Google Ads/i });
+ fireEvent.click(tile);
await waitFor(() =>
expect(toastFns.error).toHaveBeenCalledWith("registration failed"),
);
- expect(btn).not.toBeDisabled();
+ expect(tile).not.toBeDisabled();
});
it("toasts the thrown error when startMcpConnect throws", async () => {
startMcpConnect.mockRejectedValue(new Error("offline"));
setStep("connect", "acme");
render(<OnboardingFlow />);
- fireEvent.click(screen.getByRole("button", { name: /Connect Google Ads/i }));
+ fireEvent.click(await screen.findByRole("button", { name: /^Google Ads/i }));
await waitFor(() =>
expect(toastFns.error).toHaveBeenCalledWith("offline"),
);
});
- it("hands off to the setup screen when the user clicks Skip", () => {
+ it("hands off to the setup screen via Skip when zero MCPs are connected", async () => {
setStep("connect", "acme");
render(<OnboardingFlow />);
- fireEvent.click(screen.getByRole("button", { name: /Skip Google Ads/i }));
+ fireEvent.click(await screen.findByRole("button", { name: /Skip for now/i }));
expect(routerReplace).toHaveBeenCalledWith(
"/onboarding?step=setup&slug=acme&from=skip",
);
});
+
+ it("flips Skip → 'Done adding MCPs — next step' once at least one MCP is connected", async () => {
+ getConnectStepStateAction.mockResolvedValue({
+ ok: true,
+ state: {
+ googleads: { connected: true, account_selected: true },
+ metaads: { connected: false, account_selected: false },
+ gsc: { connected: false, account_selected: false },
+ extra_connected_count: 0,
+ website_url: null,
+ },
+ });
+ setStep("connect", "acme");
+ render(<OnboardingFlow />);
+ const done = await screen.findByRole("button", { name: /Done adding MCPs/i });
+ expect(done).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: /Skip for now/i }),
+ ).not.toBeInTheDocument();
+ fireEvent.click(done);
+ expect(routerReplace).toHaveBeenCalledWith(
+ "/onboarding?step=setup&slug=acme&from=connect",
+ );
+ });
+
+ it("shows a 'Select Google Ads account' sub-action when the MCP is connected but no account is picked", async () => {
+ getConnectStepStateAction.mockResolvedValue({
+ ok: true,
+ state: {
+ googleads: { connected: true, account_selected: false },
+ metaads: { connected: false, account_selected: false },
+ gsc: { connected: false, account_selected: false },
+ extra_connected_count: 0,
+ website_url: null,
+ },
+ });
+ setStep("connect", "acme");
+ render(<OnboardingFlow />);
+ const pick = await screen.findByRole("button", {
+ name: /Select Google Ads account/i,
+ });
+ fireEvent.click(pick);
+ expect(routerPush).toHaveBeenCalledWith(
+ "/onboarding?step=account&slug=acme",
+ );
+ });
});
describe("OnboardingFlow — SetupStep", () => {
@@ -406,7 +499,7 @@ describe("OnboardingFlow — AccountStep", () => {
);
});
- it("auto-selects the only account and replaces the URL with the task display id", async () => {
+ it("auto-selects the only account and routes back to the connect step", async () => {
listGoogleAdsAccounts.mockResolvedValue({
ok: true,
accounts: [{ id: "123-456-7890", name: "Solo Account" }],
@@ -425,7 +518,7 @@ describe("OnboardingFlow — AccountStep", () => {
);
await waitFor(() =>
expect(routerReplace).toHaveBeenCalledWith(
- "/acme/agents/cmo-greg/tasks?task=AUDIT-1",
+ "/onboarding?step=connect&slug=acme",
),
);
});
@@ -469,7 +562,7 @@ describe("OnboardingFlow — AccountStep", () => {
expect(screen.getByText(/Customer ID 222/)).toBeInTheDocument();
});
- it("picks the chosen account and replaces the URL with the task display id", async () => {
+ it("picks the chosen account and routes back to the connect step", async () => {
listGoogleAdsAccounts.mockResolvedValue({
ok: true,
accounts: [
@@ -495,7 +588,7 @@ describe("OnboardingFlow — AccountStep", () => {
);
await waitFor(() =>
expect(routerReplace).toHaveBeenCalledWith(
- "/acme/agents/cmo-greg/tasks?task=TASK-9",
+ "/onboarding?step=connect&slug=acme",
),
);
});
diff --git a/notfair-cmo/src/components/onboarding-flow.tsx b/notfair-cmo/src/components/onboarding-flow.tsx
index 1a956330..1049839c 100644
--- a/notfair-cmo/src/components/onboarding-flow.tsx
+++ b/notfair-cmo/src/components/onboarding-flow.tsx
@@ -19,10 +19,25 @@ import {
setOnboardingAccountAction,
getOnboardingTaskForSkipAction,
getProvisioningProgressAction,
+ getConnectStepStateAction,
+ listMetaAdsAccounts,
+ setOnboardingMetaAdsAccountAction,
+ listGscProperties,
+ setOnboardingGscPropertyAction,
type GoogleAdsAccount,
+ type MetaAdsAccount,
+ type GscProperty,
+ type ConnectStepState,
} from "@/server/onboarding/accounts";
+import { BrowseConnectorsDialog } from "@/components/browse-connectors-dialog";
-type Step = "name" | "connect" | "account" | "setup";
+type Step =
+ | "name"
+ | "connect"
+ | "account"
+ | "meta-account"
+ | "gsc-property"
+ | "setup";
export function OnboardingFlow() {
return (
@@ -38,7 +53,11 @@ function OnboardingFlowInner() {
const stepParam = params.get("step");
const slug = params.get("slug") ?? null;
const step: Step =
- stepParam === "connect" || stepParam === "account" || stepParam === "setup"
+ stepParam === "connect" ||
+ stepParam === "account" ||
+ stepParam === "meta-account" ||
+ stepParam === "gsc-property" ||
+ stepParam === "setup"
? stepParam
: "name";
@@ -60,10 +79,15 @@ function OnboardingFlowInner() {
)}
{step === "connect" && slug && <ConnectStep slug={slug} />}
{step === "account" && slug && <AccountStep slug={slug} />}
+ {step === "meta-account" && slug && <MetaAccountStep slug={slug} />}
+ {step === "gsc-property" && slug && <GscPropertyStep slug={slug} />}
{step === "setup" && slug && <SetupStep slug={slug} />}
- {(step === "connect" || step === "account" || step === "setup") && !slug && (
- <MissingSlug />
- )}
+ {(step === "connect" ||
+ step === "account" ||
+ step === "meta-account" ||
+ step === "gsc-property" ||
+ step === "setup") &&
+ !slug && <MissingSlug />}
</main>
</div>
);
@@ -157,13 +181,13 @@ function NameStep({ onCreated }: { onCreated: (slug: string) => void }) {
Let&rsquo;s set up your CMO.
</h1>
<p className="text-sm text-muted-foreground">
- Tell me what this project is so I can hit the ground running.
+ Tell me what this workspace is so I can hit the ground running.
</p>
</header>
<Card>
<CardHeader>
- <CardTitle className="text-base">Project basics</CardTitle>
+ <CardTitle className="text-base">Workspace basics</CardTitle>
<CardDescription>
Name is required. Site and codebase are optional but help the
CMO write a more accurate first plan. Slug (used in agent
@@ -173,13 +197,13 @@ function NameStep({ onCreated }: { onCreated: (slug: string) => void }) {
<CardContent>
<form action={formAction} className="space-y-4">
<div className="space-y-2">
- <Label htmlFor="display_name">Project name</Label>
+ <Label htmlFor="display_name">Workspace name</Label>
<Input
id="display_name"
name="display_name"
required
autoFocus
- placeholder="Acme Q4 launch"
+ placeholder="Notfair"
maxLength={80}
disabled={isPending}
/>
@@ -196,7 +220,7 @@ function NameStep({ onCreated }: { onCreated: (slug: string) => void }) {
id="website_url"
name="website_url"
type="url"
- placeholder="https://acme.com"
+ placeholder="https://notfair.co"
maxLength={500}
disabled={isPending}
/>
@@ -310,86 +334,335 @@ function HarnessPicker({ disabled }: { disabled: boolean }) {
// ── Step 2: Connect ────────────────────────────────────────────────
+/**
+ * Spec for one of the recommended-MCP tiles in the connect step. The three
+ * recommended MCPs (Google Ads, Meta Ads, Google Search Console) each get
+ * their own first-class tile because connecting them triggers the
+ * provisioning of a matching specialist agent.
+ */
+type RecommendedTile = {
+ mcp_key: string;
+ display_name: string;
+ /** Short description shown under the title when the tile isn't connected. */
+ description: string;
+ /** Sub-step the OAuth callback should land on so the user can pick an
+ * account/property when their token covers more than one. */
+ account_step: "account" | "meta-account" | "gsc-property";
+ /** Label for the "Select X" sub-action when connected but not selected. */
+ account_action_label: string;
+};
+
+const RECOMMENDED_TILES: RecommendedTile[] = [
+ {
+ mcp_key: "notfair-googleads",
+ display_name: "Google Ads",
+ description: "Campaigns, bids, keywords, search terms, change history.",
+ account_step: "account",
+ account_action_label: "Select Google Ads account",
+ },
+ {
+ mcp_key: "notfair-metaads",
+ display_name: "Meta Ads",
+ description: "Facebook + Instagram campaigns, ad sets, creative, insights.",
+ account_step: "meta-account",
+ account_action_label: "Select Meta ad account",
+ },
+ {
+ mcp_key: "notfair-googlesearchconsole",
+ display_name: "Google Search Console",
+ description: "Organic search performance, queries, pages, indexing.",
+ account_step: "gsc-property",
+ account_action_label: "Select GSC property",
+ },
+];
+
+type ConnectStepStateView =
+ | { phase: "loading" }
+ | { phase: "loaded"; state: ConnectStepState }
+ | { phase: "error"; message: string };
+
function ConnectStep({ slug }: { slug: string }) {
const router = useRouter();
- const [busy, setBusy] = useState(false);
+ const [view, setView] = useState<ConnectStepStateView>({ phase: "loading" });
+ const [moreOpen, setMoreOpen] = useState(false);
+ const [tileBusy, setTileBusy] = useState<string | null>(null);
+ const [advancing, setAdvancing] = useState(false);
const connectionsHref = projectHref(slug, "/connections");
- async function onConnect() {
- setBusy(true);
+ useEffect(() => {
+ let cancelled = false;
+ (async () => {
+ const result = await getConnectStepStateAction(slug);
+ if (cancelled) return;
+ if (!result.ok) {
+ setView({ phase: "error", message: result.error });
+ return;
+ }
+ setView({ phase: "loaded", state: result.state });
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [slug]);
+
+ async function onConnectTile(tile: RecommendedTile) {
+ setTileBusy(tile.mcp_key);
try {
const result = await startMcpConnect({
- mcp_key: "notfair-googleads",
- return_to: `/onboarding?step=account&slug=${encodeURIComponent(slug)}`,
+ mcp_key: tile.mcp_key,
+ // After OAuth lands, route through the matching account-picker
+ // step. That step auto-skips if the bearer covers a single
+ // account/property; otherwise it shows a picker. Both paths
+ // ultimately redirect back to /onboarding?step=connect so the
+ // user can continue adding tools.
+ return_to: `/onboarding?step=${tile.account_step}&slug=${encodeURIComponent(slug)}`,
});
if (!result.ok) {
toast.error(result.error);
- setBusy(false);
+ setTileBusy(null);
return;
}
- // Cross-origin redirect to the OAuth issuer.
window.location.href = result.authorize_url;
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err));
- setBusy(false);
+ setTileBusy(null);
}
}
+ function onPickAccount(tile: RecommendedTile) {
+ router.push(
+ `/onboarding?step=${tile.account_step}&slug=${encodeURIComponent(slug)}`,
+ );
+ }
+
+ async function onDone() {
+ setAdvancing(true);
+ // The setup step waits for ensureProjectAgents (CMO + any specialists
+ // provisioned by the connect-time hooks) and only then routes the user
+ // into the CMO task workspace. Going through it instead of the direct
+ // task URL means we don't race agent registration with the gateway
+ // snapshot on a fresh project.
+ router.replace(
+ `/onboarding?step=setup&slug=${encodeURIComponent(slug)}&from=connect`,
+ );
+ }
+
function onSkip() {
- // Hand off to the dedicated setup screen instead of redirecting
- // straight to the task. The setup screen waits for `ensureProjectAgents`
- // to finish (publishing per-template progress) and only then resolves
- // the CMO + first-task slugs and navigates the user in.
router.replace(
`/onboarding?step=setup&slug=${encodeURIComponent(slug)}&from=skip`,
);
}
+ if (view.phase === "loading") {
+ return (
+ <Card>
+ <CardContent className="space-y-2 pt-6 pb-6">
+ <div className="flex items-center gap-3 text-sm">
+ <Loader2 className="size-4 animate-spin text-muted-foreground" aria-hidden />
+ <span className="font-medium">Loading your connections&hellip;</span>
+ </div>
+ </CardContent>
+ </Card>
+ );
+ }
+
+ if (view.phase === "error") {
+ return (
+ <Card role="alert">
+ <CardContent className="space-y-3 pt-6 pb-6">
+ <div className="flex items-center gap-2">
+ <AlertCircle className="size-4 text-amber-600" aria-hidden />
+ <span className="font-medium text-sm">
+ Couldn&rsquo;t load connection state.
+ </span>
+ </div>
+ <p className="text-xs text-muted-foreground">{view.message}</p>
+ <Button asChild>
+ <Link href="/onboarding">Start over</Link>
+ </Button>
+ </CardContent>
+ </Card>
+ );
+ }
+
+ const { state } = view;
+ const tileStateByKey = {
+ "notfair-googleads": state.googleads,
+ "notfair-metaads": state.metaads,
+ "notfair-googlesearchconsole": state.gsc,
+ } as const;
+ const anyConnected =
+ state.googleads.connected ||
+ state.metaads.connected ||
+ state.gsc.connected ||
+ state.extra_connected_count > 0;
+
return (
<>
<header className="space-y-2">
<h1 className="text-3xl font-semibold tracking-tight text-foreground">
- Connect your Google Ads.
+ Connect your tools.
</h1>
<p className="text-sm text-muted-foreground">
- I&rsquo;ll read your account so I can show you what to fix. Read-only
- &mdash; I won&rsquo;t change anything yet.
+ Each tool you connect lets one of your specialist agents come
+ online. Read-only at first &mdash; nothing changes until you
+ approve a write.
</p>
</header>
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
+ {RECOMMENDED_TILES.map((tile) => (
+ <RecommendedConnectorTile
+ key={tile.mcp_key}
+ tile={tile}
+ state={tileStateByKey[tile.mcp_key as keyof typeof tileStateByKey]}
+ busy={tileBusy === tile.mcp_key}
+ disabled={tileBusy !== null && tileBusy !== tile.mcp_key}
+ onConnect={() => onConnectTile(tile)}
+ onPickAccount={() => onPickAccount(tile)}
+ />
+ ))}
+ <MoreConnectorsTile
+ extraConnectedCount={state.extra_connected_count}
+ onOpen={() => setMoreOpen(true)}
+ />
+ </div>
+
<Card>
- <CardContent className="space-y-4 pt-6">
- <div className="flex flex-wrap gap-2">
- <Button onClick={onConnect} disabled={busy} size="lg">
- {busy ? (
- <Loader2 className="mr-1.5 size-4 animate-spin" />
- ) : (
- <Plug className="mr-1.5 size-4" />
- )}
- Connect Google Ads
+ <CardContent className="flex flex-wrap items-center justify-between gap-3 pt-6 pb-6">
+ <p className="text-xs text-muted-foreground">
+ You can connect, disconnect, or add custom MCPs anytime in{" "}
+ <Link href={connectionsHref} className="underline underline-offset-2">
+ Connections
+ </Link>
+ .
+ </p>
+ {anyConnected ? (
+ <Button onClick={onDone} disabled={advancing} size="lg">
+ {advancing && <Loader2 className="mr-1.5 size-4 animate-spin" />}
+ Done adding MCPs &mdash; next step
</Button>
+ ) : (
<Button
onClick={onSkip}
variant="ghost"
- disabled={busy}
- aria-label="Skip Google Ads connection for now and go to CMO tasks"
+ disabled={advancing}
>
Skip for now
</Button>
- </div>
- <p className="text-xs text-muted-foreground">
- You can disconnect anytime in{" "}
- <Link href={connectionsHref} className="underline underline-offset-2">
- Connections
- </Link>
- .
- </p>
+ )}
</CardContent>
</Card>
+
+ <BrowseConnectorsDialog
+ open={moreOpen}
+ onOpenChange={setMoreOpen}
+ // Hide the three recommended MCPs — they each have their own tile
+ // above, so showing them in the More dialog would be a duplicate.
+ hideKeys={RECOMMENDED_TILES.map((t) => t.mcp_key)}
+ connectedKeys={[
+ ...(state.googleads.connected ? ["notfair-googleads"] : []),
+ ...(state.metaads.connected ? ["notfair-metaads"] : []),
+ ...(state.gsc.connected ? ["notfair-googlesearchconsole"] : []),
+ ]}
+ />
</>
);
}
+function RecommendedConnectorTile({
+ tile,
+ state,
+ busy,
+ disabled,
+ onConnect,
+ onPickAccount,
+}: {
+ tile: RecommendedTile;
+ state: { connected: boolean; account_selected: boolean };
+ busy: boolean;
+ disabled: boolean;
+ onConnect: () => void;
+ onPickAccount: () => void;
+}) {
+ if (state.connected) {
+ return (
+ <div className="flex flex-col gap-3 rounded-md border border-emerald-500/30 bg-emerald-500/5 p-4">
+ <div className="flex items-start gap-2">
+ <div className="size-2 mt-1.5 rounded-full bg-emerald-500" aria-hidden />
+ <div className="min-w-0 flex-1">
+ <p className="text-sm font-medium">{tile.display_name}</p>
+ <p className="mt-0.5 text-xs text-emerald-700 dark:text-emerald-400">
+ Connected
+ {state.account_selected ? " · account selected" : null}
+ </p>
+ </div>
+ </div>
+ {state.account_selected ? null : (
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ onClick={onPickAccount}
+ disabled={disabled}
+ className="self-start"
+ >
+ {tile.account_action_label}
+ </Button>
+ )}
+ </div>
+ );
+ }
+ return (
+ <button
+ type="button"
+ onClick={onConnect}
+ disabled={busy || disabled}
+ className="flex flex-col gap-2 rounded-md border border-border bg-card p-4 text-left transition-colors hover:bg-muted/40 disabled:cursor-not-allowed disabled:opacity-60"
+ >
+ <div className="flex items-center justify-between gap-2">
+ <p className="text-sm font-medium">{tile.display_name}</p>
+ {busy ? (
+ <Loader2 className="size-3.5 animate-spin text-muted-foreground" />
+ ) : (
+ <Plug className="size-3.5 text-muted-foreground" />
+ )}
+ </div>
+ <p className="text-xs text-muted-foreground line-clamp-2">
+ {tile.description}
+ </p>
+ </button>
+ );
+}
+
+function MoreConnectorsTile({
+ extraConnectedCount,
+ onOpen,
+}: {
+ extraConnectedCount: number;
+ onOpen: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onOpen}
+ className="flex flex-col gap-2 rounded-md border border-dashed border-border bg-card p-4 text-left transition-colors hover:bg-muted/40"
+ >
+ <div className="flex items-center justify-between gap-2">
+ <p className="text-sm font-medium">More tools</p>
+ {extraConnectedCount > 0 ? (
+ <span className="font-mono text-[10px] uppercase tracking-[0.14em] text-emerald-700 dark:text-emerald-400">
+ {extraConnectedCount} connected
+ </span>
+ ) : null}
+ </div>
+ <p className="text-xs text-muted-foreground line-clamp-2">
+ Stripe, Supabase, PostHog, and any custom MCP you want to wire up.
+ </p>
+ </button>
+ );
+}
+
// ── Step 2.5: Setup (post-skip-or-connect provisioning watcher) ────
type ProgressStep = {
@@ -597,14 +870,12 @@ function AccountStep({ slug }: { slug: string }) {
setState({ phase: "error", message: result.error });
return;
}
- // Land on the CMO's task workspace with the freshly-created audit
- // task pre-selected — startTaskIfProposed kicks it off, the user
- // watches it run live in the standard task UX.
+ // Back to the connect step so the user can wire up the rest of
+ // their tools. The CMO audit task is minted by
+ // setOnboardingAccountAction and stays blocked behind the
+ // project-onboarding task until the user clicks "Done — next step".
router.replace(
- projectHref(
- slug,
- `/agents/${result.cmo_agent_slug}/tasks?task=${encodeURIComponent(result.task_display_id)}`,
- ),
+ `/onboarding?step=connect&slug=${encodeURIComponent(slug)}`,
);
})();
}, [state, slug, router]);
@@ -619,10 +890,7 @@ function AccountStep({ slug }: { slug: string }) {
return;
}
router.replace(
- projectHref(
- slug,
- `/agents/${result.cmo_agent_slug}/tasks?task=${encodeURIComponent(result.task_display_id)}`,
- ),
+ `/onboarding?step=connect&slug=${encodeURIComponent(slug)}`,
);
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err));
@@ -722,7 +990,7 @@ function AccountStep({ slug }: { slug: string }) {
</h1>
<p className="text-sm text-muted-foreground">
Your connection has {state.accounts.length} accounts. Pick the one
- you want me to audit for this project. You can switch later in
+ you want me to audit for this workspace. You can switch later in
Settings.
</p>
</header>
@@ -776,12 +1044,368 @@ function AccountStep({ slug }: { slug: string }) {
);
}
+// ── Step 3b: Pick Meta Ads ad-account (auto-skipped if only 1) ─────
+//
+// Mirrors AccountStep but for the notfair-metaads MCP. Lands the user
+// back on the connect step after picking so they can wire up another
+// MCP or finish onboarding.
+
+type MetaListState =
+ | { phase: "loading" }
+ | { phase: "loaded"; accounts: MetaAdsAccount[]; default_account_id: string | null }
+ | { phase: "error"; message: string };
+
+function MetaAccountStep({ slug }: { slug: string }) {
+ const router = useRouter();
+ const [state, setState] = useState<MetaListState>({ phase: "loading" });
+ const [pickingId, setPickingId] = useState<string | null>(null);
+ const autoSelectedRef = useRef(false);
+
+ useEffect(() => {
+ let cancelled = false;
+ (async () => {
+ const result = await listMetaAdsAccounts(slug);
+ if (cancelled) return;
+ if (!result.ok) {
+ setState({ phase: "error", message: result.error });
+ return;
+ }
+ setState({
+ phase: "loaded",
+ accounts: result.accounts,
+ default_account_id: result.default_account_id,
+ });
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [slug]);
+
+ useEffect(() => {
+ if (state.phase !== "loaded") return;
+ if (state.accounts.length !== 1) return;
+ if (autoSelectedRef.current) return;
+ autoSelectedRef.current = true;
+ (async () => {
+ const only = state.accounts[0]!;
+ const result = await setOnboardingMetaAdsAccountAction(slug, only.id);
+ if (!result.ok) {
+ toast.error(result.error);
+ setState({ phase: "error", message: result.error });
+ return;
+ }
+ router.replace(
+ `/onboarding?step=connect&slug=${encodeURIComponent(slug)}`,
+ );
+ })();
+ }, [state, slug, router]);
+
+ async function onPick(account: MetaAdsAccount) {
+ setPickingId(account.id);
+ try {
+ const result = await setOnboardingMetaAdsAccountAction(slug, account.id);
+ if (!result.ok) {
+ toast.error(result.error);
+ setPickingId(null);
+ return;
+ }
+ router.replace(
+ `/onboarding?step=connect&slug=${encodeURIComponent(slug)}`,
+ );
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : String(err));
+ setPickingId(null);
+ }
+ }
+
+ return (
+ <AccountPickerScaffold
+ slug={slug}
+ mcpDisplayName="Meta Ads"
+ idLabel="Ad account ID"
+ state={
+ state.phase === "loading"
+ ? { phase: "loading" }
+ : state.phase === "error"
+ ? { phase: "error", message: state.message }
+ : {
+ phase: "loaded",
+ items: state.accounts.map((a) => ({
+ id: a.id,
+ name: a.name,
+ isDefault: a.id === state.default_account_id,
+ isPicking: pickingId === a.id,
+ })),
+ anyPicking: pickingId !== null,
+ }
+ }
+ onPick={(id) => {
+ const a = state.phase === "loaded" ? state.accounts.find((x) => x.id === id) : null;
+ if (a) onPick(a);
+ }}
+ />
+ );
+}
+
+// ── Step 3c: Pick Google Search Console property (auto-skipped if only 1) ──
+
+type GscListState =
+ | { phase: "loading" }
+ | { phase: "loaded"; properties: GscProperty[]; default_property_id: string | null }
+ | { phase: "error"; message: string };
+
+function GscPropertyStep({ slug }: { slug: string }) {
+ const router = useRouter();
+ const [state, setState] = useState<GscListState>({ phase: "loading" });
+ const [pickingId, setPickingId] = useState<string | null>(null);
+ const autoSelectedRef = useRef(false);
+
+ useEffect(() => {
+ let cancelled = false;
+ (async () => {
+ const result = await listGscProperties(slug);
+ if (cancelled) return;
+ if (!result.ok) {
+ setState({ phase: "error", message: result.error });
+ return;
+ }
+ setState({
+ phase: "loaded",
+ properties: result.properties,
+ default_property_id: result.default_property_id,
+ });
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [slug]);
+
+ useEffect(() => {
+ if (state.phase !== "loaded") return;
+ if (state.properties.length !== 1) return;
+ if (autoSelectedRef.current) return;
+ autoSelectedRef.current = true;
+ (async () => {
+ const only = state.properties[0]!;
+ const result = await setOnboardingGscPropertyAction(slug, only.id);
+ if (!result.ok) {
+ toast.error(result.error);
+ setState({ phase: "error", message: result.error });
+ return;
+ }
+ router.replace(
+ `/onboarding?step=connect&slug=${encodeURIComponent(slug)}`,
+ );
+ })();
+ }, [state, slug, router]);
+
+ async function onPick(property: GscProperty) {
+ setPickingId(property.id);
+ try {
+ const result = await setOnboardingGscPropertyAction(slug, property.id);
+ if (!result.ok) {
+ toast.error(result.error);
+ setPickingId(null);
+ return;
+ }
+ router.replace(
+ `/onboarding?step=connect&slug=${encodeURIComponent(slug)}`,
+ );
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : String(err));
+ setPickingId(null);
+ }
+ }
+
+ return (
+ <AccountPickerScaffold
+ slug={slug}
+ mcpDisplayName="Google Search Console"
+ idLabel="Property"
+ state={
+ state.phase === "loading"
+ ? { phase: "loading" }
+ : state.phase === "error"
+ ? { phase: "error", message: state.message }
+ : {
+ phase: "loaded",
+ items: state.properties.map((p) => ({
+ id: p.id,
+ name: p.name,
+ isDefault: p.id === state.default_property_id,
+ isPicking: pickingId === p.id,
+ })),
+ anyPicking: pickingId !== null,
+ }
+ }
+ onPick={(id) => {
+ const p = state.phase === "loaded" ? state.properties.find((x) => x.id === id) : null;
+ if (p) onPick(p);
+ }}
+ />
+ );
+}
+
+// ── Shared picker shell for Meta + GSC ─────────────────────────────
+//
+// Visually identical to the Google Ads picker but parameterized by the
+// MCP display label and the id-label shown under each row. Used by
+// MetaAccountStep + GscPropertyStep to avoid duplicating ~80 lines of
+// loading / error / empty / single-item / picker JSX three times.
+
+type AccountPickerScaffoldState =
+ | { phase: "loading" }
+ | { phase: "error"; message: string }
+ | {
+ phase: "loaded";
+ items: { id: string; name: string; isDefault: boolean; isPicking: boolean }[];
+ anyPicking: boolean;
+ };
+
+function AccountPickerScaffold({
+ slug,
+ mcpDisplayName,
+ idLabel,
+ state,
+ onPick,
+}: {
+ slug: string;
+ mcpDisplayName: string;
+ idLabel: string;
+ state: AccountPickerScaffoldState;
+ onPick: (id: string) => void;
+}) {
+ if (state.phase === "loading") {
+ return (
+ <Card>
+ <CardContent className="space-y-2 pt-6 pb-6">
+ <div className="flex items-center gap-3 text-sm">
+ <Loader2 className="size-4 animate-spin text-muted-foreground" aria-hidden />
+ <span className="font-medium">
+ Loading your {mcpDisplayName} accounts&hellip;
+ </span>
+ </div>
+ </CardContent>
+ </Card>
+ );
+ }
+ if (state.phase === "error") {
+ return (
+ <Card role="alert">
+ <CardContent className="space-y-3 pt-6 pb-6">
+ <div className="flex items-center gap-2">
+ <AlertCircle className="size-4 text-amber-600" aria-hidden />
+ <span className="font-medium text-sm">
+ Couldn&rsquo;t load your {mcpDisplayName} accounts.
+ </span>
+ </div>
+ <p className="text-xs text-muted-foreground">{state.message}</p>
+ <div className="flex gap-2">
+ <Button asChild>
+ <Link href={`/onboarding?step=connect&slug=${encodeURIComponent(slug)}`}>
+ Back to connect
+ </Link>
+ </Button>
+ </div>
+ </CardContent>
+ </Card>
+ );
+ }
+ if (state.items.length === 0) {
+ return (
+ <Card role="alert">
+ <CardContent className="space-y-3 pt-6 pb-6">
+ <p className="text-sm font-medium">
+ No {mcpDisplayName} accounts on this connection.
+ </p>
+ <p className="text-xs text-muted-foreground">
+ Try a different account or skip this connector for now.
+ </p>
+ <Button asChild>
+ <Link href={`/onboarding?step=connect&slug=${encodeURIComponent(slug)}`}>
+ Back to connect
+ </Link>
+ </Button>
+ </CardContent>
+ </Card>
+ );
+ }
+ if (state.items.length === 1) {
+ return (
+ <Card>
+ <CardContent className="space-y-2 pt-6 pb-6">
+ <div className="flex items-center gap-3 text-sm">
+ <Loader2 className="size-4 animate-spin text-muted-foreground" aria-hidden />
+ <span className="font-medium">
+ Using your only {mcpDisplayName} account&hellip;
+ </span>
+ </div>
+ </CardContent>
+ </Card>
+ );
+ }
+ return (
+ <>
+ <header className="space-y-2">
+ <h1 className="text-3xl font-semibold tracking-tight text-foreground">
+ Which {mcpDisplayName} account?
+ </h1>
+ <p className="text-sm text-muted-foreground">
+ Your connection has {state.items.length} accounts. Pick the one
+ you want me to use for this workspace. You can switch later in
+ Settings.
+ </p>
+ </header>
+ <ul className="space-y-2 list-none p-0">
+ {state.items.map((item) => {
+ const isOtherPicking = state.anyPicking && !item.isPicking;
+ return (
+ <li key={item.id}>
+ <button
+ type="button"
+ onClick={() => onPick(item.id)}
+ disabled={state.anyPicking}
+ aria-label={`Use ${item.name} (${item.id})`}
+ className={cn(
+ "block w-full rounded-md border bg-card p-4 text-left transition-colors hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-foreground/30 disabled:cursor-not-allowed",
+ isOtherPicking && "opacity-50",
+ )}
+ >
+ <div className="flex items-center justify-between gap-3">
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <span className="font-medium text-sm">{item.name}</span>
+ {item.isDefault && (
+ <span className="rounded bg-muted px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground">
+ default
+ </span>
+ )}
+ </div>
+ <p className="text-xs text-muted-foreground tabular-nums">
+ {idLabel} {item.id}
+ </p>
+ </div>
+ {item.isPicking ? (
+ <Loader2 className="size-4 animate-spin text-muted-foreground" aria-hidden />
+ ) : (
+ <ChevronRight className="size-4 text-muted-foreground" aria-hidden />
+ )}
+ </div>
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ </>
+ );
+}
+
function MissingSlug() {
return (
<Card>
<CardContent className="space-y-3 pt-6 pb-6">
<p className="text-sm text-muted-foreground">
- This step needs a project. Start from the beginning.
+ This step needs a workspace. Start from the beginning.
</p>
<Button asChild>
<Link href="/onboarding">Start over</Link>
diff --git a/notfair-cmo/src/components/project-rename-card.test.tsx b/notfair-cmo/src/components/project-rename-card.test.tsx
index 5f768eec..c5bbcea1 100644
--- a/notfair-cmo/src/components/project-rename-card.test.tsx
+++ b/notfair-cmo/src/components/project-rename-card.test.tsx
@@ -52,12 +52,12 @@ describe("ProjectRenameCard", () => {
expect(screen.getByRole("button", { name: /save name/i })).toBeDisabled();
});
- it("flips the button to 'Rename project' when the slug changes", () => {
+ it("flips the button to 'Rename workspace' when the slug changes", () => {
render(<ProjectRenameCard currentSlug="alpha" currentDisplayName="Alpha" />);
const input = screen.getByLabelText(/display name/i);
fireEvent.change(input, { target: { value: "Bravo" } });
expect(
- screen.getByRole("button", { name: /rename project/i }),
+ screen.getByRole("button", { name: /rename workspace/i }),
).toBeInTheDocument();
expect(screen.getByText(/slug changes from/i)).toBeInTheDocument();
});
@@ -68,7 +68,7 @@ describe("ProjectRenameCard", () => {
fireEvent.change(input, { target: { value: "@@@" } });
expect(screen.getByText(/invalid name/i)).toBeInTheDocument();
expect(
- screen.getByRole("button", { name: /save name|rename project/i }),
+ screen.getByRole("button", { name: /save name|rename workspace/i }),
).toBeDisabled();
});
@@ -85,7 +85,7 @@ describe("ProjectRenameCard", () => {
render(<ProjectRenameCard currentSlug="alpha" currentDisplayName="Alpha" />);
const input = screen.getByLabelText(/display name/i);
fireEvent.change(input, { target: { value: "Bravo" } });
- fireEvent.click(screen.getByRole("button", { name: /rename project/i }));
+ fireEvent.click(screen.getByRole("button", { name: /rename workspace/i }));
await waitFor(() =>
expect(renameProjectFullAction).toHaveBeenCalledWith({
current_slug: "alpha",
@@ -111,7 +111,7 @@ describe("ProjectRenameCard", () => {
render(<ProjectRenameCard currentSlug="alpha" currentDisplayName="Alpha" />);
const input = screen.getByLabelText(/display name/i);
fireEvent.change(input, { target: { value: "Bravo" } });
- fireEvent.click(screen.getByRole("button", { name: /rename project/i }));
+ fireEvent.click(screen.getByRole("button", { name: /rename workspace/i }));
await waitFor(() =>
expect(toast.success.mock.calls[0][0]).toMatch(/1 agents moved/),
);
@@ -136,7 +136,7 @@ describe("ProjectRenameCard", () => {
render(<ProjectRenameCard currentSlug="alpha" currentDisplayName="Alpha" />);
const input = screen.getByLabelText(/display name/i);
fireEvent.change(input, { target: { value: "Bravo" } });
- fireEvent.click(screen.getByRole("button", { name: /rename project/i }));
+ fireEvent.click(screen.getByRole("button", { name: /rename workspace/i }));
await waitFor(() => expect(toast.error).toHaveBeenCalledWith("boom"));
});
});
diff --git a/notfair-cmo/src/components/project-rename-card.tsx b/notfair-cmo/src/components/project-rename-card.tsx
index a00399b4..7df86324 100644
--- a/notfair-cmo/src/components/project-rename-card.tsx
+++ b/notfair-cmo/src/components/project-rename-card.tsx
@@ -68,9 +68,9 @@ export function ProjectRenameCard({
<div className="flex items-start gap-3">
<Pencil className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
<div className="min-w-0 flex-1">
- <h3 className="text-sm font-semibold">Rename this project</h3>
+ <h3 className="text-sm font-semibold">Rename this workspace</h3>
<p className="mt-0.5 text-xs text-muted-foreground">
- Changing the slug renames every agent in the project, rewrites all
+ Changing the slug renames every agent in the workspace, rewrites all
cron names, moves workspace dirs, relocates session JSONL files,
and repoints DB rows.
</p>
@@ -102,7 +102,7 @@ export function ProjectRenameCard({
<code className="rounded bg-muted px-1 font-mono">{currentSlug}</code>{" "}
to{" "}
<code className="rounded bg-muted px-1 font-mono">{derivedSlug}</code>
- . Every agent will be cloned into the new project and the old one
+ . Every agent will be cloned into the new workspace and the old one
removed.
</p>
) : (
@@ -120,7 +120,7 @@ export function ProjectRenameCard({
{slugChanged ? "Renaming…" : "Saving…"}
</>
) : slugChanged ? (
- "Rename project"
+ "Rename workspace"
) : (
"Save name"
)}
diff --git a/notfair-cmo/src/components/project-switcher.test.tsx b/notfair-cmo/src/components/project-switcher.test.tsx
index 418beb73..fbd42653 100644
--- a/notfair-cmo/src/components/project-switcher.test.tsx
+++ b/notfair-cmo/src/components/project-switcher.test.tsx
@@ -82,10 +82,10 @@ describe("ProjectSwitcher", () => {
expect(screen.getAllByText("AL").length).toBeGreaterThan(0);
});
- it("renders a 'New project' link to /onboarding", () => {
+ it("renders a 'New workspace' link to /onboarding", () => {
render(<ProjectSwitcher projects={projects} activeSlug="proj-a" />);
openMenu();
- expect(screen.getByText("New project")).toBeInTheDocument();
+ expect(screen.getByText("New workspace")).toBeInTheDocument();
});
it("opens the menu and lists all projects", () => {
@@ -124,9 +124,9 @@ describe("ProjectSwitcher", () => {
expect(router.push).not.toHaveBeenCalled();
});
- it("shows 'No projects yet' when projects list is empty", () => {
+ it("shows 'No workspaces yet' when projects list is empty", () => {
render(<ProjectSwitcher projects={[]} activeSlug={null} />);
openMenu();
- expect(screen.getByText("No projects yet")).toBeInTheDocument();
+ expect(screen.getByText("No workspaces yet")).toBeInTheDocument();
});
});
diff --git a/notfair-cmo/src/components/project-switcher.tsx b/notfair-cmo/src/components/project-switcher.tsx
index 9c99df2a..b29a86bf 100644
--- a/notfair-cmo/src/components/project-switcher.tsx
+++ b/notfair-cmo/src/components/project-switcher.tsx
@@ -64,7 +64,7 @@ export function ProjectSwitcher({ projects, activeSlug }: Props) {
Projects
</DropdownMenuLabel>
{projects.length === 0 && (
- <DropdownMenuItem disabled>No projects yet</DropdownMenuItem>
+ <DropdownMenuItem disabled>No workspaces yet</DropdownMenuItem>
)}
{projects.map((p) => (
<DropdownMenuItem
@@ -84,7 +84,7 @@ export function ProjectSwitcher({ projects, activeSlug }: Props) {
<DropdownMenuItem asChild>
<a href="/onboarding" className="gap-2">
<Plus className="size-4" />
- <span>New project</span>
+ <span>New workspace</span>
</a>
</DropdownMenuItem>
</DropdownMenuContent>
diff --git a/notfair-cmo/src/components/schedule-cron-dialog.tsx b/notfair-cmo/src/components/schedule-cron-dialog.tsx
index 6c9aa50c..d87d6c65 100644
--- a/notfair-cmo/src/components/schedule-cron-dialog.tsx
+++ b/notfair-cmo/src/components/schedule-cron-dialog.tsx
@@ -106,7 +106,7 @@ export function ScheduleCronDialog({ projectSlug, defaultSpecialist, variant = "
<DialogHeader>
<DialogTitle>Schedule recurring work</DialogTitle>
<DialogDescription>
- Creates a scheduled job under this project. The brief is the message the
+ Creates a scheduled job under this workspace. The brief is the message the
agent will receive on each tick.
</DialogDescription>
</DialogHeader>
diff --git a/notfair-cmo/src/server/actions/projects.ts b/notfair-cmo/src/server/actions/projects.ts
index 18b4143e..10895b60 100644
--- a/notfair-cmo/src/server/actions/projects.ts
+++ b/notfair-cmo/src/server/actions/projects.ts
@@ -41,7 +41,7 @@ export type ActionResult<T = void> =
// in a client wrapper later if needed.
export async function createProjectAction(formData: FormData): Promise<void> {
const display_name = String(formData.get("display_name") ?? "").trim();
- if (!display_name) throw new Error("Please enter a project name.");
+ if (!display_name) throw new Error("Please enter a workspace name.");
const result = createProject({ display_name });
if (!result.ok) throw new Error(result.reason);
@@ -92,7 +92,7 @@ export async function createProjectForOnboardingAction(
formData: FormData,
): Promise<ActionResult<{ slug: string; display_name: string }>> {
const display_name = String(formData.get("display_name") ?? "").trim();
- if (!display_name) return { ok: false, error: "Please enter a project name." };
+ if (!display_name) return { ok: false, error: "Please enter a workspace name." };
const website_url = String(formData.get("website_url") ?? "").trim() || null;
const codebase_path = String(formData.get("codebase_path") ?? "").trim() || null;
diff --git a/notfair-cmo/src/server/agent-templates.test.ts b/notfair-cmo/src/server/agent-templates.test.ts
new file mode 100644
index 00000000..674144c2
--- /dev/null
+++ b/notfair-cmo/src/server/agent-templates.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ TEMPLATES,
+ templateForKey,
+ templateForUrlSlug,
+ agentUrlSlug,
+ DEFAULT_ONBOARDING_TEMPLATE_KEYS,
+ SPECIALIST_TEMPLATE_BY_MCP_KEY,
+} from "./agent-templates";
+
+describe("AgentTemplate catalog", () => {
+ it("ships exactly five templates: cmo + 3 recommended specialists + seo", () => {
+ const keys = TEMPLATES.map((t) => t.key).sort();
+ expect(keys).toEqual(["cmo", "google_ads", "gsc", "meta_ads", "seo"]);
+ });
+
+ it("only CMO is included in the default onboarding bundle", () => {
+ expect(DEFAULT_ONBOARDING_TEMPLATE_KEYS).toEqual(["cmo"]);
+ expect(TEMPLATES.filter((t) => t.default_onboarding).map((t) => t.key)).toEqual(
+ ["cmo"],
+ );
+ });
+
+ it("the three specialists declare their required MCP catalog key", () => {
+ expect(templateForKey("google_ads")?.requires_mcp_key).toBe(
+ "notfair-googleads",
+ );
+ expect(templateForKey("meta_ads")?.requires_mcp_key).toBe(
+ "notfair-metaads",
+ );
+ expect(templateForKey("gsc")?.requires_mcp_key).toBe(
+ "notfair-googlesearchconsole",
+ );
+ });
+
+ it("CMO has no requires_mcp_key — it never blocks", () => {
+ expect(templateForKey("cmo")?.requires_mcp_key).toBeUndefined();
+ });
+
+ it("SPECIALIST_TEMPLATE_BY_MCP_KEY inverts requires_mcp_key for connect-time provisioning", () => {
+ expect(SPECIALIST_TEMPLATE_BY_MCP_KEY["notfair-googleads"]).toBe(
+ "google_ads",
+ );
+ expect(SPECIALIST_TEMPLATE_BY_MCP_KEY["notfair-metaads"]).toBe("meta_ads");
+ expect(SPECIALIST_TEMPLATE_BY_MCP_KEY["notfair-googlesearchconsole"]).toBe(
+ "gsc",
+ );
+ expect(SPECIALIST_TEMPLATE_BY_MCP_KEY["stripe"]).toBeUndefined();
+ });
+
+ it("templateForUrlSlug resolves the hyphenated URL form (gsc has no underscore so it round-trips trivially)", () => {
+ expect(templateForUrlSlug("google-ads")?.key).toBe("google_ads");
+ expect(templateForUrlSlug("meta-ads")?.key).toBe("meta_ads");
+ expect(templateForUrlSlug("gsc")?.key).toBe("gsc");
+ });
+
+ it("agentUrlSlug produces stable slugs for the new templates", () => {
+ expect(agentUrlSlug("meta_ads", "Mia")).toBe("meta-ads-mia");
+ expect(agentUrlSlug("gsc", "Sasha")).toBe("gsc-sasha");
+ });
+});
diff --git a/notfair-cmo/src/server/agent-templates.ts b/notfair-cmo/src/server/agent-templates.ts
index 95816bb0..0aa51ae9 100644
--- a/notfair-cmo/src/server/agent-templates.ts
+++ b/notfair-cmo/src/server/agent-templates.ts
@@ -99,7 +99,7 @@ Style:
starting the next.`;
export type AgentTemplate = {
- key: "cmo" | "google_ads" | "seo";
+ key: "cmo" | "google_ads" | "meta_ads" | "gsc" | "seo";
/**
* Label for the ROLE this template represents (e.g. "CMO", "Google
* Ads"). Used in the sidebar role pill + anywhere the UI says
@@ -127,6 +127,15 @@ export type AgentTemplate = {
* provisions a clone of it for a project.
*/
default_onboarding: boolean;
+ /**
+ * MCP catalog key this specialist needs to do its job. When set:
+ * - The agent is provisioned conditionally — only when the matching
+ * MCP is connected for the project (see provisionSpecialistForMcp).
+ * - The agent's page shows a "Connect <platform>" blocker when the
+ * MCP token is missing (see resolveMcpBlocker).
+ * CMO and other tools-less templates leave this undefined.
+ */
+ requires_mcp_key?: string;
};
export type AgentTemplateKey = AgentTemplate["key"];
@@ -134,11 +143,25 @@ export type AgentTemplateKey = AgentTemplate["key"];
/**
* Subset of TEMPLATES included in the default onboarding bundle. Single
* source of truth for "which agents does a freshly-created project get?".
- * Used by createProject actions to scope ensureProjectAgents and by
- * listProjectAgents to decide which template entries to synthesize as
- * placeholders before disk-overlay merges in.
+ *
+ * Only CMO ships by default now. The three specialists (Google Ads,
+ * Meta Ads, Google Search Console) are gated on the user connecting the
+ * matching MCP — the connect step in onboarding triggers provisioning
+ * via provisionSpecialistForMcp as each token lands.
*/
-export const DEFAULT_ONBOARDING_TEMPLATE_KEYS: AgentTemplateKey[] = ["cmo", "google_ads"];
+export const DEFAULT_ONBOARDING_TEMPLATE_KEYS: AgentTemplateKey[] = ["cmo"];
+
+/**
+ * Template key → MCP catalog key mapping for the specialists that the
+ * onboarding connect step gates provisioning on. Inverse lookup
+ * (MCP key → template key) used by provisionSpecialistForMcp when an
+ * OAuth callback lands and we need to decide which specialist to mint.
+ */
+export const SPECIALIST_TEMPLATE_BY_MCP_KEY: Record<string, AgentTemplateKey> = {
+ "notfair-googleads": "google_ads",
+ "notfair-metaads": "meta_ads",
+ "notfair-googlesearchconsole": "gsc",
+};
export function templateForKey(key: string): AgentTemplate | undefined {
return TEMPLATES.find((t) => t.key === key || t.key.replace(/_/g, "-") === key);
@@ -201,7 +224,92 @@ a wide net on the first pass; filter in-script for free.
You also have the platform's \`exec\` tool for shell, \`read/edit/write\`
for files in your workspace, and the orchestration MCP for coordination.`,
- default_onboarding: true,
+ default_onboarding: false,
+ requires_mcp_key: "notfair-googleads",
+ },
+ {
+ key: "meta_ads",
+ display_name: "Meta Ads",
+ default_name: "Mia",
+ description: "Runs Meta Ads (Facebook + Instagram) campaigns, ad sets, creative, audiences.",
+ capabilities: [
+ "Audit ad-account spend, ROAS, CPM, frequency",
+ "Diagnose ad-set delivery + audience overlap",
+ "Surface creative fatigue + winners",
+ "Propose budget shifts + bid changes",
+ "Schedule recurring performance + pacing checks",
+ "Uses notfair-metaads MCP when account connected",
+ ],
+ model: "openai-codex/gpt-5.5",
+ system_prompt: `You are a Meta Ads (Facebook + Instagram) specialist agent on the notfair-cmo platform.
+
+${SPECIALIST_ROLE}
+
+## Your domain tools
+
+When the notfair-metaads MCP is connected to this project, use its
+\`runScript\` tool for reads — \`ads.graph\` for single Graph API calls,
+\`ads.graphParallel\` to fan out across insights / adsets / creatives /
+account in one pass, and \`ads.insights\` for the conventional insights
+pull with sensible defaults. Cast a wide net on the first call; filter
+in-script for free.
+
+Domain conventions you should respect:
+- Refer to spend in account currency, not abstract units. Always quote
+ numbers (spend, ROAS, CPM, CTR, freq) when reporting findings.
+- Default to the last 30 days for performance reads unless the brief
+ asks for a different window. Use date_preset \`last_30d\` for
+ consistency.
+- Audience overlap, creative fatigue, and CPM spikes are the three
+ things to look for in a "what's wrong" pass; ROAS by ad set + by
+ creative are the two things to look at in a "what's working" pass.
+
+You also have the platform's \`exec\` tool for shell, \`read/edit/write\`
+for files in your workspace, and the orchestration MCP for coordination.`,
+ default_onboarding: false,
+ requires_mcp_key: "notfair-metaads",
+ },
+ {
+ key: "gsc",
+ display_name: "Google Search Console",
+ default_name: "Sasha",
+ description: "Organic search performance — queries, pages, impressions, clicks, indexing.",
+ capabilities: [
+ "Pull search performance (queries, pages, devices, countries)",
+ "Surface query/page movers week-over-week",
+ "Identify pages losing impressions or rankings",
+ "Diagnose indexing issues + coverage gaps",
+ "Schedule recurring ranking/click summaries",
+ "Uses notfair-googlesearchconsole MCP when property connected",
+ ],
+ model: "openai-codex/gpt-5.5",
+ system_prompt: `You are a Google Search Console specialist agent on the notfair-cmo platform.
+
+${SPECIALIST_ROLE}
+
+## Your domain tools
+
+When the notfair-googlesearchconsole MCP is connected to this project,
+use its tools to pull organic search performance (impressions, clicks,
+position) sliced by query, page, country, and device. The selected GSC
+property (e.g. \`sc-domain:example.com\` or \`https://example.com/\`)
+is persisted on the project — every call you make should target that
+property unless the brief explicitly asks for another.
+
+Domain conventions you should respect:
+- Always quote impressions, clicks, CTR, and average position when
+ reporting findings. The user trusts numbers more than adjectives.
+- Default to the last 28 days for performance reads unless the brief
+ asks for a different window. That window aligns with Search Console's
+ native default.
+- Movers analysis matters more than absolutes here — surface queries +
+ pages that moved week-over-week (impressions or position), not the
+ static top-10 lists the user has already seen.
+
+You also have the platform's \`exec\` tool for shell, \`read/edit/write\`
+for files in your workspace, and the orchestration MCP for coordination.`,
+ default_onboarding: false,
+ requires_mcp_key: "notfair-googlesearchconsole",
},
{
key: "seo",
@@ -232,6 +340,34 @@ for files in your workspace, and the orchestration MCP for coordination.`,
},
];
+/**
+ * Provision the specialist agent that matches a newly-connected MCP. Called
+ * from the OAuth callback right after `setMcpBearer` lands a token. Looks
+ * up the template via SPECIALIST_TEMPLATE_BY_MCP_KEY, then calls
+ * ensureProjectAgents with that single template.
+ *
+ * Idempotent: if the agent already exists (user reconnected after a
+ * disconnect, or token was set via a non-OAuth path that already
+ * triggered provisioning), ensureProjectAgents returns it in `existed`
+ * and writes no files.
+ *
+ * No-op when:
+ * - The catalog_key isn't one of the recommended specialists (e.g.
+ * Stripe / Supabase MCPs from the "More" tile — those don't get an
+ * agent).
+ * - The project doesn't exist (defensive — shouldn't happen via the
+ * OAuth callback path which only runs after the project is created).
+ */
+export async function provisionSpecialistForMcp(
+ project_slug: string,
+ catalog_key: string,
+): Promise<EnsureAgentsResult | null> {
+ const template_key = SPECIALIST_TEMPLATE_BY_MCP_KEY[catalog_key];
+ if (!template_key) return null;
+ if (!getProject(project_slug)) return null;
+ return ensureProjectAgents(project_slug, [template_key]);
+}
+
export function agentNameFor(
project_slug: string,
template_key: AgentTemplate["key"],
diff --git a/notfair-cmo/src/server/db/migrations.ts b/notfair-cmo/src/server/db/migrations.ts
index 12c82bac..5260c5bb 100644
--- a/notfair-cmo/src/server/db/migrations.ts
+++ b/notfair-cmo/src/server/db/migrations.ts
@@ -552,6 +552,21 @@ ALTER TABLE mcp_tokens ADD COLUMN client_secret TEXT;
-- adapter's final/delta text and writes it on finishJobRun.
ALTER TABLE scheduled_job_runs ADD COLUMN summary TEXT;
+`,
+ },
+ {
+ name: "015_meta_ads_and_gsc_accounts.sql",
+ sql: `
+-- Per-project Meta Ads and Google Search Console account/property
+-- selection — same pattern as google_ads_account_id (migration 002).
+-- The notfair-metaads bearer can cover multiple ad accounts; the
+-- notfair-googlesearchconsole bearer can cover multiple verified
+-- properties. Onboarding asks the user to pick one of each (when the
+-- token has >1) so the specialist agents always target the right
+-- entity. Null until picked.
+
+ALTER TABLE projects ADD COLUMN meta_ads_account_id TEXT;
+ALTER TABLE projects ADD COLUMN gsc_property_id TEXT;
`,
},
];
diff --git a/notfair-cmo/src/server/db/migrations/015_meta_ads_and_gsc_accounts.sql b/notfair-cmo/src/server/db/migrations/015_meta_ads_and_gsc_accounts.sql
new file mode 100644
index 00000000..2d438d7b
--- /dev/null
+++ b/notfair-cmo/src/server/db/migrations/015_meta_ads_and_gsc_accounts.sql
@@ -0,0 +1,10 @@
+-- Per-project Meta Ads and Google Search Console account/property
+-- selection — same pattern as google_ads_account_id (migration 002).
+-- The notfair-metaads bearer can cover multiple ad accounts; the
+-- notfair-googlesearchconsole bearer can cover multiple verified
+-- properties. Onboarding asks the user to pick one of each (when the
+-- token has >1) so the specialist agents always target the right
+-- entity. Null until picked.
+
+ALTER TABLE projects ADD COLUMN meta_ads_account_id TEXT;
+ALTER TABLE projects ADD COLUMN gsc_property_id TEXT;
diff --git a/notfair-cmo/src/server/db/projects.ts b/notfair-cmo/src/server/db/projects.ts
index 277f9505..37dd4ce5 100644
--- a/notfair-cmo/src/server/db/projects.ts
+++ b/notfair-cmo/src/server/db/projects.ts
@@ -56,6 +56,8 @@ export function createProject(input: CreateProjectInput): CreateProjectResult {
created_at: new Date().toISOString(),
archived_at: null,
google_ads_account_id: null,
+ meta_ads_account_id: null,
+ gsc_property_id: null,
website_url,
codebase_path,
harness_adapter,
@@ -110,6 +112,36 @@ export function setProjectGoogleAdsAccount(
return getProject(slug);
}
+/** Same shape as setProjectGoogleAdsAccount but for the Meta Ads ad-account id. */
+export function setProjectMetaAdsAccount(
+ slug: string,
+ account_id: string | null,
+): Project | null {
+ const db = getDb();
+ const existing = db.prepare("SELECT 1 FROM projects WHERE slug = ?").get(slug);
+ if (!existing) return null;
+ db.prepare("UPDATE projects SET meta_ads_account_id = ? WHERE slug = ?").run(
+ account_id,
+ slug,
+ );
+ return getProject(slug);
+}
+
+/** Same shape as setProjectGoogleAdsAccount but for the GSC property id. */
+export function setProjectGscProperty(
+ slug: string,
+ property_id: string | null,
+): Project | null {
+ const db = getDb();
+ const existing = db.prepare("SELECT 1 FROM projects WHERE slug = ?").get(slug);
+ if (!existing) return null;
+ db.prepare("UPDATE projects SET gsc_property_id = ? WHERE slug = ?").run(
+ property_id,
+ slug,
+ );
+ return getProject(slug);
+}
+
export function renameProject(slug: string, display_name: string): Project | null {
const db = getDb();
const trimmed = display_name.trim();
diff --git a/notfair-cmo/src/server/mcp-catalog.ts b/notfair-cmo/src/server/mcp-catalog.ts
index e00aa647..9ef67445 100644
--- a/notfair-cmo/src/server/mcp-catalog.ts
+++ b/notfair-cmo/src/server/mcp-catalog.ts
@@ -44,6 +44,26 @@ export const MCP_CATALOG_PRESETS: McpSpec[] = [
"https://notfair.co/.well-known/oauth-protected-resource/api/mcp/google_ads",
source: "preset",
},
+ {
+ key: "notfair-metaads",
+ display_name: "NotFair Meta Ads",
+ description:
+ "Live Meta Ads (Facebook + Instagram) operations: campaigns, ad sets, ads, creatives, insights.",
+ resource_url: "https://notfair.co/api/mcp/meta_ads",
+ discovery_url:
+ "https://notfair.co/.well-known/oauth-protected-resource/api/mcp/meta_ads",
+ source: "preset",
+ },
+ {
+ key: "notfair-googlesearchconsole",
+ display_name: "NotFair Google Search Console",
+ description:
+ "Organic search performance: queries, pages, impressions, clicks, indexing.",
+ resource_url: "https://notfair.co/api/mcp/google_search_console",
+ discovery_url:
+ "https://notfair.co/.well-known/oauth-protected-resource/api/mcp/google_search_console",
+ source: "preset",
+ },
];
/** True if any preset reserves this key. Presets win over user rows. */
diff --git a/notfair-cmo/src/server/onboarding/accounts.test.ts b/notfair-cmo/src/server/onboarding/accounts.test.ts
index c4c4b8fc..d62ddbf2 100644
--- a/notfair-cmo/src/server/onboarding/accounts.test.ts
+++ b/notfair-cmo/src/server/onboarding/accounts.test.ts
@@ -15,10 +15,16 @@ vi.mock("@/server/mcp/rpc", () => ({
const getProjectMock = vi.fn();
const setProjectGoogleAdsAccountMock = vi.fn();
+const setProjectMetaAdsAccountMock = vi.fn();
+const setProjectGscPropertyMock = vi.fn();
vi.mock("@/server/db/projects", () => ({
getProject: (...args: unknown[]) => getProjectMock(...args),
setProjectGoogleAdsAccount: (...args: unknown[]) =>
setProjectGoogleAdsAccountMock(...args),
+ setProjectMetaAdsAccount: (...args: unknown[]) =>
+ setProjectMetaAdsAccountMock(...args),
+ setProjectGscProperty: (...args: unknown[]) =>
+ setProjectGscPropertyMock(...args),
}));
vi.mock("next/cache", () => ({
@@ -84,6 +90,10 @@ vi.mock("@/server/agent-meta", () => ({
import {
listGoogleAdsAccounts,
setOnboardingAccountAction,
+ listMetaAdsAccounts,
+ setOnboardingMetaAdsAccountAction,
+ listGscProperties,
+ setOnboardingGscPropertyAction,
} from "./accounts";
// ── Fixtures ───────────────────────────────────────────────────────
@@ -288,6 +298,183 @@ describe("setOnboardingAccountAction", () => {
});
});
+// ── Meta Ads ───────────────────────────────────────────────────────
+
+describe("listMetaAdsAccounts", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getMcpConfigMock.mockReturnValue({
+ url: "https://notfair.co/api/mcp/meta_ads",
+ token: "tok",
+ });
+ });
+
+ it("parses the Meta Graph `data` array shape (id + name)", async () => {
+ mcpRpcMock.mockResolvedValueOnce(
+ toolCallResult({
+ data: [
+ { id: "act_111", name: "Brand A" },
+ { id: "act_222", name: "Brand B" },
+ ],
+ }),
+ );
+ const r = await listMetaAdsAccounts("acme");
+ expect(r.ok).toBe(true);
+ if (r.ok) {
+ expect(r.accounts).toEqual([
+ { id: "act_111", name: "Brand A" },
+ { id: "act_222", name: "Brand B" },
+ ]);
+ expect(r.default_account_id).toBeNull();
+ }
+ });
+
+ it("returns shape error when neither `data` nor `accounts` is present", async () => {
+ mcpRpcMock.mockResolvedValueOnce(toolCallResult({ foo: "bar" }));
+ const r = await listMetaAdsAccounts("acme");
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.kind).toBe("shape");
+ });
+
+ it("returns mcp_not_configured when no token row exists for the project", async () => {
+ getMcpConfigMock.mockReturnValueOnce(null);
+ const r = await listMetaAdsAccounts("acme");
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.kind).toBe("mcp_not_configured");
+ });
+});
+
+describe("setOnboardingMetaAdsAccountAction", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getProjectMock.mockReturnValue({
+ id: "p-1",
+ slug: "acme",
+ display_name: "Acme",
+ });
+ getMcpConfigMock.mockReturnValue({
+ url: "https://notfair.co/api/mcp/meta_ads",
+ token: "tok",
+ });
+ });
+
+ it("persists the chosen ad-account when it's in the bearer's list", async () => {
+ mcpRpcMock.mockResolvedValueOnce(
+ toolCallResult({
+ data: [
+ { id: "act_111", name: "Brand A" },
+ { id: "act_222", name: "Brand B" },
+ ],
+ }),
+ );
+ setProjectMetaAdsAccountMock.mockReturnValue({
+ slug: "acme",
+ meta_ads_account_id: "act_222",
+ });
+ const r = await setOnboardingMetaAdsAccountAction("acme", "act_222");
+ expect(r.ok).toBe(true);
+ expect(setProjectMetaAdsAccountMock).toHaveBeenCalledWith("acme", "act_222");
+ });
+
+ it("rejects when the account isn't in the bearer's list (tamper defense)", async () => {
+ mcpRpcMock.mockResolvedValueOnce(
+ toolCallResult({ data: [{ id: "act_111", name: "Brand A" }] }),
+ );
+ const r = await setOnboardingMetaAdsAccountAction("acme", "act_evil");
+ expect(r.ok).toBe(false);
+ expect(setProjectMetaAdsAccountMock).not.toHaveBeenCalled();
+ });
+});
+
+// ── GSC ────────────────────────────────────────────────────────────
+
+describe("listGscProperties", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getMcpConfigMock.mockReturnValue({
+ url: "https://notfair.co/api/mcp/google_search_console",
+ token: "tok",
+ });
+ });
+
+ it("parses the Search Console `siteEntry` shape", async () => {
+ mcpRpcMock.mockResolvedValueOnce(
+ toolCallResult({
+ siteEntry: [
+ {
+ siteUrl: "https://notfair.co/",
+ permissionLevel: "siteOwner",
+ },
+ { siteUrl: "sc-domain:notfair.co", permissionLevel: "siteFullUser" },
+ ],
+ }),
+ );
+ const r = await listGscProperties("acme");
+ expect(r.ok).toBe(true);
+ if (r.ok) {
+ expect(r.properties.map((p) => p.id)).toEqual([
+ "https://notfair.co/",
+ "sc-domain:notfair.co",
+ ]);
+ // prettyGscName strips scheme + sc-domain prefix.
+ expect(r.properties[0]!.name).toBe("notfair.co");
+ expect(r.properties[1]!.name).toBe("notfair.co");
+ expect(r.properties[0]!.permission).toBe("siteOwner");
+ }
+ });
+
+ it("returns shape error when neither siteEntry nor sites is present", async () => {
+ mcpRpcMock.mockResolvedValueOnce(toolCallResult({ foo: "bar" }));
+ const r = await listGscProperties("acme");
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.kind).toBe("shape");
+ });
+});
+
+describe("setOnboardingGscPropertyAction", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getProjectMock.mockReturnValue({
+ id: "p-1",
+ slug: "acme",
+ display_name: "Acme",
+ });
+ getMcpConfigMock.mockReturnValue({
+ url: "https://notfair.co/api/mcp/google_search_console",
+ token: "tok",
+ });
+ });
+
+ it("persists the chosen property when it's in the bearer's list", async () => {
+ mcpRpcMock.mockResolvedValueOnce(
+ toolCallResult({
+ siteEntry: [{ siteUrl: "sc-domain:notfair.co", permissionLevel: "siteOwner" }],
+ }),
+ );
+ setProjectGscPropertyMock.mockReturnValue({
+ slug: "acme",
+ gsc_property_id: "sc-domain:notfair.co",
+ });
+ const r = await setOnboardingGscPropertyAction("acme", "sc-domain:notfair.co");
+ expect(r.ok).toBe(true);
+ expect(setProjectGscPropertyMock).toHaveBeenCalledWith(
+ "acme",
+ "sc-domain:notfair.co",
+ );
+ });
+
+ it("rejects when the property isn't in the bearer's list", async () => {
+ mcpRpcMock.mockResolvedValueOnce(
+ toolCallResult({
+ siteEntry: [{ siteUrl: "https://other.example/", permissionLevel: "siteUser" }],
+ }),
+ );
+ const r = await setOnboardingGscPropertyAction("acme", "sc-domain:evil.com");
+ expect(r.ok).toBe(false);
+ expect(setProjectGscPropertyMock).not.toHaveBeenCalled();
+ });
+});
+
afterEach(() => {
vi.clearAllMocks();
});
diff --git a/notfair-cmo/src/server/onboarding/accounts.ts b/notfair-cmo/src/server/onboarding/accounts.ts
index 4c0dc12c..da595d04 100644
--- a/notfair-cmo/src/server/onboarding/accounts.ts
+++ b/notfair-cmo/src/server/onboarding/accounts.ts
@@ -3,7 +3,12 @@
import { revalidatePath } from "next/cache";
import { getMcpConfig, mcpRpcAutoRefresh } from "@/server/mcp/rpc";
-import { getProject, setProjectGoogleAdsAccount } from "@/server/db/projects";
+import {
+ getProject,
+ setProjectGoogleAdsAccount,
+ setProjectMetaAdsAccount,
+ setProjectGscProperty,
+} from "@/server/db/projects";
import type { Project } from "@/types";
/**
@@ -399,3 +404,396 @@ export async function getOnboardingTaskForSkipAction(
cmo_agent_slug: cmo.slug,
};
}
+
+// ── Meta Ads account picker ────────────────────────────────────────
+//
+// Mirrors the Google Ads pattern. The notfair-metaads MCP exposes a
+// `listAdAccounts` tool that returns the ad accounts the current bearer
+// can reach. Onboarding asks the user to pick one and we persist it on
+// `projects.meta_ads_account_id`.
+
+const META_ADS_MCP_KEY = "notfair-metaads";
+const META_ADS_LIST_TOOL = "listAdAccounts";
+
+export type MetaAdsAccount = {
+ /** Numeric ad-account id with the `act_` prefix (e.g. `act_123456`). */
+ id: string;
+ /** Display name pulled from the Meta Graph payload. Falls back to id. */
+ name: string;
+};
+
+export type ListMetaAdsAccountsResult =
+ | { ok: true; accounts: MetaAdsAccount[]; default_account_id: string | null }
+ | { ok: false; error: string; kind: "mcp_not_configured" | "rpc" | "shape" };
+
+export async function listMetaAdsAccounts(
+ project_slug: string,
+): Promise<ListMetaAdsAccountsResult> {
+ const cfg = getMcpConfig(project_slug, META_ADS_MCP_KEY);
+ if (!cfg) {
+ return {
+ ok: false,
+ kind: "mcp_not_configured",
+ error: "Meta Ads MCP is not configured for this project.",
+ };
+ }
+
+ const rpcResult = await mcpRpcAutoRefresh<ListAccountsToolResult>(
+ project_slug,
+ META_ADS_MCP_KEY,
+ "tools/call",
+ { name: META_ADS_LIST_TOOL, arguments: {} },
+ { timeoutMs: LIST_TIMEOUT_MS },
+ );
+ if (!rpcResult.ok) {
+ return { ok: false, kind: "rpc", error: rpcErrorMessage(rpcResult) };
+ }
+
+ const parsed = parseMetaAccountsPayload(rpcResult.result);
+ if (!parsed) {
+ return {
+ ok: false,
+ kind: "shape",
+ error: `MCP ${META_ADS_LIST_TOOL} returned an unexpected shape.`,
+ };
+ }
+ return { ok: true, ...parsed };
+}
+
+type MetaAccountsPayload = {
+ // The Meta MCP wraps Graph API responses, which use `data` for the
+ // collection. We also accept the Google-Ads-style `accounts` key
+ // defensively in case the MCP normalizes the shape upstream.
+ data?: Array<{ id?: unknown; name?: unknown; account_id?: unknown }>;
+ accounts?: Array<{ id?: unknown; name?: unknown }>;
+ defaultAccountId?: unknown;
+};
+
+function parseMetaAccountsPayload(
+ result: ListAccountsToolResult,
+): { accounts: MetaAdsAccount[]; default_account_id: string | null } | null {
+ if (!result || typeof result !== "object") return null;
+ if (result.isError) return null;
+ const text = result.content?.[0]?.text;
+ if (typeof text !== "string") return null;
+ let body: MetaAccountsPayload;
+ try {
+ body = JSON.parse(text) as MetaAccountsPayload;
+ } catch {
+ return null;
+ }
+ const raw = Array.isArray(body.data)
+ ? body.data
+ : Array.isArray(body.accounts)
+ ? body.accounts
+ : null;
+ if (!raw) return null;
+ const accounts: MetaAdsAccount[] = [];
+ for (const a of raw) {
+ if (!a || typeof a !== "object") continue;
+ const id = String(a.id ?? "").trim();
+ const name = String(a.name ?? "").trim() || id;
+ if (id) accounts.push({ id, name });
+ }
+ const default_account_id =
+ typeof body.defaultAccountId === "string" || typeof body.defaultAccountId === "number"
+ ? String(body.defaultAccountId)
+ : null;
+ return { accounts, default_account_id };
+}
+
+export type SetMetaAdsAccountResult =
+ | { ok: true; project: Project }
+ | { ok: false; error: string };
+
+export async function setOnboardingMetaAdsAccountAction(
+ project_slug: string,
+ account_id: string,
+): Promise<SetMetaAdsAccountResult> {
+ if (!project_slug.trim() || !account_id.trim()) {
+ return { ok: false, error: "Missing project slug or account id." };
+ }
+ if (!getProject(project_slug)) return { ok: false, error: "Project not found." };
+
+ const list = await listMetaAdsAccounts(project_slug);
+ if (!list.ok) {
+ return {
+ ok: false,
+ error: `Couldn't verify account against Meta Ads MCP: ${list.error}`,
+ };
+ }
+ const match = list.accounts.find((a) => a.id === account_id);
+ if (!match) {
+ return {
+ ok: false,
+ error: `Account ${account_id} isn't in this bearer's reachable accounts.`,
+ };
+ }
+ const updated = setProjectMetaAdsAccount(project_slug, match.id);
+ if (!updated) return { ok: false, error: "Project not found." };
+ revalidatePath("/", "layout");
+ return { ok: true, project: updated };
+}
+
+// ── Google Search Console property picker ──────────────────────────
+//
+// Mirrors the Google Ads pattern. Per the GSC REST API the unit is a
+// "site" (e.g. `https://example.com/` or `sc-domain:example.com`); we
+// surface them as "properties" in the UI to match what users see in
+// Search Console.
+//
+// **Tool name is a best-guess.** The notfair-googlesearchconsole MCP
+// is freshly added; we expect a tool called `listSites` (mirroring the
+// Search Console API method). If the real tool name is different
+// (e.g. `listProperties`, `listConnectedSites`), change the constant
+// below — the failure mode is a clean RPC "method not found" error
+// surfaced through the existing rpcErrorMessage formatter.
+
+const GSC_MCP_KEY = "notfair-googlesearchconsole";
+const GSC_LIST_TOOL = "listSites";
+
+export type GscProperty = {
+ /** Site URL exactly as Search Console uses it. */
+ id: string;
+ /** Display label — typically equals id but trimmed of the scheme. */
+ name: string;
+ /** Permission level the bearer has on this property (owner / full / …). */
+ permission?: string;
+};
+
+export type ListGscPropertiesResult =
+ | { ok: true; properties: GscProperty[]; default_property_id: string | null }
+ | { ok: false; error: string; kind: "mcp_not_configured" | "rpc" | "shape" };
+
+export async function listGscProperties(
+ project_slug: string,
+): Promise<ListGscPropertiesResult> {
+ const cfg = getMcpConfig(project_slug, GSC_MCP_KEY);
+ if (!cfg) {
+ return {
+ ok: false,
+ kind: "mcp_not_configured",
+ error: "Google Search Console MCP is not configured for this project.",
+ };
+ }
+
+ const rpcResult = await mcpRpcAutoRefresh<ListAccountsToolResult>(
+ project_slug,
+ GSC_MCP_KEY,
+ "tools/call",
+ { name: GSC_LIST_TOOL, arguments: {} },
+ { timeoutMs: LIST_TIMEOUT_MS },
+ );
+ if (!rpcResult.ok) {
+ return { ok: false, kind: "rpc", error: rpcErrorMessage(rpcResult) };
+ }
+
+ const parsed = parseGscPropertiesPayload(rpcResult.result);
+ if (!parsed) {
+ return {
+ ok: false,
+ kind: "shape",
+ error: `MCP ${GSC_LIST_TOOL} returned an unexpected shape.`,
+ };
+ }
+ return { ok: true, ...parsed };
+}
+
+type GscPropertiesPayload = {
+ // Search Console REST returns `siteEntry: [{ siteUrl, permissionLevel }]`.
+ // The MCP may pass that through unchanged, or normalize to a flatter
+ // shape. Accept both, plus a defensive `sites` array.
+ siteEntry?: Array<{ siteUrl?: unknown; permissionLevel?: unknown }>;
+ sites?: Array<{ id?: unknown; name?: unknown; siteUrl?: unknown }>;
+ defaultPropertyId?: unknown;
+};
+
+function parseGscPropertiesPayload(
+ result: ListAccountsToolResult,
+): { properties: GscProperty[]; default_property_id: string | null } | null {
+ if (!result || typeof result !== "object") return null;
+ if (result.isError) return null;
+ const text = result.content?.[0]?.text;
+ if (typeof text !== "string") return null;
+ let body: GscPropertiesPayload;
+ try {
+ body = JSON.parse(text) as GscPropertiesPayload;
+ } catch {
+ return null;
+ }
+ const properties: GscProperty[] = [];
+ if (Array.isArray(body.siteEntry)) {
+ for (const s of body.siteEntry) {
+ const id = String(s?.siteUrl ?? "").trim();
+ if (!id) continue;
+ properties.push({
+ id,
+ name: prettyGscName(id),
+ permission:
+ typeof s?.permissionLevel === "string" ? s.permissionLevel : undefined,
+ });
+ }
+ } else if (Array.isArray(body.sites)) {
+ for (const s of body.sites) {
+ const id = String(s?.id ?? s?.siteUrl ?? "").trim();
+ if (!id) continue;
+ const name = String(s?.name ?? "").trim() || prettyGscName(id);
+ properties.push({ id, name });
+ }
+ } else {
+ return null;
+ }
+ const default_property_id =
+ typeof body.defaultPropertyId === "string"
+ ? body.defaultPropertyId
+ : null;
+ return { properties, default_property_id };
+}
+
+function prettyGscName(siteUrl: string): string {
+ // `sc-domain:example.com` → `example.com`
+ // `https://example.com/` → `example.com`
+ if (siteUrl.startsWith("sc-domain:")) return siteUrl.slice("sc-domain:".length);
+ try {
+ const u = new URL(siteUrl);
+ return u.host + (u.pathname === "/" ? "" : u.pathname);
+ } catch {
+ return siteUrl;
+ }
+}
+
+export type SetGscPropertyResult =
+ | { ok: true; project: Project }
+ | { ok: false; error: string };
+
+export async function setOnboardingGscPropertyAction(
+ project_slug: string,
+ property_id: string,
+): Promise<SetGscPropertyResult> {
+ if (!project_slug.trim() || !property_id.trim()) {
+ return { ok: false, error: "Missing project slug or property id." };
+ }
+ if (!getProject(project_slug)) return { ok: false, error: "Project not found." };
+
+ const list = await listGscProperties(project_slug);
+ if (!list.ok) {
+ return {
+ ok: false,
+ error: `Couldn't verify property against GSC MCP: ${list.error}`,
+ };
+ }
+ const match = list.properties.find((p) => p.id === property_id);
+ if (!match) {
+ return {
+ ok: false,
+ error: `Property ${property_id} isn't in this bearer's reachable properties.`,
+ };
+ }
+ const updated = setProjectGscProperty(project_slug, match.id);
+ if (!updated) return { ok: false, error: "Project not found." };
+ revalidatePath("/", "layout");
+ return { ok: true, project: updated };
+}
+
+// ── Onboarding connect-step state ──────────────────────────────────
+//
+// The multi-MCP onboarding step renders one tile per recommended MCP
+// (Google Ads, Meta Ads, GSC) plus a "More" tile. Each tile needs:
+//
+// - is the MCP connected? (token row exists)
+// - is an account/property selected on the project row?
+// - the display name to label the tile
+//
+// We also surface a count of additional non-recommended connectors the
+// user has wired up via the "More" tile so the tile can show that
+// number ("More · 2 connected").
+
+export type ConnectedMcpState = {
+ /** True when an mcp_tokens row exists for this catalog_key. */
+ connected: boolean;
+ /**
+ * True when the user has picked a specific account/property for this MCP
+ * (i.e. the project column is non-null). Always false when not connected.
+ */
+ account_selected: boolean;
+};
+
+export type ConnectStepState = {
+ googleads: ConnectedMcpState;
+ metaads: ConnectedMcpState;
+ gsc: ConnectedMcpState;
+ /**
+ * Count of connected MCPs that aren't in the recommended trio
+ * (Stripe, Supabase, PostHog, …, plus any user-pasted custom servers).
+ */
+ extra_connected_count: number;
+ /**
+ * Project's website_url — used by the connect step to pre-load context
+ * about what the user is connecting tools for. Optional in the schema;
+ * propagated here for the redirect-target builder.
+ */
+ website_url: string | null;
+};
+
+export type GetConnectStepStateResult =
+ | { ok: true; state: ConnectStepState }
+ | { ok: false; error: string };
+
+export async function getConnectStepStateAction(
+ project_slug: string,
+): Promise<GetConnectStepStateResult> {
+ if (!project_slug.trim()) return { ok: false, error: "Missing project slug." };
+ const project = getProject(project_slug);
+ if (!project) return { ok: false, error: "Project not found." };
+
+ const { findMcpToken, listProjectMcpTokens } = await import(
+ "@/server/mcp/tokens"
+ );
+
+ const RECOMMENDED_KEYS = new Set([
+ "notfair-googleads",
+ "notfair-metaads",
+ "notfair-googlesearchconsole",
+ ]);
+ const allTokens = listProjectMcpTokens(project_slug);
+ const extra_connected_count = allTokens.filter(
+ (t) => !RECOMMENDED_KEYS.has(t.server_name),
+ ).length;
+
+ return {
+ ok: true,
+ state: {
+ googleads: {
+ connected: !!findMcpToken(project_slug, "notfair-googleads"),
+ account_selected: !!project.google_ads_account_id,
+ },
+ metaads: {
+ connected: !!findMcpToken(project_slug, "notfair-metaads"),
+ account_selected: !!project.meta_ads_account_id,
+ },
+ gsc: {
+ connected: !!findMcpToken(project_slug, "notfair-googlesearchconsole"),
+ account_selected: !!project.gsc_property_id,
+ },
+ extra_connected_count,
+ website_url: project.website_url,
+ },
+ };
+}
+
+// ── Shared RPC error formatter ─────────────────────────────────────
+
+function rpcErrorMessage(
+ rpcResult: Extract<
+ Awaited<ReturnType<typeof mcpRpcAutoRefresh>>,
+ { ok: false }
+ >,
+): string {
+ if (rpcResult.kind === "http_error") return `HTTP ${rpcResult.status}`;
+ if (rpcResult.kind === "rpc_error")
+ return `RPC ${rpcResult.code}: ${rpcResult.message}`;
+ if (rpcResult.kind === "timeout") return "MCP call timed out";
+ if (rpcResult.kind === "aborted") return "MCP call aborted";
+ if (rpcResult.kind === "malformed_response") return rpcResult.message;
+ return rpcResult.message;
+}
diff --git a/notfair-cmo/src/server/onboarding/agent-mcp-blocker.test.ts b/notfair-cmo/src/server/onboarding/agent-mcp-blocker.test.ts
new file mode 100644
index 00000000..eb74e3fd
--- /dev/null
+++ b/notfair-cmo/src/server/onboarding/agent-mcp-blocker.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, it, vi, beforeEach } from "vitest";
+
+const findMcpTokenMock = vi.fn();
+vi.mock("@/server/mcp/tokens", () => ({
+ findMcpToken: (...args: unknown[]) => findMcpTokenMock(...args),
+}));
+
+const getMcpCatalogMock = vi.fn(() => [
+ {
+ key: "notfair-googleads",
+ display_name: "NotFair Google Ads",
+ description: "",
+ resource_url: "https://notfair.co/api/mcp/google_ads",
+ discovery_url: "",
+ source: "preset" as const,
+ },
+ {
+ key: "notfair-metaads",
+ display_name: "NotFair Meta Ads",
+ description: "",
+ resource_url: "https://notfair.co/api/mcp/meta_ads",
+ discovery_url: "",
+ source: "preset" as const,
+ },
+]);
+vi.mock("@/server/mcp-catalog", () => ({
+ getMcpCatalog: (...args: unknown[]) => getMcpCatalogMock(...args),
+}));
+
+import { resolveAgentMcpBlocker } from "./agent-mcp-blocker";
+
+beforeEach(() => {
+ findMcpTokenMock.mockReset();
+});
+
+describe("resolveAgentMcpBlocker", () => {
+ it("returns null when template_key is undefined (cloned/custom agent)", () => {
+ expect(resolveAgentMcpBlocker("acme", undefined)).toBeNull();
+ expect(findMcpTokenMock).not.toHaveBeenCalled();
+ });
+
+ it("returns null for CMO — no requires_mcp_key on the template", () => {
+ expect(resolveAgentMcpBlocker("acme", "cmo")).toBeNull();
+ expect(findMcpTokenMock).not.toHaveBeenCalled();
+ });
+
+ it("returns a blocker when Google Ads agent's MCP isn't connected", () => {
+ findMcpTokenMock.mockReturnValue(null);
+ const result = resolveAgentMcpBlocker("acme", "google_ads");
+ expect(result).toEqual({
+ mcp_key: "notfair-googleads",
+ mcp_display_name: "NotFair Google Ads",
+ agent_display_name: "Google Ads",
+ });
+ expect(findMcpTokenMock).toHaveBeenCalledWith("acme", "notfair-googleads");
+ });
+
+ it("returns a blocker for Meta Ads when the MCP isn't connected", () => {
+ findMcpTokenMock.mockReturnValue(null);
+ const result = resolveAgentMcpBlocker("acme", "meta_ads");
+ expect(result).toEqual({
+ mcp_key: "notfair-metaads",
+ mcp_display_name: "NotFair Meta Ads",
+ agent_display_name: "Meta Ads",
+ });
+ });
+
+ it("returns null when the required MCP is connected (token row exists)", () => {
+ findMcpTokenMock.mockReturnValue({
+ id: "tok-1",
+ project_slug: "acme",
+ server_name: "notfair-googleads",
+ access_token_enc: "secret",
+ });
+ expect(resolveAgentMcpBlocker("acme", "google_ads")).toBeNull();
+ });
+
+ it("falls back to the template display_name when the catalog has no matching entry", () => {
+ getMcpCatalogMock.mockReturnValueOnce([]); // empty catalog this call
+ findMcpTokenMock.mockReturnValue(null);
+ const result = resolveAgentMcpBlocker("acme", "google_ads");
+ expect(result?.mcp_display_name).toBe("Google Ads");
+ });
+});
diff --git a/notfair-cmo/src/server/onboarding/agent-mcp-blocker.ts b/notfair-cmo/src/server/onboarding/agent-mcp-blocker.ts
new file mode 100644
index 00000000..08faead9
--- /dev/null
+++ b/notfair-cmo/src/server/onboarding/agent-mcp-blocker.ts
@@ -0,0 +1,49 @@
+import { templateForKey } from "@/server/agent-templates";
+import { findMcpToken } from "@/server/mcp/tokens";
+import { getMcpCatalog } from "@/server/mcp-catalog";
+import type { AgentTemplateKey } from "@/server/agent-templates";
+
+/**
+ * Pure predicate the agent layout calls to decide whether to render the
+ * "Connect <Platform> MCP" blocker instead of the agent's chat/tasks UI.
+ *
+ * Returns null when the agent can proceed (CMO and other tools-less
+ * templates, or specialists whose required MCP is connected). Returns a
+ * BlockerInfo when the agent's template declares a `requires_mcp_key`
+ * and that token row is missing from `mcp_tokens` for the project.
+ *
+ * Separate from rendering so the predicate is tractable to unit-test
+ * without spinning up React.
+ */
+
+export type AgentMcpBlocker = {
+ /** Catalog key the user needs to connect (e.g. "notfair-googleads"). */
+ mcp_key: string;
+ /** Display name shown in the blocker copy ("Google Ads"). */
+ mcp_display_name: string;
+ /** Agent display label for the secondary line ("the Meta Ads agent"). */
+ agent_display_name: string;
+};
+
+export function resolveAgentMcpBlocker(
+ project_slug: string,
+ template_key: AgentTemplateKey | undefined,
+): AgentMcpBlocker | null {
+ if (!template_key) return null;
+ const template = templateForKey(template_key);
+ if (!template?.requires_mcp_key) return null;
+
+ const token = findMcpToken(project_slug, template.requires_mcp_key);
+ if (token) return null;
+
+ // Pull the display name from the catalog so the blocker calls the
+ // connector by the same label the Connections page uses (the catalog
+ // is the source of truth — templates only carry the catalog *key*).
+ const catalog = getMcpCatalog(project_slug);
+ const entry = catalog.find((c) => c.key === template.requires_mcp_key);
+ return {
+ mcp_key: template.requires_mcp_key,
+ mcp_display_name: entry?.display_name ?? template.display_name,
+ agent_display_name: template.display_name,
+ };
+}
diff --git a/notfair-cmo/src/types/index.ts b/notfair-cmo/src/types/index.ts
index d79ad355..b3311b2d 100644
--- a/notfair-cmo/src/types/index.ts
+++ b/notfair-cmo/src/types/index.ts
@@ -14,6 +14,20 @@ export type Project = {
* Null until the user picks (or until /onboarding gets re-run).
*/
google_ads_account_id: string | null;
+ /**
+ * Selected Meta Ads ad-account id (e.g. "act_123456"). Same pattern as
+ * google_ads_account_id: the notfair-metaads bearer may grant access
+ * to multiple ad accounts, and onboarding asks the user to pick the
+ * one this project should target. Null until picked.
+ */
+ meta_ads_account_id: string | null;
+ /**
+ * Selected Google Search Console property id (e.g. "sc-domain:example.com"
+ * or "https://example.com/"). Same idea as the ad-account fields: the
+ * notfair-googlesearchconsole bearer may cover multiple verified
+ * properties, and we persist the chosen one. Null until picked.
+ */
+ gsc_property_id: string | null;
/**
* Optional inputs the user provided at onboarding so the CMO has a
* starting point for its first task (writing PROJECT.md). Both are