Open-source SEO, GEO, and marketing skills for AI agents.
feat(chat): banner to connect notfair-googleads MCP from Google Ads chat
Yuting Zhong1ac0f2b88687
diff --git a/src/app/(app)/agents/[agent]/chat/[thread]/page.tsx b/src/app/(app)/agents/[agent]/chat/[thread]/page.tsxindex fa94a453..fcbf789a 100644--- a/src/app/(app)/agents/[agent]/chat/[thread]/page.tsx+++ b/src/app/(app)/agents/[agent]/chat/[thread]/page.tsx@@ -9,17 +9,25 @@ import {listSessionsForAgent,loadSessionHistory,} from "@/server/openclaw/sessions";+import { storedMcpKey } from "@/server/mcp-catalog";+import { getMcpStatus } from "@/server/mcp-state";import { AgentChat } from "@/components/agent-chat";+import { GoogleAdsMcpBanner } from "@/components/google-ads-mcp-banner";+import { McpFlashBanner } from "@/components/mcp-flash-banner";import { ThreadSelector } from "@/components/thread-selector";type Params = { agent: string; thread: string };+type Search = { mcp_connected?: string; mcp_error?: string };export default async function AgentChatThreadPage({params,+ searchParams,}: {params: Promise<Params>;+ searchParams: Promise<Search>;}) {const { agent: agentSlug, thread: threadId } = await params;+ const { mcp_connected, mcp_error } = await searchParams;const project = await getActiveProject();if (!project) {@@ -71,8 +79,24 @@ export default async function AgentChatThreadPage({...allSessions,];+ // The Google Ads agent depends on the notfair-googleads MCP for live+ // account operations. When it isn't connected yet (or the token is stale),+ // surface a banner so the user can fix it in one click without leaving+ // the chat. Probe runs server-side with its own 2s timeout — same as the+ // Connections page — so a slow upstream can't gate the chat render.+ const googleAdsMcpStatus =+ resolved.template_key === "google_ads"+ ? await getMcpStatus(storedMcpKey(project.slug, "notfair-googleads"))+ : null;+return (<div className="flex h-full flex-col">+ <McpFlashBanner connected={mcp_connected} error={mcp_error} />++ {googleAdsMcpStatus && googleAdsMcpStatus.state !== "connected" && (+ <GoogleAdsMcpBanner status={googleAdsMcpStatus} />+ )}+<div className="flex items-center justify-between border-b bg-background/80 px-6 py-2 backdrop-blur"><div className="text-xs text-muted-foreground">{sessionsForDropdown.length === 0diff --git a/src/app/api/mcp-oauth/callback/route.ts b/src/app/api/mcp-oauth/callback/route.tsindex dd909eca..7a4bbe02 100644--- a/src/app/api/mcp-oauth/callback/route.ts+++ b/src/app/api/mcp-oauth/callback/route.ts@@ -31,7 +31,12 @@ export async function GET(request: Request) {return htmlErrorPage("This authorization link has expired or was already used.");}- const back = new URL("/connections", request.url);+ // The pending state may carry a `return_to` (e.g. the chat URL the user+ // started from). Default to /connections — that's where the MCP cards+ // live, so it's a sensible landing if no caller asked for somewhere else.+ // `return_to` is already sanitized in startMcpConnect to be a same-origin+ // path; URL() with a base will additionally reject anything malformed.+ const back = new URL(pending.return_to ?? "/connections", request.url);if (upstreamError) {back.searchParams.set(diff --git a/src/components/google-ads-mcp-banner.tsx b/src/components/google-ads-mcp-banner.tsxnew file mode 100644index 00000000..9b62e1fb--- /dev/null+++ b/src/components/google-ads-mcp-banner.tsx@@ -0,0 +1,136 @@+"use client";++import { useState } from "react";+import Link from "next/link";+import { Loader2, Plug, AlertTriangle } from "lucide-react";+import { Button } from "@/components/ui/button";+import { toast } from "sonner";+import { startMcpConnect } from "@/server/actions/mcp";+import type { McpRuntimeStatus } from "@/server/mcp-state";++type Props = {+ status: McpRuntimeStatus;+};++/**+ * Shown above the chat for the Google Ads agent when the notfair-googleads+ * MCP isn't usable yet. The Connect button kicks off the same OAuth flow as+ * the Connections page, but threads the current chat URL through as+ * `return_to` so the user lands back here on success.+ */+export function GoogleAdsMcpBanner({ status }: Props) {+ const [busy, setBusy] = useState(false);++ if (status.state === "connected") return null;++ const isStale = status.state === "stale_token";+ const isUnreachable = status.state === "unreachable";++ async function onConnect() {+ setBusy(true);+ try {+ // Captured at click time (vs. via useSearchParams) so we don't pull in+ // a hook that would force a Suspense boundary in the page above us.+ const return_to = window.location.pathname + window.location.search;+ const result = await startMcpConnect({+ mcp_key: "notfair-googleads",+ return_to,+ });+ if (!result.ok) {+ toast.error(result.error);+ setBusy(false);+ return;+ }+ // Cross-origin redirect: leave the SPA and head to the issuer.+ window.location.href = result.authorize_url;+ } catch (err) {+ toast.error(err instanceof Error ? err.message : String(err));+ setBusy(false);+ }+ }++ const { headline, detail, action } = copyFor(status);++ return (+ <div+ className="border-b bg-amber-50 px-6 py-3 dark:bg-amber-950/30"+ role="status"+ >+ <div className="mx-auto flex w-full max-w-3xl items-start gap-3">+ <div className="mt-0.5 flex size-7 shrink-0 items-center justify-center rounded-md bg-amber-100 text-amber-900 dark:bg-amber-900/50 dark:text-amber-200">+ {isStale || isUnreachable ? (+ <AlertTriangle className="size-4" />+ ) : (+ <Plug className="size-4" />+ )}+ </div>+ <div className="min-w-0 flex-1">+ <div className="text-sm font-medium text-amber-900 dark:text-amber-100">+ {headline}+ </div>+ <p className="mt-0.5 text-xs text-amber-900/80 dark:text-amber-100/80">+ {detail}{" "}+ <Link+ href="/connections"+ className="underline underline-offset-2 hover:text-amber-900 dark:hover:text-amber-50"+ >+ Manage connections+ </Link>+ </p>+ </div>+ <Button+ type="button"+ size="sm"+ onClick={onConnect}+ disabled={busy}+ className="shrink-0"+ >+ {busy ? (+ <Loader2 className="size-3.5 animate-spin" />+ ) : (+ <Plug className="size-3.5" />+ )}+ {action}+ </Button>+ </div>+ </div>+ );+}++function copyFor(status: McpRuntimeStatus): {+ headline: string;+ detail: string;+ action: string;+} {+ switch (status.state) {+ case "stale_token":+ return {+ headline: "Google Ads connection expired",+ action: "Reconnect",+ detail:+ "The NotFair Google Ads token was rejected. Reconnect to resume live account operations.",+ };+ case "unreachable":+ return {+ headline: "Google Ads connection is unreachable",+ action: "Reconnect",+ detail:+ "Couldn't reach the NotFair Google Ads MCP. The agent will run blind until this is restored.",+ };+ case "configured_no_token":+ return {+ headline: "Google Ads MCP needs a token",+ action: "Connect",+ detail:+ "Connect to enable live campaign, keyword, bid, and budget operations against your account.",+ };+ case "not_configured":+ default:+ return {+ headline: "Connect NotFair Google Ads to go live",+ action: "Connect",+ detail:+ "Connect the MCP to let this agent run campaigns, manage keywords, and pull real metrics from your account.",+ };+ }+}diff --git a/src/server/actions/mcp.ts b/src/server/actions/mcp.tsindex 1eaa3a0d..c85e39b5 100644--- a/src/server/actions/mcp.ts+++ b/src/server/actions/mcp.ts@@ -21,6 +21,12 @@ export type StartMcpConnectResult =*/export async function startMcpConnect(input: {mcp_key: string;+ /**+ * Same-origin path to bounce back to after the callback. Anything that+ * doesn't look like a local path (no leading `/`, or `//` protocol-relative)+ * is dropped — the callback will use the default `/connections` instead.+ */+ return_to?: string;}): Promise<StartMcpConnectResult> {const spec = mcpSpecByKey(input.mcp_key);if (!spec) return { ok: false, error: `Unknown MCP key: ${input.mcp_key}` };@@ -67,6 +73,7 @@ export async function startMcpConnect(input: {code_verifier,redirect_uri,project_slug: project.slug,+ return_to: sanitizeReturnTo(input.return_to),created_at: Date.now(),});@@ -207,3 +214,16 @@ function humanError(err: unknown): string {if (err instanceof Error) return err.message;return String(err);}++/**+ * Accept only same-origin, path-only redirect targets. Anything with a scheme+ * or a `//` prefix would let a caller redirect the user off-site after OAuth,+ * which is an open-redirect class bug. Returns undefined when the input+ * isn't a safe local path, so the callback falls back to /connections.+ */+function sanitizeReturnTo(raw: string | undefined): string | undefined {+ if (!raw) return undefined;+ if (!raw.startsWith("/")) return undefined;+ if (raw.startsWith("//")) return undefined;+ return raw;+}diff --git a/src/server/mcp-pending.ts b/src/server/mcp-pending.tsindex 56dda5d9..89174c38 100644--- a/src/server/mcp-pending.ts+++ b/src/server/mcp-pending.ts@@ -33,6 +33,12 @@ export type PendingMcpFlow = {redirect_uri: string;/** Project slug (the active project at the time the flow started). */project_slug: string;+ /**+ * Local path to redirect to after the callback finishes (e.g. the chat+ * URL the user started from). Validated to be same-origin/path-only when+ * stashed. Falls back to /connections when absent.+ */+ return_to?: string;created_at: number;};