Open-source SEO, GEO, and marketing skills for AI agents.
feat(notfair-cmo): silent OAuth refresh for MCP connections (0.4.1)
Yuting Zhong93e07f4d71b3
diff --git a/notfair-cmo/CHANGELOG.md b/notfair-cmo/CHANGELOG.mdindex af139a4e..4907e587 100644--- a/notfair-cmo/CHANGELOG.md+++ b/notfair-cmo/CHANGELOG.md@@ -1,5 +1,17 @@# notfair-cmo+## 0.4.1 — 2026-06-01++**Silent OAuth refresh for MCP connections.** The Connections page stopped flapping to "token expired" every hour for providers with short-lived access tokens (Stripe, Mixpanel, Supabase, PostHog). The MCP OAuth callback used to discard the `refresh_token`, `expires_in`, and `scope` fields from the token-endpoint response and store only the access token — so when the upstream rotated it (~1h for most providers), the only recovery path was a manual "Reconnect" click.++The callback now captures the full token envelope and persists the token endpoint + DCR-issued `client_id` / `client_secret` alongside it (new migration `013`). A new `mcpRpcAutoRefresh` wrapper proactively swaps an expiring access token (within 60s) and reactively retries once on HTTP 401, rotating the stored pair when the provider issues a new refresh token (RFC 6749 §6).++Existing token rows (created before this release) have no refresh token captured, so they continue to fall through to the existing reconnect-on-401 UX. After one fresh reconnect they pick up silent refresh.++**Probe + tool-list + onboarding's account picker** now route through `mcpRpcAutoRefresh`, so the status badge, the View tools dialog, and Google Ads account selection all stay green across the access-token TTL boundary instead of flashing stale_token between refreshes.++**Stripe (and any AS that gates refresh tokens on client capability) now issues one.** Dynamic client registration now advertises `grant_types: ["authorization_code", "refresh_token"]` per [SEP-2207](https://modelcontextprotocol.io/seps/2207-oidc-refresh-token-guidance). Without it, Stripe's MCP authorization server returned only an access token at consent time — forcing a manual reconnect every ~1h. After this change, reconnecting Stripe captures a refresh token alongside the access token, and silent rotation works the same as it does for Supabase and Mixpanel.+## 0.4.0 — 2026-05-31Redesigned Connections page + curated "Browse connectors" UX. The catalog now ships with a small directory of trusted MCPs you opt into; clicking a tile adds it to the project and starts OAuth in one step. The page itself was rebuilt as an editorial list with a top-right "Add server" menu.diff --git a/notfair-cmo/package.json b/notfair-cmo/package.jsonindex 6d835554..b458d951 100644--- a/notfair-cmo/package.json+++ b/notfair-cmo/package.json@@ -1,6 +1,6 @@{"name": "notfair-cmo",- "version": "0.4.0",+ "version": "0.4.1","description": "Open-source AI marketing CMO portal. Run locally; orchestrates marketing agents (Google Ads, SEO, and more) on top of Claude Code, Codex, or other local AI coding agents.","license": "MIT","bin": {diff --git a/notfair-cmo/scripts/force-refresh-mcp-tokens.ts b/notfair-cmo/scripts/force-refresh-mcp-tokens.tsnew file mode 100644index 00000000..28db4b19--- /dev/null+++ b/notfair-cmo/scripts/force-refresh-mcp-tokens.ts@@ -0,0 +1,115 @@+/**+ * One-off: force the MCP refresh path against live tokens.+ *+ * For each (project_slug, server_name) pair on argv (or a default set), this+ * loads the stored row, calls refreshMcpToken(), and prints a short summary+ * showing whether the access token actually rotated and whether the refresh+ * token rotated alongside it.+ *+ * Usage:+ * pnpm tsx scripts/force-refresh-mcp-tokens.ts+ * pnpm tsx scripts/force-refresh-mcp-tokens.ts demo1 stripe demo1 supabase+ */+import { findMcpToken } from "../src/server/mcp/tokens";+import { refreshMcpToken, isExpiringSoon } from "../src/server/mcp/refresh";++const DEFAULT_TARGETS: Array<[string, string]> = [+ ["demo1", "supabase"],+ ["demo1", "mixpanel"],+ ["demo1", "stripe"],+ ["demo1", "posthog"],+ ["demo1", "notfair-googleads"],+ ["demo1", "notfair-meta-ads"],+];++function tailMask(s: string | null, head = 6, tail = 4): string {+ if (!s) return "<null>";+ if (s.length <= head + tail + 1) return `${s.slice(0, head)}…`;+ return `${s.slice(0, head)}…${s.slice(-tail)} (len=${s.length})`;+}++function ms(value: string | null): string {+ if (!value) return "<null>";+ const t = Date.parse(value);+ if (Number.isNaN(t)) return value;+ const deltaMs = t - Date.now();+ const mins = Math.round(deltaMs / 60_000);+ return `${value} (${deltaMs >= 0 ? "+" : ""}${mins}m)`;+}++async function refreshOne(project_slug: string, server_name: string): Promise<void> {+ console.log(`\n── ${project_slug}/${server_name} ────────────────────`);+ const before = findMcpToken(project_slug, server_name);+ if (!before) {+ console.log(" no row stored — skip");+ return;+ }++ console.log(" before:");+ console.log(` access_token = ${tailMask(before.access_token_enc)}`);+ console.log(` refresh_token = ${tailMask(before.refresh_token_enc)}`);+ console.log(` expires_at = ${ms(before.expires_at)}`);+ console.log(` token_endpoint= ${before.token_endpoint ?? "<null>"}`);+ console.log(` client_id = ${before.client_id ?? "<null>"}`);+ console.log(` has client_secret = ${before.client_secret ? "yes" : "no"}`);+ console.log(` is expiring soon (default 60s) = ${isExpiringSoon(before)}`);++ if (!before.refresh_token_enc || !before.token_endpoint || !before.client_id) {+ console.log(+ " ⇒ refresh path will short-circuit (missing refresh_token/token_endpoint/client_id)",+ );+ }++ const refreshed = await refreshMcpToken(before);++ if (!refreshed) {+ console.log(" ❌ refreshMcpToken returned null");+ return;+ }++ const accessRotated = refreshed.access_token_enc !== before.access_token_enc;+ const refreshRotated =+ refreshed.refresh_token_enc !== before.refresh_token_enc;++ console.log(" after:");+ console.log(+ ` access_token = ${tailMask(refreshed.access_token_enc)} ${+ accessRotated ? "✅ ROTATED" : "(same)"+ }`,+ );+ console.log(+ ` refresh_token = ${tailMask(refreshed.refresh_token_enc)} ${+ refreshRotated ? "🔁 ROTATED" : "(same)"+ }`,+ );+ console.log(` expires_at = ${ms(refreshed.expires_at)}`);+ console.log(` ✅ refresh succeeded`);+}++async function main(): Promise<void> {+ const argv = process.argv.slice(2);+ const targets: Array<[string, string]> = [];+ if (argv.length === 0) {+ targets.push(...DEFAULT_TARGETS);+ } else if (argv.length % 2 !== 0) {+ console.error("Args must come in (project_slug, server_name) pairs");+ process.exit(2);+ } else {+ for (let i = 0; i < argv.length; i += 2) {+ targets.push([argv[i]!, argv[i + 1]!]);+ }+ }++ for (const [slug, name] of targets) {+ try {+ await refreshOne(slug, name);+ } catch (err) {+ console.error(` ❌ threw: ${err instanceof Error ? err.message : String(err)}`);+ }+ }+}++main().catch((err) => {+ console.error(err);+ process.exit(1);+});diff --git a/notfair-cmo/src/app/api/mcp-oauth/callback/route.ts b/notfair-cmo/src/app/api/mcp-oauth/callback/route.tsindex adde4761..90bc42a3 100644--- a/notfair-cmo/src/app/api/mcp-oauth/callback/route.ts+++ b/notfair-cmo/src/app/api/mcp-oauth/callback/route.ts@@ -63,7 +63,12 @@ export async function GET(request: Request) {});if (pending.client_secret) body.set("client_secret", pending.client_secret);- let access_token: string;+ let tokenEnvelope: {+ access_token: string;+ refresh_token?: string;+ expires_in?: number;+ scope?: string;+ };try {const res = await fetch(pending.token_endpoint, {method: "POST",@@ -81,12 +86,22 @@ export async function GET(request: Request) {);return NextResponse.redirect(back);}- const parsed = JSON.parse(text) as { access_token?: string };+ const parsed = JSON.parse(text) as {+ access_token?: string;+ refresh_token?: string;+ expires_in?: number;+ scope?: string;+ };if (!parsed.access_token) {back.searchParams.set("mcp_error", "Token endpoint returned no access_token.");return NextResponse.redirect(back);}- access_token = parsed.access_token;+ tokenEnvelope = {+ access_token: parsed.access_token,+ refresh_token: parsed.refresh_token,+ expires_in: parsed.expires_in,+ scope: parsed.scope,+ };} catch (err) {back.searchParams.set("mcp_error",@@ -95,8 +110,30 @@ export async function GET(request: Request) {return NextResponse.redirect(back);}+ // Compute absolute expiry only when the provider advertised expires_in.+ // For providers that omit it (rare, but legal under RFC 6749), we leave+ // expires_at NULL and rely on reactive refresh-on-401.+ const expires_at =+ typeof tokenEnvelope.expires_in === "number"+ ? new Date(Date.now() + tokenEnvelope.expires_in * 1000).toISOString()+ : undefined;+try {- await setMcpBearer(pending.project_slug, pending.catalog_key, access_token);+ await setMcpBearer(+ pending.project_slug,+ pending.catalog_key,+ tokenEnvelope.access_token,+ {+ refresh_token: tokenEnvelope.refresh_token,+ expires_at,+ scope: tokenEnvelope.scope,+ // Stash everything the refresh helper needs so it can rotate the+ // access token later without bouncing through consent again.+ token_endpoint: pending.token_endpoint,+ client_id: pending.client_id,+ client_secret: pending.client_secret,+ },+ );} catch (err) {const raw = err instanceof Error ? err.message : String(err);// Scrub bearers + any oat_ token shape before exposing in the URL —diff --git a/notfair-cmo/src/server/actions/mcp.ts b/notfair-cmo/src/server/actions/mcp.tsindex 8e3aceb6..e78ce1dd 100644--- a/notfair-cmo/src/server/actions/mcp.ts+++ b/notfair-cmo/src/server/actions/mcp.ts@@ -137,18 +137,14 @@ export async function listMcpToolsAction(input: {if (!project) {return { ok: false, error: "No active project." };}- const { getMcpConfig, mcpRpc } = await import("@/server/mcp/rpc");+ const { getMcpConfig, mcpRpcAutoRefresh } = await import("@/server/mcp/rpc");const cfg = getMcpConfig(project.slug, input.mcp_key);if (!cfg) {return { ok: false, error: "MCP is not configured for this project." };}- const r = await mcpRpc<{ tools?: Array<{ name?: unknown; description?: unknown; inputSchema?: unknown }> }>(- cfg.url,- cfg.token,- "tools/list",- {},- { timeoutMs: 5_000 },- );+ const r = await mcpRpcAutoRefresh<{+ tools?: Array<{ name?: unknown; description?: unknown; inputSchema?: unknown }>;+ }>(project.slug, input.mcp_key, "tools/list", {}, { timeoutMs: 5_000 });if (!r.ok) {const message =r.kind === "http_error"@@ -561,10 +557,19 @@ async function dynamicRegister(// require a confidential client; for those we register as// `client_secret_post` — the AS returns a client_secret which the// callback then sends alongside the code at token exchange.+ //+ // grant_types includes `refresh_token` per SEP-2207 ("OIDC-Flavored+ // Refresh Token Guidance", accepted 2026-02-04). Some Authorization+ // Servers (notably Stripe's MCP) only issue refresh tokens to clients+ // that explicitly register the capability — without this we still get+ // a working access token but the user is forced to reconnect when it+ // expires (~1h for Stripe). Servers that don't support refresh_token+ // grant either ignore the extra entry or reject it; in the latter case+ // we'd fall back to the authorization_code-only registration anyway.const body = {client_name: "notfair-cmo",redirect_uris: [redirect_uri],- grant_types: ["authorization_code"],+ grant_types: ["authorization_code", "refresh_token"],response_types: ["code"],token_endpoint_auth_method: auth_method,};diff --git a/notfair-cmo/src/server/db/migrations.ts b/notfair-cmo/src/server/db/migrations.tsindex 3790b7fc..8f429f9d 100644--- a/notfair-cmo/src/server/db/migrations.ts+++ b/notfair-cmo/src/server/db/migrations.ts@@ -520,6 +520,28 @@ CREATE INDEX IF NOT EXISTS idx_user_mcp_servers_project ON user_mcp_servers(projALTER TABLE projectsADD COLUMN hidden_mcp_preset_keys_json TEXT NOT NULL DEFAULT '[]';+`,+ },+ {+ name: "013_mcp_token_oauth_client.sql",+ sql: `+-- Migration 013: persist OAuth client + token endpoint on mcp_tokens.+--+-- Refresh-token rotation needs three things at runtime: the token endpoint+-- URL, the dynamically-registered client_id, and (where the server requires+-- it) the client_secret. We have all three in mcp_oauth_pending during the+-- authorize flow but used to throw them away after the callback finished.+-- Persisting them here lets the refresh helper exchange a refresh_token for+-- a fresh access_token without bouncing the user back through consent.+--+-- All three columns are nullable. Pre-existing rows (created before this+-- migration) have no refresh_token captured either, so they fall through to+-- the "reconnect to fix" path on next 401 — exactly the behavior they had+-- before. New rows written by the patched callback will populate them.++ALTER TABLE mcp_tokens ADD COLUMN token_endpoint TEXT;+ALTER TABLE mcp_tokens ADD COLUMN client_id TEXT;+ALTER TABLE mcp_tokens ADD COLUMN client_secret TEXT;`,},];diff --git a/notfair-cmo/src/server/db/migrations/013_mcp_token_oauth_client.sql b/notfair-cmo/src/server/db/migrations/013_mcp_token_oauth_client.sqlnew file mode 100644index 00000000..4c460744--- /dev/null+++ b/notfair-cmo/src/server/db/migrations/013_mcp_token_oauth_client.sql@@ -0,0 +1,17 @@+-- Migration 013: persist OAuth client + token endpoint on mcp_tokens.+--+-- Refresh-token rotation needs three things at runtime: the token endpoint+-- URL, the dynamically-registered client_id, and (where the server requires+-- it) the client_secret. We have all three in mcp_oauth_pending during the+-- authorize flow but used to throw them away after the callback finished.+-- Persisting them here lets the refresh helper exchange a refresh_token for+-- a fresh access_token without bouncing the user back through consent.+--+-- All three columns are nullable. Pre-existing rows (created before this+-- migration) have no refresh_token captured either, so they fall through to+-- the "reconnect to fix" path on next 401 — exactly the behavior they had+-- before. New rows written by the patched callback will populate them.++ALTER TABLE mcp_tokens ADD COLUMN token_endpoint TEXT;+ALTER TABLE mcp_tokens ADD COLUMN client_id TEXT;+ALTER TABLE mcp_tokens ADD COLUMN client_secret TEXT;diff --git a/notfair-cmo/src/server/mcp/refresh.test.ts b/notfair-cmo/src/server/mcp/refresh.test.tsnew file mode 100644index 00000000..93077377--- /dev/null+++ b/notfair-cmo/src/server/mcp/refresh.test.ts@@ -0,0 +1,221 @@+import Database from "better-sqlite3";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { MIGRATIONS } from "@/server/db/migrations";++let testDb: Database.Database;++vi.mock("@/server/db/db", () => ({+ getDb: () => testDb,+ getDbPath: () => ":memory:",+}));++import { refreshMcpToken, isExpiringSoon } from "./refresh";+import { findMcpToken, upsertMcpToken, type McpToken } from "./tokens";++function applyMigrations(db: Database.Database): void {+ for (const migration of MIGRATIONS) db.exec(migration.sql);+}++function seedProject(slug = "acme"): void {+ testDb+ .prepare(+ "INSERT INTO projects (id, slug, display_name, created_at) VALUES (?, ?, ?, ?)",+ )+ .run("p-" + slug, slug, slug, "2026-01-01T00:00:00.000Z");+}++function makeToken(overrides: Partial<McpToken> = {}): McpToken {+ seedProject();+ const row = upsertMcpToken({+ project_slug: "acme",+ server_name: "stripe",+ access_token: overrides.access_token_enc ?? "old-at",+ refresh_token: overrides.refresh_token_enc ?? "rt-1",+ expires_at: overrides.expires_at ?? "2026-01-01T00:00:00.000Z",+ token_endpoint: overrides.token_endpoint ?? "https://auth.example.com/token",+ client_id: overrides.client_id ?? "client-abc",+ client_secret: overrides.client_secret ?? "shh",+ });+ return row;+}++beforeEach(() => {+ testDb = new Database(":memory:");+ testDb.pragma("foreign_keys = ON");+ applyMigrations(testDb);+});++afterEach(() => {+ testDb.close();+ vi.restoreAllMocks();+});++describe("refreshMcpToken", () => {+ it("exchanges refresh_token for a fresh access_token and persists it", async () => {+ const token = makeToken();+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({ access_token: "new-at", expires_in: 3600 }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ ),+ ),+ );++ const refreshed = await refreshMcpToken(token);+ expect(refreshed).not.toBeNull();+ expect(refreshed!.access_token_enc).toBe("new-at");+ expect(refreshed!.refresh_token_enc).toBe("rt-1");+ expect(Date.parse(refreshed!.expires_at!)).toBeGreaterThan(Date.now() + 3500 * 1000);++ const stored = findMcpToken("acme", "stripe");+ expect(stored!.access_token_enc).toBe("new-at");+ });++ it("rotates the refresh_token when the provider returns a new one", async () => {+ const token = makeToken();+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ access_token: "new-at",+ refresh_token: "rt-2",+ expires_in: 3600,+ }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ ),+ ),+ );++ const refreshed = await refreshMcpToken(token);+ expect(refreshed!.refresh_token_enc).toBe("rt-2");+ });++ it("returns null when the row has no refresh_token (legacy)", async () => {+ seedProject();+ const legacy = upsertMcpToken({+ project_slug: "acme",+ server_name: "stripe",+ access_token: "old-at",+ token_endpoint: "https://auth.example.com/token",+ client_id: "client-abc",+ });+ const fetchSpy = vi.fn();+ vi.stubGlobal("fetch", fetchSpy);++ expect(await refreshMcpToken(legacy)).toBeNull();+ expect(fetchSpy).not.toHaveBeenCalled();+ });++ it("returns null when the row has no token_endpoint (legacy)", async () => {+ seedProject();+ const legacy = upsertMcpToken({+ project_slug: "acme",+ server_name: "stripe",+ access_token: "old-at",+ refresh_token: "rt-1",+ client_id: "client-abc",+ });+ const fetchSpy = vi.fn();+ vi.stubGlobal("fetch", fetchSpy);++ expect(await refreshMcpToken(legacy)).toBeNull();+ expect(fetchSpy).not.toHaveBeenCalled();+ });++ it("returns null on 4xx (revoked refresh token) without trashing the row", async () => {+ const token = makeToken();+ vi.stubGlobal(+ "fetch",+ vi+ .fn()+ .mockResolvedValue(new Response("invalid_grant", { status: 400 })),+ );++ expect(await refreshMcpToken(token)).toBeNull();+ const stored = findMcpToken("acme", "stripe");+ expect(stored!.access_token_enc).toBe("old-at");+ expect(stored!.refresh_token_enc).toBe("rt-1");+ });++ it("returns null on network error", async () => {+ const token = makeToken();+ vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("ECONNREFUSED")));+ expect(await refreshMcpToken(token)).toBeNull();+ });++ it("omits client_secret when not stored (public client)", async () => {+ seedProject();+ const publicClient = upsertMcpToken({+ project_slug: "acme",+ server_name: "stripe",+ access_token: "old-at",+ refresh_token: "rt-1",+ token_endpoint: "https://auth.example.com/token",+ client_id: "client-abc",+ // no client_secret+ });+ const fetchSpy = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({ access_token: "new-at", expires_in: 3600 }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ ),+ );+ vi.stubGlobal("fetch", fetchSpy);++ await refreshMcpToken(publicClient);+ const call = fetchSpy.mock.calls[0];+ const body = call[1].body as string;+ expect(body).toContain("grant_type=refresh_token");+ expect(body).toContain("client_id=client-abc");+ expect(body).not.toContain("client_secret");+ });+});++describe("isExpiringSoon", () => {+ function row(expires_at: string | null): McpToken {+ return {+ id: "x",+ project_slug: "acme",+ server_name: "stripe",+ account_label: "",+ access_token_enc: "at",+ refresh_token_enc: null,+ expires_at,+ scope: null,+ metadata_json: null,+ token_endpoint: null,+ client_id: null,+ client_secret: null,+ created_at: new Date().toISOString(),+ updated_at: new Date().toISOString(),+ };+ }++ it("returns true when expires_at is in the past", () => {+ expect(isExpiringSoon(row("2020-01-01T00:00:00.000Z"))).toBe(true);+ });++ it("returns true when expires_at is within the skew window", () => {+ const soon = new Date(Date.now() + 30_000).toISOString();+ expect(isExpiringSoon(row(soon))).toBe(true);+ });++ it("returns false when expires_at is comfortably in the future", () => {+ const later = new Date(Date.now() + 10 * 60_000).toISOString();+ expect(isExpiringSoon(row(later))).toBe(false);+ });++ it("returns false when expires_at is null (unknown)", () => {+ expect(isExpiringSoon(row(null))).toBe(false);+ });++ it("respects a custom skew", () => {+ const inTwoMin = new Date(Date.now() + 2 * 60_000).toISOString();+ expect(isExpiringSoon(row(inTwoMin), 30_000)).toBe(false);+ expect(isExpiringSoon(row(inTwoMin), 5 * 60_000)).toBe(true);+ });+});diff --git a/notfair-cmo/src/server/mcp/refresh.ts b/notfair-cmo/src/server/mcp/refresh.tsnew file mode 100644index 00000000..ef01e113--- /dev/null+++ b/notfair-cmo/src/server/mcp/refresh.ts@@ -0,0 +1,108 @@+import { updateMcpTokenSecrets, type McpToken } from "./tokens";++/**+ * Exchange a stored refresh_token for a fresh access_token at the upstream+ * OAuth token endpoint, persist the rotated pair, and return the updated row.+ *+ * Returns `null` (and leaves the row alone) when:+ * - the row has no refresh_token / token_endpoint / client_id stored+ * (legacy rows from before migration 013 + callback fix), OR+ * - the token endpoint rejects the refresh (revoked, expired, scope drift).+ *+ * Callers should treat `null` as "the user must reconnect" and surface the+ * existing stale-token UX. We deliberately don't delete the row on a failed+ * refresh — the user might be offline, and a transient 5xx shouldn't nuke+ * their connection.+ */+export async function refreshMcpToken(token: McpToken): Promise<McpToken | null> {+ if (!token.refresh_token_enc || !token.token_endpoint || !token.client_id) {+ return null;+ }++ const body = new URLSearchParams({+ grant_type: "refresh_token",+ refresh_token: token.refresh_token_enc,+ client_id: token.client_id,+ });+ if (token.client_secret) body.set("client_secret", token.client_secret);++ let res: Response;+ try {+ res = await fetch(token.token_endpoint, {+ method: "POST",+ headers: {+ "Content-Type": "application/x-www-form-urlencoded",+ Accept: "application/json",+ },+ body: body.toString(),+ });+ } catch (err) {+ console.warn(+ `[mcp-refresh] network error refreshing ${token.server_name}:`,+ err instanceof Error ? err.message : String(err),+ );+ return null;+ }++ if (!res.ok) {+ // Don't log the body — refresh failures from some providers echo the+ // refresh token verbatim in the error payload. Status is enough to+ // distinguish "token revoked" (4xx) from "provider hiccup" (5xx).+ console.warn(+ `[mcp-refresh] ${token.server_name} refresh failed: HTTP ${res.status}`,+ );+ return null;+ }++ let parsed: {+ access_token?: string;+ refresh_token?: string;+ expires_in?: number;+ };+ try {+ parsed = (await res.json()) as typeof parsed;+ } catch (err) {+ console.warn(+ `[mcp-refresh] ${token.server_name} returned non-JSON body:`,+ err instanceof Error ? err.message : String(err),+ );+ return null;+ }++ if (!parsed.access_token) {+ console.warn(`[mcp-refresh] ${token.server_name} response missing access_token`);+ return null;+ }++ const expires_at =+ typeof parsed.expires_in === "number"+ ? new Date(Date.now() + parsed.expires_in * 1000).toISOString()+ : null;++ return updateMcpTokenSecrets(token.id, {+ access_token: parsed.access_token,+ // Per RFC 6749 §6, the response MAY include a new refresh_token. When+ // present, providers expect us to replace the old one (Stripe rotates,+ // Google doesn't). When absent, COALESCE in updateMcpTokenSecrets keeps+ // the existing one.+ refresh_token: parsed.refresh_token ?? null,+ expires_at,+ });+}++/**+ * True iff the access token is either expired or within `skewMs` of expiry.+ * Used to decide whether to refresh proactively before an MCP RPC. We keep+ * the skew tight (default 60s) so we don't refresh every single call — only+ * when we're actually close to a 401.+ *+ * Rows with no `expires_at` (legacy or providers that omit `expires_in`)+ * return `false`: we can't tell if they're expiring, so we let the call+ * proceed and rely on the 401 reactive path.+ */+export function isExpiringSoon(token: McpToken, skewMs = 60_000): boolean {+ if (!token.expires_at) return false;+ const expiresMs = Date.parse(token.expires_at);+ if (Number.isNaN(expiresMs)) return false;+ return expiresMs - Date.now() < skewMs;+}diff --git a/notfair-cmo/src/server/mcp/rpc.test.ts b/notfair-cmo/src/server/mcp/rpc.test.tsnew file mode 100644index 00000000..5fef8f51--- /dev/null+++ b/notfair-cmo/src/server/mcp/rpc.test.ts@@ -0,0 +1,207 @@+import Database from "better-sqlite3";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { MIGRATIONS } from "@/server/db/migrations";++let testDb: Database.Database;++vi.mock("@/server/db/db", () => ({+ getDb: () => testDb,+ getDbPath: () => ":memory:",+}));++import { mcpRpcAutoRefresh } from "./rpc";+import { findMcpToken, upsertMcpToken } from "./tokens";++const PRESET_KEY = "notfair-googleads";+const PRESET_URL = "https://notfair.co/api/mcp/google_ads";++function applyMigrations(db: Database.Database): void {+ for (const migration of MIGRATIONS) db.exec(migration.sql);+}++function seedProject(slug = "acme"): void {+ testDb+ .prepare(+ "INSERT INTO projects (id, slug, display_name, created_at) VALUES (?, ?, ?, ?)",+ )+ .run("p-" + slug, slug, slug, "2026-01-01T00:00:00.000Z");+}++function rpcOk(body: unknown): Response {+ return new Response(JSON.stringify({ jsonrpc: "2.0", id: 1, result: body }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+}++function http401(): Response {+ return new Response("unauthorized", { status: 401 });+}++beforeEach(() => {+ testDb = new Database(":memory:");+ testDb.pragma("foreign_keys = ON");+ applyMigrations(testDb);+ seedProject();+});++afterEach(() => {+ testDb.close();+ vi.restoreAllMocks();+});++describe("mcpRpcAutoRefresh", () => {+ it("returns 401 when no token row exists", async () => {+ const fetchSpy = vi.fn();+ vi.stubGlobal("fetch", fetchSpy);+ const r = await mcpRpcAutoRefresh("acme", PRESET_KEY, "initialize");+ expect(r.ok).toBe(false);+ if (!r.ok && r.kind === "http_error") {+ expect(r.status).toBe(401);+ }+ expect(fetchSpy).not.toHaveBeenCalled();+ });++ it("returns 404 when the catalog key is unknown", async () => {+ upsertMcpToken({+ project_slug: "acme",+ server_name: "ghost",+ access_token: "at",+ });+ const r = await mcpRpcAutoRefresh("acme", "ghost", "initialize");+ expect(r.ok).toBe(false);+ if (!r.ok && r.kind === "http_error") expect(r.status).toBe(404);+ });++ it("calls mcpRpc with the stored access token (happy path)", async () => {+ upsertMcpToken({+ project_slug: "acme",+ server_name: PRESET_KEY,+ access_token: "at-1",+ expires_at: new Date(Date.now() + 60 * 60_000).toISOString(),+ });+ const fetchSpy = vi.fn().mockResolvedValue(rpcOk({ ok: true }));+ vi.stubGlobal("fetch", fetchSpy);++ const r = await mcpRpcAutoRefresh("acme", PRESET_KEY, "initialize");+ expect(r.ok).toBe(true);+ expect(fetchSpy).toHaveBeenCalledTimes(1);+ const headers = fetchSpy.mock.calls[0][1].headers;+ expect(headers.Authorization).toBe("Bearer at-1");+ });++ it("refreshes proactively when expires_at is within the skew window", async () => {+ upsertMcpToken({+ project_slug: "acme",+ server_name: PRESET_KEY,+ access_token: "stale-at",+ refresh_token: "rt-1",+ expires_at: new Date(Date.now() + 10_000).toISOString(), // 10s away+ token_endpoint: "https://auth.example.com/token",+ client_id: "client-abc",+ client_secret: "shh",+ });++ const fetchSpy = vi+ .fn()+ // 1st call: refresh+ .mockResolvedValueOnce(+ new Response(+ JSON.stringify({ access_token: "fresh-at", expires_in: 3600 }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ ),+ )+ // 2nd call: actual RPC against the MCP resource+ .mockResolvedValueOnce(rpcOk({ ok: true }));+ vi.stubGlobal("fetch", fetchSpy);++ const r = await mcpRpcAutoRefresh("acme", PRESET_KEY, "initialize");+ expect(r.ok).toBe(true);+ expect(fetchSpy).toHaveBeenCalledTimes(2);+ expect(fetchSpy.mock.calls[0][0]).toBe("https://auth.example.com/token");+ expect(fetchSpy.mock.calls[1][0]).toBe(PRESET_URL);+ expect(fetchSpy.mock.calls[1][1].headers.Authorization).toBe("Bearer fresh-at");+ expect(findMcpToken("acme", PRESET_KEY)!.access_token_enc).toBe("fresh-at");+ });++ it("refreshes reactively on 401 and retries once", async () => {+ upsertMcpToken({+ project_slug: "acme",+ server_name: PRESET_KEY,+ access_token: "stale-at",+ refresh_token: "rt-1",+ expires_at: new Date(Date.now() + 60 * 60_000).toISOString(), // not soon+ token_endpoint: "https://auth.example.com/token",+ client_id: "client-abc",+ });+ // Backdate updated_at so the reactive guard ("just refreshed") doesn't+ // suppress the retry.+ testDb+ .prepare("UPDATE mcp_tokens SET updated_at = ? WHERE project_slug = ?")+ .run(new Date(Date.now() - 60_000).toISOString(), "acme");++ const fetchSpy = vi+ .fn()+ .mockResolvedValueOnce(http401()) // first RPC: 401+ .mockResolvedValueOnce(+ new Response(+ JSON.stringify({ access_token: "fresh-at", expires_in: 3600 }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ ),+ )+ .mockResolvedValueOnce(rpcOk({ ok: true }));+ vi.stubGlobal("fetch", fetchSpy);++ const r = await mcpRpcAutoRefresh("acme", PRESET_KEY, "initialize");+ expect(r.ok).toBe(true);+ expect(fetchSpy).toHaveBeenCalledTimes(3);+ expect(fetchSpy.mock.calls[2][1].headers.Authorization).toBe("Bearer fresh-at");+ });++ it("does not loop refresh when the fresh token also 401s", async () => {+ upsertMcpToken({+ project_slug: "acme",+ server_name: PRESET_KEY,+ access_token: "stale-at",+ refresh_token: "rt-1",+ expires_at: new Date(Date.now() + 5_000).toISOString(), // triggers proactive refresh+ token_endpoint: "https://auth.example.com/token",+ client_id: "client-abc",+ });++ const fetchSpy = vi+ .fn()+ // proactive refresh+ .mockResolvedValueOnce(+ new Response(+ JSON.stringify({ access_token: "fresh-but-still-bad", expires_in: 3600 }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ ),+ )+ // RPC still 401s (e.g. server invalidated the session)+ .mockResolvedValueOnce(http401());+ vi.stubGlobal("fetch", fetchSpy);++ const r = await mcpRpcAutoRefresh("acme", PRESET_KEY, "initialize");+ expect(r.ok).toBe(false);+ if (!r.ok && r.kind === "http_error") expect(r.status).toBe(401);+ expect(fetchSpy).toHaveBeenCalledTimes(2); // no third call+ });++ it("returns the original 401 when no refresh_token is stored (legacy row)", async () => {+ upsertMcpToken({+ project_slug: "acme",+ server_name: PRESET_KEY,+ access_token: "stale-at",+ // no refresh_token, no token_endpoint, no client_id+ });+ const fetchSpy = vi.fn().mockResolvedValueOnce(http401());+ vi.stubGlobal("fetch", fetchSpy);++ const r = await mcpRpcAutoRefresh("acme", PRESET_KEY, "initialize");+ expect(r.ok).toBe(false);+ if (!r.ok && r.kind === "http_error") expect(r.status).toBe(401);+ expect(fetchSpy).toHaveBeenCalledTimes(1);+ });+});diff --git a/notfair-cmo/src/server/mcp/rpc.ts b/notfair-cmo/src/server/mcp/rpc.tsindex faad8092..bbd21fdc 100644--- a/notfair-cmo/src/server/mcp/rpc.ts+++ b/notfair-cmo/src/server/mcp/rpc.ts@@ -1,5 +1,6 @@import { findMcpToken } from "@/server/mcp/tokens";import { mcpSpecByKey } from "@/server/mcp-catalog";+import { refreshMcpToken, isExpiringSoon } from "./refresh";/*** Shared MCP HTTP plumbing. Two callers use this today:@@ -164,6 +165,59 @@ export async function mcpRpc<T = unknown>(return parseRpcBody<T>(body);}+/**+ * `mcpRpc` with silent refresh-token handling. Looks up the token row by+ * (project_slug, catalog_key), proactively refreshes when the access token+ * is within ~60s of expiry, calls `mcpRpc`, and on HTTP 401 attempts a+ * single refresh + retry before giving up.+ *+ * Returns the same `RpcResult<T>` shape as `mcpRpc` so callers don't need a+ * new error branch. When refresh isn't possible (legacy rows without+ * refresh_token, or upstream rejects the refresh), the original 401 result+ * is returned and the caller's existing stale-token UX kicks in.+ */+export async function mcpRpcAutoRefresh<T = unknown>(+ project_slug: string,+ catalog_key: string,+ method: string,+ params: Record<string, unknown> = {},+ opts: McpRpcOpts = {},+): Promise<RpcResult<T>> {+ const spec = mcpSpecByKey(project_slug, catalog_key);+ if (!spec) {+ return { ok: false, kind: "http_error", status: 404, body: "unknown mcp catalog key" };+ }+ let token = findMcpToken(project_slug, catalog_key);+ if (!token) {+ return { ok: false, kind: "http_error", status: 401, body: "no token stored" };+ }++ if (isExpiringSoon(token)) {+ const refreshed = await refreshMcpToken(token);+ if (refreshed) token = refreshed;+ }++ const first = await mcpRpc<T>(+ spec.resource_url,+ token.access_token_enc,+ method,+ params,+ opts,+ );+ if (first.ok) return first;+ if (first.kind !== "http_error" || first.status !== 401) return first;++ // Reactive refresh. Skip if we just refreshed proactively — the upstream+ // is telling us our fresh token is bad, and looping would burn cycles.+ // `updated_at` is bumped by updateMcpTokenSecrets, so we can detect a+ // refresh that happened within this same call.+ if (Date.parse(token.updated_at) > Date.now() - 5_000) return first;++ const refreshed = await refreshMcpToken(token);+ if (!refreshed) return first;+ return mcpRpc<T>(spec.resource_url, refreshed.access_token_enc, method, params, opts);+}+function parseRpcBody<T>(body: string): RpcResult<T> {const envelope = pickRpcEnvelope(body);if (envelope === null) {diff --git a/notfair-cmo/src/server/mcp/state.ts b/notfair-cmo/src/server/mcp/state.tsindex 76fa68c6..5b6981f3 100644--- a/notfair-cmo/src/server/mcp/state.ts+++ b/notfair-cmo/src/server/mcp/state.ts@@ -1,6 +1,6 @@import { findMcpToken, upsertMcpToken, deleteMcpToken } from "./tokens";import { mcpSpecByKey } from "@/server/mcp-catalog";-import { mcpRpc } from "./rpc";+import { mcpRpcAutoRefresh } from "./rpc";/*** Status surface for the Connections page + dashboard banners.@@ -41,10 +41,14 @@ export async function getMcpStatus(if (!spec) return { state: "not_configured" };const token = findMcpToken(project_slug, catalog_key);if (!token) return { state: "not_configured" };- return probe(spec.resource_url, token.access_token_enc);+ return probe(project_slug, catalog_key, spec.resource_url);}-async function probe(url: string, token: string): Promise<McpRuntimeStatus> {+async function probe(+ project_slug: string,+ catalog_key: string,+ url: string,+): Promise<McpRuntimeStatus> {const last_checked_at = new Date().toISOString();// Use `initialize` — the spec-mandated first call — as the liveness// probe. Some MCP servers (Supabase) reject `tools/list` with HTTP 400@@ -52,9 +56,13 @@ async function probe(url: string, token: string): Promise<McpRuntimeStatus> {// accepted as the opening message. We don't track the session ID since// we're not following up with another call in the probe; tool count// gets surfaced on demand via the View tools dialog (its own RPC).- const r = await mcpRpc<unknown>(- url,- token,+ //+ // Goes through `mcpRpcAutoRefresh` so an expired access token gets+ // silently swapped for a fresh one instead of flapping the status to+ // "stale_token" on every page load.+ const r = await mcpRpcAutoRefresh<unknown>(+ project_slug,+ catalog_key,"initialize",{protocolVersion: "2025-06-18",@@ -116,7 +124,14 @@ export async function setMcpBearer(project_slug: string,catalog_key: string,token: string,- options: { scope?: string; expires_at?: string } = {},+ options: {+ scope?: string;+ expires_at?: string;+ refresh_token?: string;+ token_endpoint?: string;+ client_id?: string;+ client_secret?: string;+ } = {},): Promise<void> {upsertMcpToken({project_slug,@@ -124,5 +139,9 @@ export async function setMcpBearer(access_token: token,scope: options.scope,expires_at: options.expires_at,+ refresh_token: options.refresh_token,+ token_endpoint: options.token_endpoint,+ client_id: options.client_id,+ client_secret: options.client_secret,});}diff --git a/notfair-cmo/src/server/mcp/tokens.test.ts b/notfair-cmo/src/server/mcp/tokens.test.tsnew file mode 100644index 00000000..ee47e00d--- /dev/null+++ b/notfair-cmo/src/server/mcp/tokens.test.ts@@ -0,0 +1,178 @@+import Database from "better-sqlite3";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { MIGRATIONS } from "@/server/db/migrations";++let testDb: Database.Database;++vi.mock("@/server/db/db", () => ({+ getDb: () => testDb,+ getDbPath: () => ":memory:",+}));++import {+ findMcpToken,+ updateMcpTokenSecrets,+ upsertMcpToken,+} from "./tokens";++function applyMigrations(db: Database.Database): void {+ for (const migration of MIGRATIONS) db.exec(migration.sql);+}++function seedProject(slug = "acme"): void {+ testDb+ .prepare(+ "INSERT INTO projects (id, slug, display_name, created_at) VALUES (?, ?, ?, ?)",+ )+ .run("p-" + slug, slug, slug, "2026-01-01T00:00:00.000Z");+}++beforeEach(() => {+ testDb = new Database(":memory:");+ testDb.pragma("foreign_keys = ON");+ applyMigrations(testDb);+});++afterEach(() => {+ testDb.close();+});++describe("upsertMcpToken (OAuth client fields)", () => {+ it("persists token_endpoint, client_id, client_secret, and refresh_token", () => {+ seedProject();+ const row = upsertMcpToken({+ project_slug: "acme",+ server_name: "stripe",+ access_token: "at-1",+ refresh_token: "rt-1",+ expires_at: "2027-01-01T00:00:00.000Z",+ scope: "read_write",+ token_endpoint: "https://auth.example.com/token",+ client_id: "client-abc",+ client_secret: "shh",+ });+ expect(row.refresh_token_enc).toBe("rt-1");+ expect(row.expires_at).toBe("2027-01-01T00:00:00.000Z");+ expect(row.scope).toBe("read_write");+ expect(row.token_endpoint).toBe("https://auth.example.com/token");+ expect(row.client_id).toBe("client-abc");+ expect(row.client_secret).toBe("shh");+ });++ it("leaves OAuth client fields null when omitted (legacy callers)", () => {+ seedProject();+ const row = upsertMcpToken({+ project_slug: "acme",+ server_name: "legacy",+ access_token: "at",+ });+ expect(row.refresh_token_enc).toBeNull();+ expect(row.token_endpoint).toBeNull();+ expect(row.client_id).toBeNull();+ expect(row.client_secret).toBeNull();+ });++ it("overwrites OAuth client fields on update (re-auth case)", () => {+ seedProject();+ upsertMcpToken({+ project_slug: "acme",+ server_name: "stripe",+ access_token: "old",+ client_id: "old-client",+ });+ const after = upsertMcpToken({+ project_slug: "acme",+ server_name: "stripe",+ access_token: "new",+ refresh_token: "new-rt",+ client_id: "new-client",+ client_secret: "new-secret",+ token_endpoint: "https://auth.example.com/token",+ });+ expect(after.access_token_enc).toBe("new");+ expect(after.refresh_token_enc).toBe("new-rt");+ expect(after.client_id).toBe("new-client");+ expect(after.client_secret).toBe("new-secret");+ expect(after.token_endpoint).toBe("https://auth.example.com/token");+ });+});++describe("updateMcpTokenSecrets", () => {+ it("rotates access_token + expires_at without touching client fields", () => {+ seedProject();+ const row = upsertMcpToken({+ project_slug: "acme",+ server_name: "stripe",+ access_token: "at-1",+ refresh_token: "rt-1",+ expires_at: "2027-01-01T00:00:00.000Z",+ token_endpoint: "https://auth.example.com/token",+ client_id: "client-abc",+ client_secret: "shh",+ });+ const updated = updateMcpTokenSecrets(row.id, {+ access_token: "at-2",+ expires_at: "2028-01-01T00:00:00.000Z",+ });+ expect(updated).not.toBeNull();+ expect(updated!.access_token_enc).toBe("at-2");+ expect(updated!.expires_at).toBe("2028-01-01T00:00:00.000Z");+ expect(updated!.refresh_token_enc).toBe("rt-1");+ expect(updated!.token_endpoint).toBe("https://auth.example.com/token");+ expect(updated!.client_id).toBe("client-abc");+ expect(updated!.client_secret).toBe("shh");+ });++ it("rotates refresh_token when provider issues a new one", () => {+ seedProject();+ const row = upsertMcpToken({+ project_slug: "acme",+ server_name: "stripe",+ access_token: "at-1",+ refresh_token: "rt-1",+ });+ const updated = updateMcpTokenSecrets(row.id, {+ access_token: "at-2",+ refresh_token: "rt-2",+ });+ expect(updated!.refresh_token_enc).toBe("rt-2");+ });++ it("keeps existing refresh_token when patch omits it (RFC 6749 §6)", () => {+ seedProject();+ const row = upsertMcpToken({+ project_slug: "acme",+ server_name: "stripe",+ access_token: "at-1",+ refresh_token: "rt-1",+ });+ const updated = updateMcpTokenSecrets(row.id, { access_token: "at-2" });+ expect(updated!.refresh_token_enc).toBe("rt-1");+ });++ it("returns null when row no longer exists", () => {+ expect(+ updateMcpTokenSecrets("nope-uuid", { access_token: "x" }),+ ).toBeNull();+ });+});++describe("findMcpToken (after migration 013)", () => {+ it("reads the new fields back via findMcpToken", () => {+ seedProject();+ upsertMcpToken({+ project_slug: "acme",+ server_name: "stripe",+ access_token: "at",+ refresh_token: "rt",+ token_endpoint: "https://auth.example.com/token",+ client_id: "client-abc",+ });+ const found = findMcpToken("acme", "stripe");+ expect(found).not.toBeNull();+ expect(found!.token_endpoint).toBe("https://auth.example.com/token");+ expect(found!.client_id).toBe("client-abc");+ expect(found!.refresh_token_enc).toBe("rt");+ });+});diff --git a/notfair-cmo/src/server/mcp/tokens.ts b/notfair-cmo/src/server/mcp/tokens.tsindex 23382f34..1f04ede2 100644--- a/notfair-cmo/src/server/mcp/tokens.ts+++ b/notfair-cmo/src/server/mcp/tokens.ts@@ -11,6 +11,11 @@ import { getDb } from "@/server/db/db";* `access_token_enc` / `refresh_token_enc` columns are encrypted-at-rest* placeholders today (we store the raw JSON envelope from the OAuth callback)* but the schema is ready for a keytar-backed encryption pass.+ *+ * `token_endpoint`, `client_id`, `client_secret` were added in migration 013+ * so the refresh helper (`mcp/refresh.ts`) can rotate access tokens without+ * sending the user back through consent. They are nullable: pre-013 rows+ * have them as NULL and stay on the legacy reconnect-on-401 path.*/export interface McpToken {id: string;@@ -22,6 +27,9 @@ export interface McpToken {expires_at: string | null;scope: string | null;metadata_json: string | null;+ token_endpoint: string | null;+ client_id: string | null;+ client_secret: string | null;created_at: string;updated_at: string;}@@ -35,6 +43,9 @@ export interface UpsertMcpTokenInput {expires_at?: string;scope?: string;metadata?: Record<string, unknown>;+ token_endpoint?: string;+ client_id?: string;+ client_secret?: string;}export function upsertMcpToken(input: UpsertMcpTokenInput): McpToken {@@ -49,13 +60,26 @@ export function upsertMcpToken(input: UpsertMcpTokenInput): McpToken {if (existing) {db.prepare(- "UPDATE mcp_tokens SET access_token_enc = ?, refresh_token_enc = ?, expires_at = ?, scope = ?, metadata_json = ?, updated_at = ? WHERE id = ?",+ `UPDATE mcp_tokens SET+ access_token_enc = ?,+ refresh_token_enc = ?,+ expires_at = ?,+ scope = ?,+ metadata_json = ?,+ token_endpoint = ?,+ client_id = ?,+ client_secret = ?,+ updated_at = ?+ WHERE id = ?`,).run(input.access_token,input.refresh_token ?? null,input.expires_at ?? null,input.scope ?? null,input.metadata ? JSON.stringify(input.metadata) : null,+ input.token_endpoint ?? null,+ input.client_id ?? null,+ input.client_secret ?? null,now,existing.id,);@@ -72,11 +96,19 @@ export function upsertMcpToken(input: UpsertMcpTokenInput): McpToken {expires_at: input.expires_at ?? null,scope: input.scope ?? null,metadata_json: input.metadata ? JSON.stringify(input.metadata) : null,+ token_endpoint: input.token_endpoint ?? null,+ client_id: input.client_id ?? null,+ client_secret: input.client_secret ?? null,created_at: now,updated_at: now,};db.prepare(- "INSERT INTO mcp_tokens (id, project_slug, server_name, account_label, access_token_enc, refresh_token_enc, expires_at, scope, metadata_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",+ `INSERT INTO mcp_tokens (+ id, project_slug, server_name, account_label,+ access_token_enc, refresh_token_enc, expires_at, scope, metadata_json,+ token_endpoint, client_id, client_secret,+ created_at, updated_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,).run(token.id,token.project_slug,@@ -87,12 +119,50 @@ export function upsertMcpToken(input: UpsertMcpTokenInput): McpToken {token.expires_at,token.scope,token.metadata_json,+ token.token_endpoint,+ token.client_id,+ token.client_secret,token.created_at,token.updated_at,);return token;}+/**+ * In-place rotation of the access token (and optionally the refresh token —+ * some providers rotate it on every refresh). Used by `mcp/refresh.ts` after+ * a successful `grant_type=refresh_token` exchange. Leaves the OAuth client+ * fields untouched so the next refresh has what it needs.+ *+ * Returns the updated row, or null if `id` no longer exists (deleted between+ * lookup and refresh — race that's possible if the user disconnects mid-call).+ */+export function updateMcpTokenSecrets(+ id: string,+ patch: { access_token: string; refresh_token?: string | null; expires_at?: string | null },+): McpToken | null {+ const db = getDb();+ const now = new Date().toISOString();+ const result = db+ .prepare(+ `UPDATE mcp_tokens SET+ access_token_enc = ?,+ refresh_token_enc = COALESCE(?, refresh_token_enc),+ expires_at = ?,+ updated_at = ?+ WHERE id = ?`,+ )+ .run(+ patch.access_token,+ patch.refresh_token ?? null,+ patch.expires_at ?? null,+ now,+ id,+ );+ if (result.changes === 0) return null;+ return getMcpToken(id);+}+export function getMcpToken(id: string): McpToken | null {return ((getDb()diff --git a/notfair-cmo/src/server/onboarding/accounts.test.ts b/notfair-cmo/src/server/onboarding/accounts.test.tsindex 0e7c9469..c4c4b8fc 100644--- a/notfair-cmo/src/server/onboarding/accounts.test.ts+++ b/notfair-cmo/src/server/onboarding/accounts.test.ts@@ -7,6 +7,10 @@ const mcpRpcMock = vi.fn();vi.mock("@/server/mcp/rpc", () => ({getMcpConfig: (...args: unknown[]) => getMcpConfigMock(...args),mcpRpc: (...args: unknown[]) => mcpRpcMock(...args),+ // The action wraps `mcpRpc` in an auto-refresh helper that resolves the+ // token from the DB; tests don't exercise refresh, so we route the+ // wrapper to the same underlying mock for simplicity.+ mcpRpcAutoRefresh: (...args: unknown[]) => mcpRpcMock(...args),}));const getProjectMock = vi.fn();diff --git a/notfair-cmo/src/server/onboarding/accounts.ts b/notfair-cmo/src/server/onboarding/accounts.tsindex d2fa3158..4c0dc12c 100644--- a/notfair-cmo/src/server/onboarding/accounts.ts+++ b/notfair-cmo/src/server/onboarding/accounts.ts@@ -2,7 +2,7 @@import { revalidatePath } from "next/cache";-import { getMcpConfig, mcpRpc } from "@/server/mcp/rpc";+import { getMcpConfig, mcpRpcAutoRefresh } from "@/server/mcp/rpc";import { getProject, setProjectGoogleAdsAccount } from "@/server/db/projects";import type { Project } from "@/types";@@ -54,9 +54,9 @@ export async function listGoogleAdsAccounts(};}- const rpcResult = await mcpRpc<ListAccountsToolResult>(- cfg.url,- cfg.token,+ const rpcResult = await mcpRpcAutoRefresh<ListAccountsToolResult>(+ project_slug,+ MCP_CATALOG_KEY,"tools/call",{ name: "listConnectedAccounts", arguments: {} },{ timeoutMs: LIST_TIMEOUT_MS },