Open-source SEO, GEO, and marketing skills for AI agents.
refactor(notfair-cmo): split browser tools into standalone notfair-browser MCP
Yuting Zhongbd7c9f15c67a
diff --git a/notfair-cmo/src/app/api/mcp/browser/route.ts b/notfair-cmo/src/app/api/mcp/browser/route.tsnew file mode 100644index 00000000..2a9505dc--- /dev/null+++ b/notfair-cmo/src/app/api/mcp/browser/route.ts@@ -0,0 +1,96 @@+import { NextResponse } from "next/server";++import { BROWSER_TOOLS } from "@/server/mcp-server/browser-tools";+import { handleJsonRpc, type JsonRpcRequest } from "@/server/mcp-server/jsonrpc";+import { verifyMcpServerSecret } from "@/server/mcp-server/secret";++export const dynamic = "force-dynamic";+export const runtime = "nodejs";++/**+ * Standalone MCP server for the workspace browser tools.+ *+ * Split out from notfair-orchestration so the orchestration surface stays+ * focused on task/approval/project tools, and so users can think about+ * "the browser MCP" as its own thing in the Connections / Codex MCP list.+ *+ * Same transport (streamable-http, JSON-only) and same shared bearer as+ * the orchestration MCP — single-user CLI on loopback so we don't need+ * per-MCP secrets.+ */++const SERVER_INFO = {+ name: "notfair-browser",+ version: "0.1.0",+ tools: BROWSER_TOOLS,+};++function unauthorized(): Response {+ return new NextResponse("Unauthorized", { status: 401 });+}++function bearerFrom(req: Request): string | null {+ const header = req.headers.get("authorization") ?? req.headers.get("Authorization");+ if (!header) return null;+ const m = header.match(/^Bearer\s+(.+)$/i);+ return m ? m[1]!.trim() : null;+}++export async function POST(req: Request): Promise<Response> {+ const bearer = bearerFrom(req);+ if (!verifyMcpServerSecret(bearer)) return unauthorized();++ let body: unknown;+ try {+ body = await req.json();+ } catch {+ return NextResponse.json(+ {+ jsonrpc: "2.0",+ id: null,+ error: { code: -32700, message: "Parse error" },+ },+ { status: 200 },+ );+ }++ if (Array.isArray(body)) {+ return NextResponse.json(+ {+ jsonrpc: "2.0",+ id: null,+ error: {+ code: -32600,+ message: "Batched requests are not supported by this server.",+ },+ },+ { status: 200 },+ );+ }++ const request = body as JsonRpcRequest;+ if (!request || typeof request !== "object" || request.jsonrpc !== "2.0") {+ return NextResponse.json(+ {+ jsonrpc: "2.0",+ id: request?.id ?? null,+ error: { code: -32600, message: "Invalid Request" },+ },+ { status: 200 },+ );+ }++ const response = await handleJsonRpc(request, SERVER_INFO);+ if (response === null) {+ return new Response(null, { status: 204 });+ }+ return NextResponse.json(response, { status: 200 });+}++export async function GET(): Promise<Response> {+ return NextResponse.json({+ name: SERVER_INFO.name,+ transport: "streamable-http",+ note: "POST JSON-RPC with Bearer auth. See ~/.notfair-cmo/mcp-server-secret.",+ });+}diff --git a/notfair-cmo/src/app/api/mcp/orchestration/route.ts b/notfair-cmo/src/app/api/mcp/orchestration/route.tsindex 4c77076f..301feb22 100644--- a/notfair-cmo/src/app/api/mcp/orchestration/route.ts+++ b/notfair-cmo/src/app/api/mcp/orchestration/route.ts@@ -2,6 +2,13 @@ import { NextResponse } from "next/server";import { handleJsonRpc, type JsonRpcRequest } from "@/server/mcp-server/jsonrpc";import { verifyMcpServerSecret } from "@/server/mcp-server/secret";+import { TOOLS } from "@/server/mcp-server/tools";++const SERVER_INFO = {+ name: "notfair-orchestration",+ version: "0.2.0",+ tools: TOOLS,+};export const dynamic = "force-dynamic";export const runtime = "nodejs";@@ -76,7 +83,7 @@ export async function POST(req: Request): Promise<Response> {);}- const response = await handleJsonRpc(request);+ const response = await handleJsonRpc(request, SERVER_INFO);if (response === null) {// Notification — JSON-RPC mandates no body. Return 204 so the client// doesn't try to parse anything.@@ -90,7 +97,7 @@ export async function GET(): Promise<Response> {// tiny shape so they know this is an MCP HTTP server (without leaking the// secret-check; auth still applies to POST).return NextResponse.json({- name: "notfair-cmo",+ name: SERVER_INFO.name,transport: "streamable-http",note: "POST JSON-RPC with Bearer auth. See ~/.notfair-cmo/mcp-server-secret.",});diff --git a/notfair-cmo/src/server/adapters/codex-local/execute.ts b/notfair-cmo/src/server/adapters/codex-local/execute.tsindex 52fd1659..8b45163c 100644--- a/notfair-cmo/src/server/adapters/codex-local/execute.ts+++ b/notfair-cmo/src/server/adapters/codex-local/execute.ts@@ -54,13 +54,17 @@ export async function* executeCodexLocal(// env var per MCP server the project has registered so each server gets// its OWN bearer:// - notfair-orchestration: shared per-machine secret+ // - notfair-browser: same shared per-machine secret (both are+ // internal notfair-cmo servers on loopback)// - notfair-googleads, gsc, etc.: per-project OAuth token from// `mcp_tokens`// Without per-server env vars every MCP would auth with the same// (wrong) bearer and codex would either surface it as Auth Unsupported// or pass the wrong token to the wrong server.+ const mcpSecret = getOrCreateMcpServerSecret();const mcpEnv: Record<string, string> = {- [CODEX_BEARER_ENV_VAR]: getOrCreateMcpServerSecret(),+ [CODEX_BEARER_ENV_VAR]: mcpSecret,+ [bearerEnvVarForServer("notfair-browser")]: mcpSecret,};for (const token of listProjectMcpTokens(ctx.projectSlug)) {mcpEnv[bearerEnvVarForServer(token.server_name)] = token.access_token_enc;diff --git a/notfair-cmo/src/server/agent-templates.ts b/notfair-cmo/src/server/agent-templates.tsindex 3c51c3f8..d1015e9c 100644--- a/notfair-cmo/src/server/agent-templates.ts+++ b/notfair-cmo/src/server/agent-templates.ts@@ -10,7 +10,10 @@ import { getProject } from "@/server/db/projects";import { getOrchestrationSkill } from "@/server/skills/orchestration-skill";import { readProjectBrief } from "@/server/onboarding/project-brief";import { DEFAULT_HARNESS_ADAPTER } from "@/server/adapters/registry";-import { registerOrchestrationForAgent } from "@/server/mcp-server/registration";+import {+ registerBrowserMcpForAgent,+ registerOrchestrationForAgent,+} from "@/server/mcp-server/registration";/*** Role-specific behavior for the CMO. Concise — the procedural how-to@@ -498,6 +501,17 @@ export async function ensureProjectAgents(err,);}+ // Wire notfair-browser MCP for this agent so browser_open /+ // browser_snapshot / browser_click etc. are callable. Best-effort —+ // an agent without browser access still has all task tooling.+ try {+ await registerBrowserMcpForAgent(project_slug, agentId);+ } catch (err) {+ console.warn(+ `[provision] browser MCP registration failed for ${agentId}:`,+ err,+ );+ }// Also wire any external catalog MCPs the project already has tokens// for (e.g. Google Ads was connected before this agent was created).// Without this, a new agent in an established project sees thediff --git a/notfair-cmo/src/server/mcp-server/jsonrpc.browser.test.ts b/notfair-cmo/src/server/mcp-server/jsonrpc.browser.test.tsnew file mode 100644index 00000000..ee96f07f--- /dev/null+++ b/notfair-cmo/src/server/mcp-server/jsonrpc.browser.test.ts@@ -0,0 +1,108 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++// The browser MCP server hits the live browser/session modules, so mock+// them out — these tests only verify wiring (right server name, right+// tools, isolation from orchestration).+vi.mock("@/server/browser/session", () => ({+ getOrLaunchBrowser: vi.fn(async () => ({ projectSlug: "acme" })),+ getSessionStatus: vi.fn(() => ({+ projectSlug: "acme",+ running: false,+ cdpPort: 19042,+ userDataDir: "/tmp/profile",+ idleTimeoutMs: 300_000,+ })),+}));++vi.mock("@/server/browser/tabs", () => ({+ openTab: vi.fn(async () => ({ id: "t1", label: "t1", url: "about:blank", title: "" })),+ listTabs: vi.fn(async () => []),+ closeTab: vi.fn(async () => false),+ getTab: vi.fn(async () => null),+}));++vi.mock("@/server/browser/actions", () => ({+ navigate: vi.fn(),+ snapshot: vi.fn(),+ click: vi.fn(),+ type: vi.fn(),+ press: vi.fn(),+ scroll: vi.fn(),+ back: vi.fn(),+}));++import { BROWSER_TOOLS } from "./browser-tools";+import { handleJsonRpc } from "./jsonrpc";+import { TOOLS as ORCHESTRATION_TOOLS } from "./tools";++const BROWSER_SERVER = {+ name: "notfair-browser",+ version: "0.1.0",+ tools: BROWSER_TOOLS,+};++beforeEach(() => vi.clearAllMocks());+afterEach(() => vi.clearAllMocks());++describe("notfair-browser MCP server", () => {+ it("identifies itself as notfair-browser on initialize", async () => {+ const r = await handleJsonRpc(+ { jsonrpc: "2.0", id: 1, method: "initialize" },+ BROWSER_SERVER,+ );+ const result = (r as { result: { serverInfo: { name: string } } }).result;+ expect(result.serverInfo.name).toBe("notfair-browser");+ });++ it("tools/list returns only browser_* tools", async () => {+ const r = await handleJsonRpc(+ { jsonrpc: "2.0", id: 1, method: "tools/list" },+ BROWSER_SERVER,+ );+ const tools = (r as { result: { tools: Array<{ name: string }> } }).result.tools;+ const names = tools.map((t) => t.name).sort();+ expect(names.length).toBeGreaterThan(0);+ expect(names.every((n) => n.startsWith("browser_"))).toBe(true);+ });++ it("orchestration registry does NOT contain browser_* tools (the split is real)", () => {+ const orchestrationNames = ORCHESTRATION_TOOLS.map((t) => t.name);+ expect(orchestrationNames.some((n) => n.startsWith("browser_"))).toBe(false);+ });++ it("browser registry does NOT contain orchestration tools (isolated surfaces)", () => {+ const browserNames = BROWSER_TOOLS.map((t) => t.name);+ expect(browserNames).not.toContain("submit_task_status");+ expect(browserNames).not.toContain("create_task");+ expect(browserNames).not.toContain("request_approval");+ });++ it("tools/call rejects orchestration tool names on the browser server", async () => {+ const r = await handleJsonRpc(+ {+ jsonrpc: "2.0",+ id: 1,+ method: "tools/call",+ params: { name: "submit_task_status", arguments: {} },+ },+ BROWSER_SERVER,+ );+ const err = (r as { error?: { code: number; message: string } }).error;+ expect(err?.code).toBe(-32601);+ expect(err?.message).toMatch(/Unknown tool/);+ });++ it("tools/call accepts a browser_* tool name", async () => {+ const r = await handleJsonRpc(+ {+ jsonrpc: "2.0",+ id: 1,+ method: "tools/call",+ params: { name: "browser_status", arguments: { project_slug: "acme" } },+ },+ BROWSER_SERVER,+ );+ const result = (r as { result: { isError?: boolean } }).result;+ expect(result.isError).toBe(false);+ });+});diff --git a/notfair-cmo/src/server/mcp-server/jsonrpc.test.ts b/notfair-cmo/src/server/mcp-server/jsonrpc.test.tsindex bf81c01b..70200b18 100644--- a/notfair-cmo/src/server/mcp-server/jsonrpc.test.ts+++ b/notfair-cmo/src/server/mcp-server/jsonrpc.test.ts@@ -32,13 +32,20 @@ vi.mock("@/server/db/agent-actions", () => ({}));import { handleJsonRpc, type JsonRpcRequest } from "./jsonrpc";+import { TOOLS } from "./tools";++const ORCHESTRATION_SERVER = {+ name: "notfair-orchestration",+ version: "0.2.0",+ tools: TOOLS,+};beforeEach(() => {vi.clearAllMocks();});function call(req: JsonRpcRequest) {- return handleJsonRpc(req);+ return handleJsonRpc(req, ORCHESTRATION_SERVER);}describe("handleJsonRpc — initialize", () => {@@ -52,7 +59,7 @@ describe("handleJsonRpc — initialize", () => {capabilities: { tools: object };};expect(result.protocolVersion).toMatch(/^\d{4}-\d{2}-\d{2}$/);- expect(result.serverInfo.name).toBe("notfair-cmo");+ expect(result.serverInfo.name).toBe("notfair-orchestration");expect(result.capabilities.tools).toEqual({});});diff --git a/notfair-cmo/src/server/mcp-server/jsonrpc.ts b/notfair-cmo/src/server/mcp-server/jsonrpc.tsindex ea54daf2..156ab1ec 100644--- a/notfair-cmo/src/server/mcp-server/jsonrpc.ts+++ b/notfair-cmo/src/server/mcp-server/jsonrpc.ts@@ -1,7 +1,13 @@-import { describeTool, findTool, TOOLS } from "./tools";+import { describeTool, type ToolDefinition } from "./tools";/**- * JSON-RPC 2.0 dispatcher for notfair-cmo's outbound MCP server.+ * JSON-RPC 2.0 dispatcher for notfair-cmo's outbound MCP servers.+ *+ * Each MCP server endpoint (e.g. /api/mcp/orchestration, /api/mcp/browser)+ * passes its own tool registry to `handleJsonRpc`. Splitting the surface+ * into multiple servers keeps related tools grouped, lets users+ * enable/disable per-MCP, and makes "what is this MCP for?" obvious from+ * the server name alone.** MCP methods we implement:* - initialize: handshake; reports protocol version + server info@@ -36,8 +42,18 @@ export type JsonRpcResponse =const PROTOCOL_VERSION = "2025-06-18";+export interface McpServerInfo {+ /** Server name reported in `initialize`. Should match the MCP registration key (e.g. "notfair-orchestration"). */+ name: string;+ /** Server version string. Bump when wire-visible behavior changes. */+ version: string;+ /** Tool registry for this server. */+ tools: ReadonlyArray<ToolDefinition>;+}+export async function handleJsonRpc(req: JsonRpcRequest,+ server: McpServerInfo,): Promise<JsonRpcResponse | null> {// Notifications (no id): handle the side-effecting ones but never reply.if (req.id === undefined || req.id === null) {@@ -50,13 +66,13 @@ export async function handleJsonRpc(case "initialize":return ok(id, {protocolVersion: PROTOCOL_VERSION,- serverInfo: { name: "notfair-cmo", version: "0.1.0" },+ serverInfo: { name: server.name, version: server.version },capabilities: { tools: {} },});case "tools/list":- return ok(id, { tools: TOOLS.map(describeTool) });+ return ok(id, { tools: server.tools.map(describeTool) });case "tools/call":- return await handleToolsCall(id, req.params ?? {});+ return await handleToolsCall(id, req.params ?? {}, server.tools);case "ping":return ok(id, {});default:@@ -74,13 +90,14 @@ export async function handleJsonRpc(async function handleToolsCall(id: string | number,params: Record<string, unknown>,+ tools: ReadonlyArray<ToolDefinition>,): Promise<JsonRpcResponse> {const name = params.name;const args = params.arguments ?? {};if (typeof name !== "string") {return err(id, -32602, "Invalid params: 'name' must be a string");}- const tool = findTool(name);+ const tool = tools.find((t) => t.name === name);if (!tool) {return err(id, -32601, `Unknown tool: ${name}`);}diff --git a/notfair-cmo/src/server/mcp-server/registration.ts b/notfair-cmo/src/server/mcp-server/registration.tsindex 1ba586ef..3eda0dcd 100644--- a/notfair-cmo/src/server/mcp-server/registration.ts+++ b/notfair-cmo/src/server/mcp-server/registration.ts@@ -20,13 +20,24 @@ import type { HarnessAdapterId } from "@/server/adapters/types";*/export const ORCHESTRATION_MCP_KEY = "notfair-orchestration";+export const BROWSER_MCP_KEY = "notfair-browser";++function notfairOriginPort(): string {+ return process.env.NOTFAIR_CMO_PORT?.trim() || "3326";+}function defaultMcpUrl(): string {if (process.env.NOTFAIR_CMO_MCP_URL?.trim()) {return process.env.NOTFAIR_CMO_MCP_URL.trim();}- const port = process.env.NOTFAIR_CMO_PORT?.trim() || "3326";- return `http://127.0.0.1:${port}/api/mcp/orchestration`;+ return `http://127.0.0.1:${notfairOriginPort()}/api/mcp/orchestration`;+}++function defaultBrowserMcpUrl(): string {+ if (process.env.NOTFAIR_CMO_BROWSER_MCP_URL?.trim()) {+ return process.env.NOTFAIR_CMO_BROWSER_MCP_URL.trim();+ }+ return `http://127.0.0.1:${notfairOriginPort()}/api/mcp/browser`;}/**@@ -70,16 +81,47 @@ export async function registerOrchestrationForAgent(project_slug: string,agent_id: string,): Promise<InstallResult> {- const url = defaultMcpUrl();+ return registerInternalMcpForAgent({+ project_slug,+ agent_id,+ key: ORCHESTRATION_MCP_KEY,+ url: defaultMcpUrl(),+ });+}++/**+ * Register the standalone browser MCP (notfair-browser) for an agent.+ * Same shared-secret auth + same harness adapter glue as orchestration;+ * separate URL + server name so agents see the surface as its own thing.+ */+export async function registerBrowserMcpForAgent(+ project_slug: string,+ agent_id: string,+): Promise<InstallResult> {+ return registerInternalMcpForAgent({+ project_slug,+ agent_id,+ key: BROWSER_MCP_KEY,+ url: defaultBrowserMcpUrl(),+ });+}++async function registerInternalMcpForAgent(args: {+ project_slug: string;+ agent_id: string;+ key: string;+ url: string;+}): Promise<InstallResult> {+ const { project_slug, agent_id, key, url } = args;const project = getProject(project_slug);if (!project) {- return { ok: false, key: ORCHESTRATION_MCP_KEY, url, error: `Unknown project ${project_slug}` };+ return { ok: false, key, url, error: `Unknown project ${project_slug}` };}try {const adapter = requireAdapter(project.harness_adapter);await maybePruneCodexOrphans(adapter.id);await adapter.registerMcp({- serverName: ORCHESTRATION_MCP_KEY,+ serverName: key,agentId: agent_id,projectSlug: project_slug,transport: {@@ -88,11 +130,11 @@ export async function registerOrchestrationForAgent(headers: { Authorization: `Bearer ${getOrCreateMcpServerSecret()}` },},});- return { ok: true, key: ORCHESTRATION_MCP_KEY, url };+ return { ok: true, key, url };} catch (err) {return {ok: false,- key: ORCHESTRATION_MCP_KEY,+ key,url,error: err instanceof Error ? err.message : String(err),};diff --git a/notfair-cmo/src/server/mcp-server/tools.ts b/notfair-cmo/src/server/mcp-server/tools.tsindex 17eb095e..61876ed5 100644--- a/notfair-cmo/src/server/mcp-server/tools.ts+++ b/notfair-cmo/src/server/mcp-server/tools.ts@@ -26,8 +26,6 @@ import {} from "@/server/orchestration/handlers";import type { TaskStatus } from "@/types";-import { BROWSER_TOOLS } from "./browser-tools";-/*** Tool definitions exposed by notfair-cmo's MCP server to OpenClaw-side* agents. The MCP server is **globally installed** (one OpenClaw row,@@ -847,9 +845,12 @@ export const TOOLS: ToolDefinition[] = [inputSchema: scheduleRecurringWorkInput,handler: handleScheduleRecurringWorkTool,},- ...BROWSER_TOOLS,];+// Browser MCP tools live in their own server (notfair-browser) so the+// orchestration surface stays focused. See ./browser-tools.ts and the+// /api/mcp/browser route.+export function describeTool(tool: ToolDefinition): {name: string;description: string;diff --git a/notfair-cmo/src/server/skills/orchestration-skill.test.ts b/notfair-cmo/src/server/skills/orchestration-skill.test.tsindex 8d251ffc..214faa6a 100644--- a/notfair-cmo/src/server/skills/orchestration-skill.test.ts+++ b/notfair-cmo/src/server/skills/orchestration-skill.test.ts@@ -86,6 +86,12 @@ describe("ORCHESTRATION_SKILL", () => {expect(s).not.toContain("<propose_cron>");});+ it("points agents at the standalone notfair-browser MCP (not the orchestration MCP)", () => {+ const s = getOrchestrationSkill();+ expect(s).toMatch(/notfair-browser MCP/);+ expect(s).not.toMatch(/notfair-orchestration MCP exposes .*browser_/);+ });+it("teaches the workspace browser tool inventory", () => {const s = getOrchestrationSkill();for (const tool of [diff --git a/notfair-cmo/src/server/skills/orchestration-skill.ts b/notfair-cmo/src/server/skills/orchestration-skill.tsindex ba798562..38f4396d 100644--- a/notfair-cmo/src/server/skills/orchestration-skill.ts+++ b/notfair-cmo/src/server/skills/orchestration-skill.ts@@ -99,7 +99,7 @@ across restarts; you do not need to ask the user to sign in again.### CRITICAL: which "browser" tool to use-The notfair-orchestration MCP exposes \`browser_open\`, \`browser_snapshot\`,+The notfair-browser MCP exposes \`browser_open\`, \`browser_snapshot\`,\`browser_click\`, etc. **These are the ONLY tools that touch the workspacebrowser.** When the user says "launch the browser", "open a page", "go to<URL>", "snapshot the page", or anything in that family, the answer is