Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(mcp): ship remote MCP server with API keys + 2 initial tools (#20)
Gökhan Geyik0e16d686421e
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex ca031aae7..76ce327db 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -60,8 +60,7 @@ Run the migration SQL to create all tables, indexes, RLS policies, and triggers1. Open your Supabase project dashboard2. Go to **SQL Editor**-3. Paste the contents of `supabase/migrations/00001_initial_schema.sql`-4. Click **Run**+3. For each file in `supabase/migrations/` (in alphabetical order — `00001_…` first, then `00002_…`, etc.), paste its contents and click **Run****Option B — Supabase CLI:**diff --git a/README.md b/README.mdindex 35ea7b341..9d01e846b 100644--- a/README.md+++ b/README.md@@ -76,8 +76,7 @@ Run the migration SQL to create all tables, indexes, RLS policies, and triggers:**Option A — Supabase Dashboard:**1. Go to your project's **SQL Editor**-2. Paste the contents of `supabase/migrations/00001_initial_schema.sql`-3. Click **Run**+2. For each file in `supabase/migrations/` (in alphabetical order — `00001_…` first, then `00002_…`, etc.), paste its contents and click **Run****Option B — Supabase CLI:**@@ -138,8 +137,8 @@ ansvisor/What we're planning to build next. React with 👍 on the linked issue (or open a new one) to push something up the list. PRs welcome on any of these.-- [ ] **Ansvisor MCP server** — expose insights through a Model Context Protocol server so Claude Desktop, Cursor, Zed, and any other MCP client can query your brand visibility directly-- [ ] **Claude Code skills** — bundled Claude Code skills so you can talk to your Ansvisor data from your terminal during a normal coding session+- [x] **Ansvisor MCP server** — expose insights through a Model Context Protocol server so Claude Desktop, Claude Code, Cursor, Zed, and any other MCP client can query your brand visibility directly. Remote (Streamable HTTP) endpoint at `/api/mcp` — zero install, paste a URL + API key into your client and you're done. Ships with `list_brands` and `get_visibility_summary` today; more tools landing as we go.+- [ ] **Claude Code skills** — opinionated workflows on top of the MCP server (page-audit, rewrite-for-aeo, check-mentions) plus a freeform `/ansvisor:ask` for conversational queries- [ ] **In-product conversational AI assistant** — chat with your dashboard about visibility trends, competitor moves, and content gaps without leaving the page- [ ] **ScrapeLLM integration** — add ScrapeLLM as an alternative scraping backend alongside Cloro for users who prefer it or need a fallback- [ ] **PostHog integration** — pipe AI-referred sessions and tracking events into PostHog for users already running it as their product analytics layerdiff --git a/docs/guides/mcp-server.mdx b/docs/guides/mcp-server.mdxnew file mode 100644index 000000000..5f8539f0f--- /dev/null+++ b/docs/guides/mcp-server.mdx@@ -0,0 +1,83 @@+---+title: "MCP server"+description: "Connect Claude Desktop, Claude Code, Cursor, Zed, and any MCP-aware client to your Ansvisor data — zero install."+---++Ansvisor ships a [Model Context Protocol](https://modelcontextprotocol.io)+server at `https://app.ansvisor.com/api/mcp` (or your own host if you+self-host) so AI assistants can query your brand visibility data through+natural-language conversation. No npm package, no local process — just a URL+and an API key.++## Generate an API key++1. Open your Ansvisor dashboard → **Settings** → **API Keys**+2. Click **New key**, give it a memorable name (e.g. _Claude — laptop_)+3. Copy the token. It's shown **once** — store it in your password manager++## Connect Claude Desktop++Edit `~/Library/Application Support/Claude/claude_desktop_config.json`+(macOS) or `%APPDATA%\Claude\claude_desktop_config.json` (Windows):++```json+{+ "mcpServers": {+ "ansvisor": {+ "url": "https://app.ansvisor.com/api/mcp",+ "headers": {+ "Authorization": "Bearer ans_..."+ }+ }+ }+}+```++Restart Claude Desktop. Type _"List my Ansvisor brands"_ — Claude should+call the `list_brands` tool and show your brands inline.++## Connect Claude Code++```bash+claude mcp add ansvisor --transport http https://app.ansvisor.com/api/mcp \+ --header "Authorization: Bearer ans_..."+```++## Self-host? Point at your own instance++The MCP endpoint lives at `/api/mcp` on whatever host runs the Ansvisor web+app. If you self-host at `ansvisor.mycompany.internal`, use that base URL+instead.++## Available tools++| Tool | What it does |+| --- | --- |+| `list_brands` | List brands the authenticated user can access. |+| `get_visibility_summary` | Aggregate visibility score, mentions, citations, top competitors for a brand over an optional date range / model / region. |++More tools land regularly — check the [project roadmap](https://github.com/aeohub/ansvisor#whats-next).++## Try it++Ask your client things like:++- _"List my Ansvisor brands."_+- _"What's my visibility score on ChatGPT for the last 7 days?"_+- _"Who are my top 5 competitors by mention count this month?"_++The model picks the right tool, fills in the brand id and filters, and+answers in plain English using the returned data.++## Revoking access++If a key leaks or you stop using a client, open **Settings → API Keys** and+click the trash icon. Clients using that key lose access immediately.++## Transport++The server speaks the+[MCP Streamable HTTP](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http)+transport in stateless mode — every request is self-contained, no session+state is kept between calls. This makes it work cleanly behind any HTTP+load balancer and on serverless runtimes.diff --git a/docs/mint.json b/docs/mint.jsonindex b556e5d87..09351aaa7 100644--- a/docs/mint.json+++ b/docs/mint.json@@ -81,7 +81,8 @@"guides/citations","guides/ai-traffic-analytics","guides/competitors",- "guides/content-optimization"+ "guides/content-optimization",+ "guides/mcp-server"]},{diff --git a/supabase/migrations/00003_api_keys.sql b/supabase/migrations/00003_api_keys.sqlnew file mode 100644index 000000000..a1c85cb71--- /dev/null+++ b/supabase/migrations/00003_api_keys.sql@@ -0,0 +1,61 @@+-- API keys+-- Long-lived bearer tokens that let external clients (MCP server, scripts,+-- third-party integrations) authenticate against the Ansvisor API on behalf+-- of a user without holding a Supabase session.+--+-- The plaintext token is shown to the user exactly once at creation time.+-- The server stores only `key_hash` (sha256 of the full token) and `prefix`+-- (first 12 chars, used for identification in the UI / logs).++CREATE TABLE IF NOT EXISTS "public"."api_keys" (+ "id" uuid DEFAULT gen_random_uuid() NOT NULL,+ "user_id" uuid NOT NULL,+ "name" text NOT NULL,+ "prefix" text NOT NULL,+ "key_hash" text NOT NULL,+ "last_used_at" timestamptz,+ "revoked_at" timestamptz,+ "created_at" timestamptz NOT NULL DEFAULT now()+);++ALTER TABLE "public"."api_keys" OWNER TO "postgres";++ALTER TABLE ONLY "public"."api_keys"+ ADD CONSTRAINT "api_keys_pkey" PRIMARY KEY ("id");++ALTER TABLE ONLY "public"."api_keys"+ ADD CONSTRAINT "api_keys_user_id_fkey"+ FOREIGN KEY ("user_id")+ REFERENCES "auth"."users"("id") ON DELETE CASCADE;++ALTER TABLE ONLY "public"."api_keys"+ ADD CONSTRAINT "api_keys_key_hash_key" UNIQUE ("key_hash");++CREATE INDEX IF NOT EXISTS "idx_api_keys_user_id"+ ON "public"."api_keys" USING btree ("user_id");++CREATE INDEX IF NOT EXISTS "idx_api_keys_key_hash"+ ON "public"."api_keys" USING btree ("key_hash");++-- RLS+ALTER TABLE "public"."api_keys" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Users can view their own api keys"+ ON "public"."api_keys" FOR SELECT+ USING (user_id = auth.uid());++CREATE POLICY "Users can insert their own api keys"+ ON "public"."api_keys" FOR INSERT+ WITH CHECK (user_id = auth.uid());++CREATE POLICY "Users can revoke their own api keys"+ ON "public"."api_keys" FOR UPDATE+ USING (user_id = auth.uid());++CREATE POLICY "Users can delete their own api keys"+ ON "public"."api_keys" FOR DELETE+ USING (user_id = auth.uid());++GRANT ALL ON TABLE "public"."api_keys" TO "anon";+GRANT ALL ON TABLE "public"."api_keys" TO "authenticated";+GRANT ALL ON TABLE "public"."api_keys" TO "service_role";diff --git a/web/package.json b/web/package.jsonindex b9468ebde..c3c615d86 100644--- a/web/package.json+++ b/web/package.json@@ -18,6 +18,7 @@},"dependencies": {"@base-ui/react": "^1.2.0",+ "@modelcontextprotocol/sdk": "^1.29.0","@radix-ui/react-checkbox": "^1.3.3","@stripe/stripe-js": "^9.1.0","@supabase/ssr": "^0.9.0",@@ -45,6 +46,7 @@"stripe": "^22.0.0","tailwind-merge": "^3.5.0","tw-animate-css": "^1.4.0",+ "zod": "^4.4.3","zustand": "^5.0.11"},"devDependencies": {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/settings/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/settings/page.tsxindex ed85782c2..866b7922e 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/settings/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/settings/page.tsx@@ -16,8 +16,9 @@ import { cn } from "@/lib/utils";import { usePlanContext } from "@/components/providers/plan-provider";import { BillingSection } from "@/components/settings/billing-section";import { TeamSection } from "@/components/settings/team-section";+import { ApiKeysSection } from "@/components/settings/api-keys-section";-type Section = "account" | "theme" | "project" | "team" | "billing";+type Section = "account" | "theme" | "project" | "team" | "api-keys" | "billing";export default function SettingsPage() {const t = useTranslations("settings");@@ -52,6 +53,7 @@ export default function SettingsPage() {{ id: "theme", label: t("theme") },{ id: "project", label: t("project") },{ id: "team", label: t("team") },+ { id: "api-keys", label: "API Keys" },...(isCloud ? [{ id: "billing" as Section, label: t("billing") }] : []),];@@ -174,6 +176,9 @@ export default function SettingsPage() {{/* Team */}{active === "team" && <TeamSection />}+ {/* API Keys */}+ {active === "api-keys" && <ApiKeysSection />}+{/* Billing */}{active === "billing" && isCloud && <BillingSection />}</div>diff --git a/web/src/app/api/keys/[id]/route.ts b/web/src/app/api/keys/[id]/route.tsnew file mode 100644index 000000000..a5ea93301--- /dev/null+++ b/web/src/app/api/keys/[id]/route.ts@@ -0,0 +1,28 @@+import { NextResponse } from 'next/server';+import { createClient } from '@/lib/supabase/server';++export async function DELETE(+ _req: Request,+ { params }: { params: Promise<{ id: string }> },+) {+ const { id } = await params;+ const supabase = await createClient();+ const {+ data: { user },+ } = await supabase.auth.getUser();+ if (!user) {+ return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });+ }++ const { error } = await supabase+ .from('api_keys')+ .update({ revoked_at: new Date().toISOString() })+ .eq('id', id)+ .eq('user_id', user.id);++ if (error) {+ return NextResponse.json({ error: error.message }, { status: 500 });+ }++ return NextResponse.json({ ok: true });+}diff --git a/web/src/app/api/keys/route.ts b/web/src/app/api/keys/route.tsnew file mode 100644index 000000000..e320567c5--- /dev/null+++ b/web/src/app/api/keys/route.ts@@ -0,0 +1,65 @@+import { NextResponse } from 'next/server';+import { createClient } from '@/lib/supabase/server';+import { generateApiKey } from '@/lib/mcp-auth';++export async function GET() {+ const supabase = await createClient();+ const {+ data: { user },+ } = await supabase.auth.getUser();+ if (!user) {+ return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });+ }++ const { data, error } = await supabase+ .from('api_keys')+ .select('id, name, prefix, last_used_at, revoked_at, created_at')+ .eq('user_id', user.id)+ .order('created_at', { ascending: false });++ if (error) {+ return NextResponse.json({ error: error.message }, { status: 500 });+ }++ return NextResponse.json({ keys: data ?? [] });+}++export async function POST(req: Request) {+ const supabase = await createClient();+ const {+ data: { user },+ } = await supabase.auth.getUser();+ if (!user) {+ return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });+ }++ const body = (await req.json().catch(() => ({}))) as { name?: string };+ const name = (body.name ?? '').trim().slice(0, 80);+ if (!name) {+ return NextResponse.json({ error: 'Name is required' }, { status: 400 });+ }++ const { token, hash, prefix } = generateApiKey();++ const { data, error } = await supabase+ .from('api_keys')+ .insert({+ user_id: user.id,+ name,+ prefix,+ key_hash: hash,+ })+ .select('id, name, prefix, created_at')+ .single();++ if (error || !data) {+ return NextResponse.json(+ { error: error?.message ?? 'Could not create key' },+ { status: 500 },+ );+ }++ return NextResponse.json({+ key: { ...data, token },+ });+}diff --git a/web/src/app/api/mcp/brands/route.ts b/web/src/app/api/mcp/brands/route.tsnew file mode 100644index 000000000..671a59087--- /dev/null+++ b/web/src/app/api/mcp/brands/route.ts@@ -0,0 +1,16 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { listBrandsFor } from '@/lib/mcp/data';++export async function GET(req: Request) {+ const auth = await authenticateMcpRequest(req);+ if (auth instanceof NextResponse) return auth;++ try {+ const brands = await listBrandsFor(auth);+ return NextResponse.json({ brands });+ } catch (err) {+ const message = err instanceof Error ? err.message : 'Failed';+ return NextResponse.json({ error: message }, { status: 500 });+ }+}diff --git a/web/src/app/api/mcp/route.ts b/web/src/app/api/mcp/route.tsnew file mode 100644index 000000000..2e8ea9069--- /dev/null+++ b/web/src/app/api/mcp/route.ts@@ -0,0 +1,45 @@+import { NextResponse } from 'next/server';+import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';++import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { createMcpServer } from '@/lib/mcp/server';++export const dynamic = 'force-dynamic';++/**+ * Streamable HTTP entry point for the Ansvisor MCP server. Claude Desktop,+ * Claude Code, Cursor, Zed, and other MCP-aware clients hit this URL with a+ * Bearer API key. Each request gets a fresh `McpServer` + transport bound to+ * the caller's user context, then is discarded — stateless, no session+ * memory between requests.+ */+async function handle(req: Request): Promise<Response> {+ const auth = await authenticateMcpRequest(req);+ if (auth instanceof NextResponse) return auth;++ const server = createMcpServer(auth);+ const transport = new WebStandardStreamableHTTPServerTransport({+ sessionIdGenerator: undefined,+ enableJsonResponse: true,+ });++ try {+ await server.connect(transport);+ return await transport.handleRequest(req);+ } catch (err) {+ const message = err instanceof Error ? err.message : 'MCP request failed';+ return NextResponse.json({ error: message }, { status: 500 });+ }+}++export async function POST(req: Request) {+ return handle(req);+}++export async function GET(req: Request) {+ return handle(req);+}++export async function DELETE(req: Request) {+ return handle(req);+}diff --git a/web/src/app/api/mcp/visibility-summary/route.ts b/web/src/app/api/mcp/visibility-summary/route.tsnew file mode 100644index 000000000..de48a5a4b--- /dev/null+++ b/web/src/app/api/mcp/visibility-summary/route.ts@@ -0,0 +1,33 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { getVisibilitySummaryFor } from '@/lib/mcp/data';++export async function GET(req: Request) {+ const auth = await authenticateMcpRequest(req);+ if (auth instanceof NextResponse) return auth;++ const url = new URL(req.url);+ const brandId = url.searchParams.get('brand_id');+ if (!brandId) {+ return NextResponse.json({ error: 'brand_id is required' }, { status: 400 });+ }++ try {+ const summary = await getVisibilitySummaryFor(auth, {+ brandId,+ dateFrom: url.searchParams.get('date_from') ?? undefined,+ dateTo: url.searchParams.get('date_to') ?? undefined,+ model: url.searchParams.get('model') ?? undefined,+ region: url.searchParams.get('region') ?? undefined,+ });++ if (!summary) {+ return NextResponse.json({ error: 'Brand not found' }, { status: 404 });+ }++ return NextResponse.json(summary);+ } catch (err) {+ const message = err instanceof Error ? err.message : 'Failed';+ return NextResponse.json({ error: message }, { status: 500 });+ }+}diff --git a/web/src/app/api/mcp/whoami/route.ts b/web/src/app/api/mcp/whoami/route.tsnew file mode 100644index 000000000..f3fec38f5--- /dev/null+++ b/web/src/app/api/mcp/whoami/route.ts@@ -0,0 +1,13 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';++export async function GET(req: Request) {+ const auth = await authenticateMcpRequest(req);+ if (auth instanceof NextResponse) return auth;++ return NextResponse.json({+ userId: auth.userId,+ email: auth.email,+ organizationId: auth.organizationId,+ });+}diff --git a/web/src/components/settings/api-keys-section.tsx b/web/src/components/settings/api-keys-section.tsxnew file mode 100644index 000000000..da70a51d7--- /dev/null+++ b/web/src/components/settings/api-keys-section.tsx@@ -0,0 +1,289 @@+"use client";++import { useCallback, useEffect, useState } from "react";+import { toast } from "sonner";+import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+} from "@/components/ui/card";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Skeleton } from "@/components/ui/skeleton";+import { Badge } from "@/components/ui/badge";+import { Copy, KeyRound, Loader2, Plus, Trash2 } from "lucide-react";++interface ApiKey {+ id: string;+ name: string;+ prefix: string;+ last_used_at: string | null;+ revoked_at: string | null;+ created_at: string;+}++function formatDate(iso: string | null): string {+ if (!iso) return "—";+ return new Date(iso).toLocaleDateString(undefined, {+ year: "numeric",+ month: "short",+ day: "numeric",+ });+}++export function ApiKeysSection() {+ const [keys, setKeys] = useState<ApiKey[]>([]);+ const [loading, setLoading] = useState(true);+ const [createOpen, setCreateOpen] = useState(false);+ const [newName, setNewName] = useState("");+ const [creating, setCreating] = useState(false);+ const [revealedToken, setRevealedToken] = useState<string | null>(null);++ const load = useCallback(async () => {+ setLoading(true);+ try {+ const res = await fetch("/api/keys");+ const body = (await res.json()) as { keys?: ApiKey[]; error?: string };+ if (!res.ok) throw new Error(body.error || "Failed to load");+ setKeys(body.keys ?? []);+ } catch (err) {+ toast.error(err instanceof Error ? err.message : "Failed to load");+ } finally {+ setLoading(false);+ }+ }, []);++ useEffect(() => {+ load();+ }, [load]);++ const handleCreate = async () => {+ if (!newName.trim()) return;+ setCreating(true);+ try {+ const res = await fetch("/api/keys", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name: newName.trim() }),+ });+ const body = (await res.json()) as {+ key?: ApiKey & { token: string };+ error?: string;+ };+ if (!res.ok || !body.key) throw new Error(body.error || "Failed to create");+ setRevealedToken(body.key.token);+ setNewName("");+ setCreateOpen(false);+ await load();+ } catch (err) {+ toast.error(err instanceof Error ? err.message : "Failed to create");+ } finally {+ setCreating(false);+ }+ };++ const handleRevoke = async (id: string) => {+ if (!confirm("Revoke this API key? Clients using it will lose access immediately.")) {+ return;+ }+ try {+ const res = await fetch(`/api/keys/${id}`, { method: "DELETE" });+ if (!res.ok) {+ const body = (await res.json().catch(() => ({}))) as { error?: string };+ throw new Error(body.error || "Failed to revoke");+ }+ toast.success("Key revoked");+ await load();+ } catch (err) {+ toast.error(err instanceof Error ? err.message : "Failed to revoke");+ }+ };++ const copy = async (text: string) => {+ await navigator.clipboard.writeText(text);+ toast.success("Copied to clipboard");+ };++ return (+ <Card>+ <CardHeader>+ <div className="flex items-start justify-between gap-4">+ <div>+ <CardTitle className="flex items-center gap-2">+ <KeyRound className="h-4 w-4" />+ API Keys+ </CardTitle>+ <CardDescription>+ Long-lived tokens for the Ansvisor MCP server and other external+ clients. Keys are shown once at creation — store them somewhere safe.+ </CardDescription>+ </div>+ <Button size="sm" onClick={() => setCreateOpen(true)} className="gap-1.5 shrink-0">+ <Plus className="h-4 w-4" />+ New key+ </Button>+ </div>+ </CardHeader>+ <CardContent className="space-y-3">+ <div className="rounded-md border bg-muted/40 p-3 text-xs space-y-1.5">+ <p className="font-medium text-foreground">MCP endpoint</p>+ <div className="flex items-center gap-2">+ <code className="flex-1 truncate font-mono">+ {typeof window !== "undefined" ? window.location.origin : ""}+ /api/mcp+ </code>+ <Button+ size="sm"+ variant="ghost"+ className="h-6 px-2"+ onClick={() =>+ copy(`${window.location.origin}/api/mcp`)+ }+ >+ <Copy className="h-3 w-3" />+ </Button>+ </div>+ <p className="text-muted-foreground">+ Paste this URL + a key below into Claude Desktop / Claude Code /+ Cursor. See the{" "}+ <a+ href="https://github.com/aeohub/ansvisor#whats-next"+ target="_blank"+ rel="noreferrer"+ className="underline"+ >+ MCP guide+ </a>+ .+ </p>+ </div>++ {loading ? (+ <div className="space-y-2">+ <Skeleton className="h-12 w-full" />+ <Skeleton className="h-12 w-full" />+ </div>+ ) : keys.length === 0 ? (+ <p className="text-sm text-muted-foreground py-6 text-center">+ No API keys yet. Create one to connect the MCP server.+ </p>+ ) : (+ <div className="divide-y rounded-md border">+ {keys.map((k) => {+ const revoked = !!k.revoked_at;+ return (+ <div+ key={k.id}+ className="flex items-center justify-between gap-4 p-3"+ >+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-2">+ <p className="text-sm font-medium truncate">{k.name}</p>+ {revoked && (+ <Badge variant="outline" className="text-[10px]">+ revoked+ </Badge>+ )}+ </div>+ <p className="text-xs text-muted-foreground font-mono">+ {k.prefix}…+ </p>+ <p className="text-[11px] text-muted-foreground">+ Created {formatDate(k.created_at)} · Last used{" "}+ {formatDate(k.last_used_at)}+ </p>+ </div>+ {!revoked && (+ <Button+ variant="ghost"+ size="sm"+ onClick={() => handleRevoke(k.id)}+ className="text-destructive hover:text-destructive"+ >+ <Trash2 className="h-4 w-4" />+ </Button>+ )}+ </div>+ );+ })}+ </div>+ )}+ </CardContent>++ <Dialog open={createOpen} onOpenChange={setCreateOpen}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>New API key</DialogTitle>+ <DialogDescription>+ Give this key a memorable name (e.g. "MCP — my laptop").+ </DialogDescription>+ </DialogHeader>+ <div className="space-y-2 py-2">+ <Label htmlFor="apiKeyName">Name</Label>+ <Input+ id="apiKeyName"+ value={newName}+ onChange={(e) => setNewName(e.target.value)}+ placeholder="MCP — local"+ autoFocus+ disabled={creating}+ />+ </div>+ <DialogFooter>+ <DialogClose render={<Button variant="outline" disabled={creating} />}>+ Cancel+ </DialogClose>+ <Button+ onClick={handleCreate}+ disabled={creating || !newName.trim()}+ >+ {creating && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}+ Create+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ <Dialog+ open={!!revealedToken}+ onOpenChange={(v) => !v && setRevealedToken(null)}+ >+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Copy your API key</DialogTitle>+ <DialogDescription>+ You won't be able to see this again. Store it somewhere safe.+ </DialogDescription>+ </DialogHeader>+ <div className="space-y-2 py-2">+ <div className="flex items-center gap-2 rounded-md border bg-muted/40 p-2 font-mono text-xs">+ <code className="flex-1 truncate">{revealedToken}</code>+ <Button+ size="sm"+ variant="ghost"+ onClick={() => revealedToken && copy(revealedToken)}+ >+ <Copy className="h-4 w-4" />+ </Button>+ </div>+ </div>+ <DialogFooter>+ <Button onClick={() => setRevealedToken(null)}>Done</Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </Card>+ );+}diff --git a/web/src/lib/mcp-auth.ts b/web/src/lib/mcp-auth.tsnew file mode 100644index 000000000..bf61d5659--- /dev/null+++ b/web/src/lib/mcp-auth.ts@@ -0,0 +1,82 @@+import { createHash, randomBytes } from 'node:crypto';+import { NextResponse } from 'next/server';+import { supabaseAdmin } from '@/lib/supabase/admin';++export const API_KEY_PREFIX = 'ans_';+export const API_KEY_DISPLAY_PREFIX_LEN = 12;++export function generateApiKey(): { token: string; hash: string; prefix: string } {+ const token = `${API_KEY_PREFIX}${randomBytes(32).toString('base64url')}`;+ const hash = createHash('sha256').update(token).digest('hex');+ const prefix = token.slice(0, API_KEY_DISPLAY_PREFIX_LEN);+ return { token, hash, prefix };+}++export function hashApiKey(token: string): string {+ return createHash('sha256').update(token).digest('hex');+}++export interface McpAuthContext {+ userId: string;+ email: string | null;+ organizationId: string | null;+ apiKeyId: string;+}++/**+ * Resolve the bearer token on a request into a user/org context.+ *+ * Accepts only Ansvisor API keys (prefix `ans_`) — not Supabase session JWTs.+ * MCP endpoints are intended to be hit by long-lived external clients, so we+ * intentionally don't fall back to the dashboard's session cookie.+ */+export async function authenticateMcpRequest(+ req: Request,+): Promise<McpAuthContext | NextResponse> {+ const auth = req.headers.get('authorization') ?? '';+ const token = auth.startsWith('Bearer ') ? auth.slice(7).trim() : '';++ if (!token || !token.startsWith(API_KEY_PREFIX)) {+ return NextResponse.json(+ { error: 'Missing or malformed API key' },+ { status: 401 },+ );+ }++ const hash = hashApiKey(token);++ const { data: key, error } = await supabaseAdmin+ .from('api_keys')+ .select('id, user_id, revoked_at')+ .eq('key_hash', hash)+ .maybeSingle();++ if (error || !key || key.revoked_at) {+ return NextResponse.json({ error: 'Invalid API key' }, { status: 401 });+ }++ // Resolve the owning user + their organization so handlers don't have to.+ const { data: profile } = await supabaseAdmin+ .from('profiles')+ .select('organization_id')+ .eq('id', key.user_id)+ .maybeSingle();++ // Best-effort touch — failing here shouldn't block the request.+ supabaseAdmin+ .from('api_keys')+ .update({ last_used_at: new Date().toISOString() })+ .eq('id', key.id)+ .then(() => {});++ const {+ data: { user },+ } = await supabaseAdmin.auth.admin.getUserById(key.user_id);++ return {+ userId: key.user_id,+ email: user?.email ?? null,+ organizationId: profile?.organization_id ?? null,+ apiKeyId: key.id,+ };+}diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.tsnew file mode 100644index 000000000..8a3e0301e--- /dev/null+++ b/web/src/lib/mcp/data.ts@@ -0,0 +1,163 @@+import { supabaseAdmin } from '@/lib/supabase/admin';+import type { McpAuthContext } from '@/lib/mcp-auth';++/**+ * Pure data-fetch functions shared by the MCP route and the parallel REST+ * endpoints under `/api/mcp/*`. Each function takes an authenticated context+ * (already resolved to a user + organization) and returns plain JSON the+ * caller can ship over the wire or into an MCP tool result.+ */++export interface BrandRow {+ id: string;+ name: string;+ slug: string;+ industry: string | null;+ region: string | null;+ created_at: string;+}++export async function listBrandsFor(+ auth: McpAuthContext,+): Promise<BrandRow[]> {+ if (!auth.organizationId) return [];++ const { data, error } = await supabaseAdmin+ .from('brands')+ .select('id, name, slug, industry, region, created_at')+ .eq('organization_id', auth.organizationId)+ .order('created_at', { ascending: false });++ if (error) throw new Error(error.message);+ return (data ?? []) as BrandRow[];+}++export interface VisibilitySummaryParams {+ brandId: string;+ dateFrom?: string;+ dateTo?: string;+ model?: string;+ region?: string;+}++export interface VisibilitySummary {+ brand: { id: string; name: string };+ totals: {+ resultCount: number;+ avgVisibility: number;+ totalMentions: number;+ totalCitations: number;+ };+ topCompetitors: Array<{+ name: string;+ mentions: number;+ avgVisibility: number;+ }>;+}++interface CompetitorMentionRow {+ name: string;+ mention_count: number;+ visibility_score: number;+}++export async function getVisibilitySummaryFor(+ auth: McpAuthContext,+ params: VisibilitySummaryParams,+): Promise<VisibilitySummary | null> {+ if (!auth.organizationId) return null;++ const { data: brand } = await supabaseAdmin+ .from('brands')+ .select('id, name')+ .eq('id', params.brandId)+ .eq('organization_id', auth.organizationId)+ .maybeSingle();+ if (!brand) return null;++ let query = supabaseAdmin+ .from('prompt_results')+ .select(+ 'visibility_score, mention_count, citation_count, sentiment, model_used, competitor_mentions',+ )+ .eq('brand_id', params.brandId);++ if (params.dateFrom) query = query.gte('created_at', params.dateFrom);+ if (params.dateTo) query = query.lte('created_at', params.dateTo);+ if (params.region) query = query.eq('region', params.region);+ if (params.model) {+ const list = params.model+ .split(',')+ .map((s) => s.trim())+ .filter(Boolean);+ query =+ list.length > 1+ ? query.in('model_used', list)+ : query.eq('model_used', list[0] ?? params.model);+ }++ const { data: rows, error } = await query;+ if (error) throw new Error(error.message);++ const results = (rows ?? []) as Array<{+ visibility_score: number;+ mention_count: number;+ citation_count: number;+ sentiment: string;+ model_used: string | null;+ competitor_mentions: CompetitorMentionRow[] | null;+ }>;++ if (results.length === 0) {+ return {+ brand: { id: brand.id, name: brand.name },+ totals: {+ resultCount: 0,+ avgVisibility: 0,+ totalMentions: 0,+ totalCitations: 0,+ },+ topCompetitors: [],+ };+ }++ let totalMentions = 0;+ let totalCitations = 0;+ let sumVis = 0;+ const compTotals = new Map<string, { mentions: number; visSum: number }>();++ for (const r of results) {+ sumVis += r.visibility_score ?? 0;+ totalMentions += r.mention_count ?? 0;+ totalCitations += r.citation_count ?? 0;+ for (const cm of r.competitor_mentions ?? []) {+ const agg = compTotals.get(cm.name) ?? { mentions: 0, visSum: 0 };+ agg.mentions += cm.mention_count ?? 0;+ agg.visSum += cm.visibility_score ?? 0;+ compTotals.set(cm.name, agg);+ }+ }++ const avgVisibility = Math.round((sumVis / results.length) * 10) / 10;++ const topCompetitors = [...compTotals.entries()]+ .map(([name, agg]) => ({+ name,+ mentions: agg.mentions,+ avgVisibility:+ Math.round((agg.visSum / Math.max(agg.mentions, 1)) * 10) / 10,+ }))+ .sort((a, b) => b.mentions - a.mentions)+ .slice(0, 5);++ return {+ brand: { id: brand.id, name: brand.name },+ totals: {+ resultCount: results.length,+ avgVisibility,+ totalMentions,+ totalCitations,+ },+ topCompetitors,+ };+}diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.tsnew file mode 100644index 000000000..16276c5f4--- /dev/null+++ b/web/src/lib/mcp/server.ts@@ -0,0 +1,92 @@+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+import { z } from 'zod';++import type { McpAuthContext } from '@/lib/mcp-auth';+import { getVisibilitySummaryFor, listBrandsFor } from './data';++/**+ * Build a fresh MCP server bound to a single authenticated request.+ *+ * Each call creates a new `McpServer` with tool handlers that close over the+ * `auth` context. The Streamable HTTP route uses this in stateless mode, so+ * connect/run/discard per request — no shared state.+ */+export function createMcpServer(auth: McpAuthContext): McpServer {+ const server = new McpServer({+ name: 'ansvisor',+ version: '0.1.0',+ });++ server.registerTool(+ 'list_brands',+ {+ description:+ 'List the brands the authenticated user can access. Returns one row per brand with id, name, slug, industry, region, and creation date. Always call this first to resolve a brand id before using other tools.',+ inputSchema: {},+ },+ async () => {+ const brands = await listBrandsFor(auth);+ return {+ content: [+ { type: 'text', text: JSON.stringify(brands, null, 2) },+ ],+ };+ },+ );++ server.registerTool(+ 'get_visibility_summary',+ {+ description:+ 'Get aggregate visibility metrics for a brand over an optional date range and filter. Returns result count, average visibility score (0-100), total mentions, total citations, and the top 5 competitors by mention count. Use this for "how is my brand doing" / "what changed" style questions.',+ inputSchema: {+ brand_id: z+ .string()+ .uuid()+ .describe('Brand UUID, from list_brands.'),+ date_from: z+ .string()+ .optional()+ .describe(+ 'ISO timestamp (inclusive) lower bound, e.g. 2026-05-01T00:00:00Z.',+ ),+ date_to: z+ .string()+ .optional()+ .describe('ISO timestamp (inclusive) upper bound.'),+ model: z+ .string()+ .optional()+ .describe(+ 'Optional model slug filter, or comma-separated list of slugs to filter a provider family.',+ ),+ region: z+ .string()+ .optional()+ .describe('Optional region code filter (e.g. "US", "TR").'),+ },+ },+ async (args) => {+ const summary = await getVisibilitySummaryFor(auth, {+ brandId: args.brand_id,+ dateFrom: args.date_from,+ dateTo: args.date_to,+ model: args.model,+ region: args.region,+ });+ if (!summary) {+ return {+ content: [{ type: 'text', text: 'Brand not found' }],+ isError: true,+ };+ }+ return {+ content: [+ { type: 'text', text: JSON.stringify(summary, null, 2) },+ ],+ };+ },+ );++ return server;+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex c28948349..cb99f67d6 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -14,6 +14,39 @@ export type Database = {};public: {Tables: {+ api_keys: {+ Row: {+ id: string;+ user_id: string;+ name: string;+ prefix: string;+ key_hash: string;+ last_used_at: string | null;+ revoked_at: string | null;+ created_at: string;+ };+ Insert: {+ id?: string;+ user_id: string;+ name: string;+ prefix: string;+ key_hash: string;+ last_used_at?: string | null;+ revoked_at?: string | null;+ created_at?: string;+ };+ Update: {+ id?: string;+ user_id?: string;+ name?: string;+ prefix?: string;+ key_hash?: string;+ last_used_at?: string | null;+ revoked_at?: string | null;+ created_at?: string;+ };+ Relationships: [];+ };ai_traffic_logs: {Row: {brand_id: string;diff --git a/web/yarn.lock b/web/yarn.lockindex 2d7a2df53..f96e3c56d 100644--- a/web/yarn.lock+++ b/web/yarn.lock@@ -732,6 +732,29 @@zod "^3.25 || ^4.0"zod-to-json-schema "^3.25.1"+"@modelcontextprotocol/sdk@^1.29.0":+ version "1.29.0"+ resolved "https://registry.yarnpkg.com/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz#79786d8b525e269de850ac82b1f1f757f3915f44"+ integrity sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==+ dependencies:+ "@hono/node-server" "^1.19.9"+ ajv "^8.17.1"+ ajv-formats "^3.0.1"+ content-type "^1.0.5"+ cors "^2.8.5"+ cross-spawn "^7.0.5"+ eventsource "^3.0.2"+ eventsource-parser "^3.0.0"+ express "^5.2.1"+ express-rate-limit "^8.2.1"+ hono "^4.11.4"+ jose "^6.1.3"+ json-schema-typed "^8.0.2"+ pkce-challenge "^5.0.0"+ raw-body "^3.0.0"+ zod "^3.25 || ^4.0"+ zod-to-json-schema "^3.25.1"+"@mswjs/interceptors@^0.41.2":version "0.41.3"resolved "https://registry.npmjs.org/@mswjs/interceptors/-/interceptors-0.41.3.tgz"@@ -6937,6 +6960,11 @@ zod@^3.24.1:resolved "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz"integrity sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==+zod@^4.4.3:+ version "4.4.3"+ resolved "https://registry.yarnpkg.com/zod/-/zod-4.4.3.tgz#b680f172885d18bbebf21a834ea25e55a1bbf356"+ integrity sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==+zustand@^5.0.11:version "5.0.11"resolved "https://registry.npmjs.org/zustand/-/zustand-5.0.11.tgz"