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(integrations): Looker Studio Community Connector (#426)
Gökhan Geyik743887f932d9
diff --git a/docs/guides/looker-studio.mdx b/docs/guides/looker-studio.mdxnew file mode 100644index 000000000..1abda0388--- /dev/null+++ b/docs/guides/looker-studio.mdx@@ -0,0 +1,46 @@+---+title: "Looker Studio"+description: "Blend Ansvisor AI visibility metrics with GA4 and Search Console in one Looker Studio dashboard."+---++The Ansvisor Community Connector pulls your AI visibility metrics into Looker Studio, so a single dashboard can show AI visibility next to organic traffic: GA4 sessions, Search Console clicks, and Ansvisor's visibility score on one date axis.++<Note>+ The connector is distributed by deployment link while it awaits the partner+ gallery. Ask us for the current link, or deploy your own copy from+ [`integrations/looker-studio`](https://github.com/ansvisor/ansvisor/tree/main/integrations/looker-studio)+ in the repo.+</Note>++## Connect++1. Create an API key in the dashboard under **Settings → API Keys** and copy the `ans_...` token — it's shown only once.+2. Open the connector's deployment link. Looker Studio asks you to authorize the connector, then prompts for a key: paste the token.+3. Pick the **brand** and a **metric set**, then hit **Connect** → **Add to report**.++## Metric sets++Each data source exposes one metric set. Add several data sources if you need more than one in a report.++| Metric set | Dimension | Metrics |+| ------------------------------ | ---------------- | -------------------------------------------------------------------------- |+| **Visibility Trend (daily)** | Date | Avg visibility score, mentions, citations, tracked results, competitor avg |+| **Share of Voice by Platform** | Platform | Brand mentions, competitor mentions, SoV % |+| **Citations — Top Domains** | Domain, category | Citations, results citing, usage % |+| **AI Traffic by Platform** | Platform | Visits |++The report's date range control drives every request — no per-source date configuration needed.++## Blending with GA4++The Visibility Trend set is built for blending: join it to a GA4 source on the **Date** dimension and plot _Avg Visibility Score_ against _Sessions_ on a dual-axis time series. A rising visibility line that precedes a traffic lift is the clearest way to show AI-search impact to a client.++## Notes & limits++- Responses are cached for 5 minutes per user, so dashboards with many charts don't hammer the API.+- The key is scoped to its creator's organization: only that organization's brands appear in the brand picker.+- Revoking the key in Settings immediately breaks the data source (it will ask for new credentials).++<Card title="Metrics API reference" icon="code" href="/api-reference/metrics">+ The same endpoints, documented — for Sheets, Power BI or custom integrations.+</Card>diff --git a/docs/mint.json b/docs/mint.jsonindex e45d965b6..187c69d82 100644--- a/docs/mint.json+++ b/docs/mint.json@@ -84,7 +84,8 @@"guides/ai-traffic-analytics","guides/competitors","guides/content-optimization",- "guides/mcp-server"+ "guides/mcp-server",+ "guides/looker-studio"]},{diff --git a/integrations/looker-studio/Code.js b/integrations/looker-studio/Code.jsnew file mode 100644index 000000000..6664b27bc--- /dev/null+++ b/integrations/looker-studio/Code.js@@ -0,0 +1,391 @@+/**+ * Ansvisor Looker Studio Community Connector.+ *+ * Pulls read-only metrics from the Public Metrics API (`/api/v1/*`, see+ * docs → API Reference → Metrics API) so agencies can blend AI visibility+ * data with GA4 / Search Console in one dashboard. Authenticates with an+ * Ansvisor API key (Settings → API Keys, prefix `ans_`).+ *+ * Apps Script project — deploy with clasp or paste into script.google.com.+ * Self-hosters: change BASE_URL below AND the urlFetchWhitelist entry in+ * appsscript.json to your web app's origin.+ */++var cc = DataStudioApp.createCommunityConnector();++var BASE_URL = "https://app.ansvisor.com";+var KEY_PROPERTY = "ansvisor.apiKey";+/** Per-chart fetches repeat on every viewer interaction — cache API reads. */+var CACHE_TTL_SECONDS = 300;++var REPORT_TYPES = [+ { id: "visibility_trend", label: "Visibility Trend (daily)" },+ { id: "share_of_voice", label: "Share of Voice by Platform" },+ { id: "citations_domains", label: "Citations — Top Domains" },+ { id: "ai_traffic_platforms", label: "AI Traffic by Platform" },+];++// ─── Auth ────────────────────────────────────────────────────────────────────++function getAuthType() {+ return cc+ .newAuthTypeResponse()+ .setAuthType(cc.AuthType.KEY)+ .setHelpUrl(+ "https://github.com/ansvisor/ansvisor/blob/main/docs/api-reference/metrics.mdx",+ )+ .build();+}++function isAdminUser() {+ return false;+}++function checkForValidKey(key) {+ if (!key || key.indexOf("ans_") !== 0) return false;+ var response = UrlFetchApp.fetch(BASE_URL + "/api/v1/whoami", {+ headers: { Authorization: "Bearer " + key },+ muteHttpExceptions: true,+ });+ return response.getResponseCode() === 200;+}++function setCredentials(request) {+ var key = request.key;+ if (!checkForValidKey(key)) {+ return { errorCode: "INVALID_CREDENTIALS" };+ }+ PropertiesService.getUserProperties().setProperty(KEY_PROPERTY, key);+ return { errorCode: "NONE" };+}++function isAuthValid() {+ var key = PropertiesService.getUserProperties().getProperty(KEY_PROPERTY);+ return checkForValidKey(key);+}++function resetAuth() {+ PropertiesService.getUserProperties().deleteProperty(KEY_PROPERTY);+}++// ─── API helper ──────────────────────────────────────────────────────────────++function throwUserError(message) {+ cc.newUserError().setText(message).throwException();+}++/**+ * GET an /api/v1 path with the stored key, short-cache the parsed JSON.+ * Cache key includes the API key hash so two data sources with different+ * keys never share entries.+ */+function apiGet(path, params) {+ var key = PropertiesService.getUserProperties().getProperty(KEY_PROPERTY);+ if (!key)+ throwUserError(+ "Your Ansvisor API key is missing — reconnect the data source.",+ );++ var query = [];+ for (var name in params) {+ if (+ params[name] !== undefined &&+ params[name] !== null &&+ params[name] !== ""+ ) {+ query.push(+ encodeURIComponent(name) + "=" + encodeURIComponent(params[name]),+ );+ }+ }+ var url = BASE_URL + path + (query.length ? "?" + query.join("&") : "");++ var cache = CacheService.getUserCache();+ var cacheKey = Utilities.base64Encode(+ Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, url + "|" + key),+ );+ var cached = cache.get(cacheKey);+ if (cached) return JSON.parse(cached);++ var response = UrlFetchApp.fetch(url, {+ headers: { Authorization: "Bearer " + key },+ muteHttpExceptions: true,+ });+ var code = response.getResponseCode();+ var body = response.getContentText();++ if (code === 401)+ throwUserError("Ansvisor rejected the API key — it may have been revoked.");+ if (code === 404)+ throwUserError("Brand not found — pick a brand this API key can access.");+ if (code !== 200)+ throwUserError("Ansvisor API error (" + code + "). Try again in a minute.");++ // CacheService caps values at ~100KB; oversized payloads just skip the cache.+ if (body.length < 90000) {+ cache.put(cacheKey, body, CACHE_TTL_SECONDS);+ }+ return JSON.parse(body);+}++// ─── Config ──────────────────────────────────────────────────────────────────++function getConfig() {+ var config = cc.getConfig();++ config+ .newInfo()+ .setId("instructions")+ .setText(+ "Pick the brand and the metric set this data source should expose.",+ );++ var brandSelect = config+ .newSelectSingle()+ .setId("brandId")+ .setName("Brand")+ .setHelpText("Brands your API key can access.");+ var brands = apiGet("/api/v1/brands", {}).brands || [];+ if (brands.length === 0) {+ throwUserError(+ "No brands found for this API key — create a brand in Ansvisor first.",+ );+ }+ brands.forEach(function (brand) {+ brandSelect.addOption(+ config.newOptionBuilder().setLabel(brand.name).setValue(brand.id),+ );+ });++ var typeSelect = config+ .newSelectSingle()+ .setId("reportType")+ .setName("Metric set")+ .setHelpText(+ "Each metric set has its own fields; use one data source per set.",+ );+ REPORT_TYPES.forEach(function (type) {+ typeSelect.addOption(+ config.newOptionBuilder().setLabel(type.label).setValue(type.id),+ );+ });++ config.setDateRangeRequired(true);+ return config.build();+}++// ─── Schema ──────────────────────────────────────────────────────────────────++function getFieldsFor(reportType) {+ var fields = cc.getFields();+ var types = cc.FieldType;+ var aggregations = cc.AggregationType;++ if (reportType === "visibility_trend") {+ fields+ .newDimension()+ .setId("date")+ .setName("Date")+ .setType(types.YEAR_MONTH_DAY);+ fields+ .newMetric()+ .setId("avg_visibility_score")+ .setName("Avg Visibility Score")+ .setType(types.NUMBER)+ .setAggregation(aggregations.AVG);+ fields+ .newMetric()+ .setId("total_mentions")+ .setName("Mentions")+ .setType(types.NUMBER)+ .setAggregation(aggregations.SUM);+ fields+ .newMetric()+ .setId("total_citations")+ .setName("Citations")+ .setType(types.NUMBER)+ .setAggregation(aggregations.SUM);+ fields+ .newMetric()+ .setId("result_count")+ .setName("Tracked Results")+ .setType(types.NUMBER)+ .setAggregation(aggregations.SUM);+ fields+ .newMetric()+ .setId("avg_competitor_score")+ .setName("Avg Competitor Score")+ .setType(types.NUMBER)+ .setAggregation(aggregations.AVG);+ } else if (reportType === "share_of_voice") {+ fields+ .newDimension()+ .setId("platform")+ .setName("Platform")+ .setType(types.TEXT);+ fields+ .newMetric()+ .setId("brand_mentions")+ .setName("Brand Mentions")+ .setType(types.NUMBER)+ .setAggregation(aggregations.SUM);+ fields+ .newMetric()+ .setId("competitor_mentions")+ .setName("Competitor Mentions")+ .setType(types.NUMBER)+ .setAggregation(aggregations.SUM);+ fields+ .newMetric()+ .setId("sov_pct")+ .setName("Share of Voice %")+ .setType(types.PERCENT);+ } else if (reportType === "citations_domains") {+ fields.newDimension().setId("domain").setName("Domain").setType(types.TEXT);+ fields+ .newDimension()+ .setId("category")+ .setName("Source Category")+ .setType(types.TEXT);+ fields+ .newMetric()+ .setId("total_citations")+ .setName("Citations")+ .setType(types.NUMBER)+ .setAggregation(aggregations.SUM);+ fields+ .newMetric()+ .setId("results_citing")+ .setName("Results Citing")+ .setType(types.NUMBER)+ .setAggregation(aggregations.SUM);+ fields+ .newMetric()+ .setId("usage_pct")+ .setName("Usage %")+ .setType(types.PERCENT);+ } else if (reportType === "ai_traffic_platforms") {+ fields+ .newDimension()+ .setId("platform")+ .setName("Platform")+ .setType(types.TEXT);+ fields+ .newMetric()+ .setId("visits")+ .setName("Visits")+ .setType(types.NUMBER)+ .setAggregation(aggregations.SUM);+ } else {+ throwUserError("Unknown metric set — edit the data source and pick one.");+ }++ return fields;+}++function getSchema(request) {+ var reportType = request.configParams && request.configParams.reportType;+ return { schema: getFieldsFor(reportType).build() };+}++// ─── Data ────────────────────────────────────────────────────────────────────++/** Looker's PERCENT type expects a 0–1 fraction; the API returns 0–100. */+function toFraction(pct) {+ return typeof pct === "number" ? pct / 100 : null;+}++function fetchRowObjects(reportType, brandId, dateFrom, dateTo) {+ var window = { brand_id: brandId, date_from: dateFrom, date_to: dateTo };++ if (reportType === "visibility_trend") {+ var trend = apiGet("/api/v1/visibility-trend", {+ brand_id: brandId,+ date_from: dateFrom,+ date_to: dateTo,+ granularity: "day",+ });+ return (trend.buckets || []).map(function (bucket) {+ return {+ date: bucket.date.replace(/-/g, ""),+ avg_visibility_score: bucket.avg_visibility_score,+ total_mentions: bucket.total_mentions,+ total_citations: bucket.total_citations,+ result_count: bucket.result_count,+ avg_competitor_score: bucket.avg_competitor_score,+ };+ });+ }++ if (reportType === "share_of_voice") {+ var comparison = apiGet("/api/v1/competitor-comparison", window);+ var byPlatform =+ (comparison.share_of_voice && comparison.share_of_voice.by_platform) ||+ [];+ return byPlatform.map(function (row) {+ return {+ platform: row.platform || row.model_used || "unknown",+ brand_mentions: row.brand_mentions,+ competitor_mentions: row.competitor_mentions,+ sov_pct: toFraction(row.sov_pct),+ };+ });+ }++ if (reportType === "citations_domains") {+ var citations = apiGet("/api/v1/citations", window);+ return (citations.top_domains || []).map(function (row) {+ return {+ domain: row.domain,+ category: row.category,+ total_citations: row.total_citations,+ results_citing: row.results_citing,+ usage_pct: toFraction(row.usage_pct),+ };+ });+ }++ if (reportType === "ai_traffic_platforms") {+ var traffic = apiGet("/api/v1/ai-traffic", window);+ return (traffic.platform_breakdown || []).map(function (row) {+ return { platform: row.platform, visits: row.visits };+ });+ }++ throwUserError("Unknown metric set — edit the data source and pick one.");+}++function getData(request) {+ var configParams = request.configParams || {};+ var brandId = configParams.brandId;+ var reportType = configParams.reportType;+ if (!brandId || !reportType) {+ throwUserError(+ "The data source is missing its brand or metric set — edit and reconfigure.",+ );+ }++ var requestedFields = getFieldsFor(reportType).forIds(+ request.fields.map(function (field) {+ return field.name;+ }),+ );++ var rowObjects = fetchRowObjects(+ reportType,+ brandId,+ request.dateRange.startDate,+ request.dateRange.endDate,+ );++ var rows = rowObjects.map(function (rowObject) {+ return {+ values: requestedFields.asArray().map(function (field) {+ var value = rowObject[field.getId()];+ return value === undefined || value === null ? "" : value;+ }),+ };+ });++ return { schema: requestedFields.build(), rows: rows };+}diff --git a/integrations/looker-studio/README.md b/integrations/looker-studio/README.mdnew file mode 100644index 000000000..34468003a--- /dev/null+++ b/integrations/looker-studio/README.md@@ -0,0 +1,35 @@+# Ansvisor Looker Studio Community Connector++Brings the [Public Metrics API](https://github.com/ansvisor/ansvisor/blob/main/docs/api-reference/metrics.mdx) into Looker Studio so Ansvisor metrics can sit next to GA4 / Search Console data in one dashboard.++**Metric sets** (each is one data source):++| Set | Fields | Backing endpoint |+| -------------------------- | -------------------------------------------------------------------------------- | ------------------------------- |+| Visibility Trend (daily) | date, avg visibility, mentions, citations, tracked results, avg competitor score | `/api/v1/visibility-trend` |+| Share of Voice by Platform | platform, brand mentions, competitor mentions, SoV % | `/api/v1/competitor-comparison` |+| Citations — Top Domains | domain, source category, citations, results citing, usage % | `/api/v1/citations` |+| AI Traffic by Platform | platform, visits | `/api/v1/ai-traffic` |++Auth is an Ansvisor API key (dashboard → **Settings → API Keys**). The report-level date range flows into every request; responses are cached for 5 minutes per user.++## Deploying (maintainers)++1. Create an Apps Script project at [script.google.com](https://script.google.com) (or `npx clasp create --type standalone` in this directory).+2. Copy `Code.js` and `appsscript.json` into the project (enable _Show "appsscript.json" manifest file_ in project settings, or use `npx clasp push`).+3. **Deploy → New deployment → Library-less "Add-on" type is not needed** — use _Deploy → Test deployments_ for development, and _Deploy → New deployment_ to mint a versioned deployment for sharing.+4. Share the connector with users via its deployment link: `https://lookerstudio.google.com/datasources/create?connectorId=<deploymentId>`.++Publishing to the partner gallery is a separate, later step (Google review, verified branding, published privacy policy / terms).++## Using (agencies)++1. Open the deployment link above → Looker Studio prompts for authorization.+2. Paste your `ans_...` API key.+3. Pick a brand and a metric set → **Connect**.+4. Add the data source to a report; blend with GA4 on the `Date` field for the visibility-vs-traffic view.++## Self-hosting notes++- Change `BASE_URL` in `Code.js` **and** the `urlFetchWhitelist` entry in `appsscript.json` to your web app's origin, then deploy your own copy.+- `logoUrl` currently points at the GitHub org avatar (`https://github.com/ansvisor.png`); replace with a hosted square PNG before any gallery submission.diff --git a/integrations/looker-studio/appsscript.json b/integrations/looker-studio/appsscript.jsonnew file mode 100644index 000000000..e7c7285f3--- /dev/null+++ b/integrations/looker-studio/appsscript.json@@ -0,0 +1,16 @@+{+ "timeZone": "Etc/UTC",+ "exceptionLogging": "STACKDRIVER",+ "runtimeVersion": "V8",+ "urlFetchWhitelist": ["https://app.ansvisor.com/"],+ "dataStudio": {+ "name": "Ansvisor — AI Visibility Metrics",+ "logoUrl": "https://github.com/ansvisor.png",+ "company": "Ansvisor",+ "companyUrl": "https://www.ansvisor.com",+ "addonUrl": "https://www.ansvisor.com",+ "supportUrl": "https://github.com/ansvisor/ansvisor/issues",+ "description": "Blend Ansvisor AI visibility metrics — ChatGPT, Gemini, Perplexity, Claude and more — with GA4 and Search Console data in one Looker Studio dashboard.",+ "shortDescription": "AI visibility metrics for Looker Studio"+ }+}