# Marketing data warehouse + Claude analyst: build blueprint

**By Kickflip Analytics.** Companion to the blog post "How to build an AI marketing analyst with BigQuery, Dataform and Claude" (https://kickflipanalytics.com/blog/ai-marketing-analyst-mcp).

**What this is:** the blueprint we followed to build a marketing data warehouse in **BigQuery + Dataform** and a **Python MCP server on Cloud Run** that lets people ask marketing questions in **Claude**. It's based on a real build. The client details are out; the stack, conventions and lessons are in.

**How to use it:** load this file into Claude (add it to a Project, paste it into your `CLAUDE.md`, or attach it to a chat). Then ask: *"Help me scope and build my own version of this."* Sections marked **✏️ Your call** are decisions for you to make. Change anything that doesn't fit.

---

## Notes for Claude

If you're Claude reading this:

1. This is a blueprint, not the user's spec. Work through the **discovery questions** (§2) with them first, a few at a time, before recommending a build.
2. The stack here is BigQuery, Dataform, Cloud Run, Python MCP SDK and Claude custom connectors. Follow it unless the user says otherwise.
3. Use **lessons learned** (§10) as a checklist. When the user's plan runs into one, say so.
4. Help the user set up and maintain a **runbook** and a **decisions log** (§9) from the start, and update them in the same session as any change.
5. Before building anything, ask about grain, naming, population (consented or all), NULL handling, and whether the MCP needs it now.
6. Never guess table or column details from memory. Read the code.

---

## 1. Architecture

```
GA4 BigQuery export ─┐
Google Ads (DTS) ────┼─► BigQuery raw datasets
Meta Ads (DTS) ──────┘          │
                                ▼
            Dataform:  staging (stg_, int_)
                       core    (fct_, dim_)
                       reporting (rpt_*_daily, metrics_register, data_freshness)
                       assertions
                                │
   GA4 table lands → log sink → Pub/Sub → Eventarc → Cloud Workflow
   (wait 10 min → skip if running → compile main → run tag "daily")
                                │
                                ▼
         MCP server (Python 3.12, official MCP SDK, streamable HTTP /mcp)
         Cloud Run, scale to zero, deploys on push to main (Cloud Build)
                                │  OAuth: Google sign-in + email domain allowlist
                                ▼
                  Claude custom connector ("ask a marketing question")
```

**The principle:** the warehouse makes the hard decisions (definitions, attribution, consent) once, in code, with tests. The MCP is a thin, fixed, safe layer. **The model never writes SQL and never does arithmetic.**

---

## 2. Discovery questions

**Business**
- Who'll use it, and how technical are they?
- Write down the 15–20 questions they ask most. These become the QA question bank.
- What are the conversions (purchases, bookings, leads, sign-ups)? Which carry a value?
- What words do people use? ("Revenue" or "booking value"? Does "this year" mean calendar or financial year?)
- When does the financial year start, and is it week-based?

**Data**
- Which sources go in phase 1, and which later?
- How much history do you need, and how far back does each source go?
- Consent: how does unconsented traffic appear in your GA4 export? What counts as consented?
- Test and internal traffic: is any reaching production? (Decide now. See §10.)
- Which attribution models do people need? We used GA4 last non-direct (default), GA4 first touch, and platform-reported.
- Ad account currency and time zone. Is spend inc or ex VAT?
- Which conversion actions in each ad platform map to which business outcome?

**Platform**
- Which GCP project and region (data residency)?
- Who can grant IAM roles, create OAuth clients and set up Cloud Run?
- Which Claude plans will users be on? With Team or Enterprise, an Owner adds the connector once for everyone. With individual plans, each user adds it with the client ID and secret.
- Which email domains are allowed in? Does the organisation use Google Workspace or Microsoft 365?
- Who gets the analyst's "we don't hold that data" requests?

**Red lines** (agree these in writing)
- Reporting tables only? Default window? Row cap? Cost cap per query?
- No personal data in answers.
- What happens when the analyst can't answer?

**✏️ Your call:** add your own.

---

## 3. Phases and gates

| Phase | What | Gate |
|---|---|---|
| 0: Foundations | GCP project, datasets (`mdw_staging`, `mdw_core`, `mdw_reporting`, `mdw_assertions`, each with a `_dev` twin), service accounts, Dataform repo linked to GitHub, CI, conventions doc, data transfers on | CI compiles; dev run green |
| 1: Core build | GA4 + Google Ads: staging → core → reporting, assertions, metrics register. **Build on a 3-day sample** | **A:** sample built and checked |
| | Load history once (backfill mode) | **B:** warehouse reconciles to the platform UIs by month |
| | Event-driven daily run + alerts | **C:** two clean automatic runs in a row, all assertions clean, freshness 0 days behind |
| MCP | Tools, auth, usage log, deploy, connect to Claude, QA | **M:** question bank matches hand-written SQL; red-line tests pass |
| 2+ | Meta Ads, other platforms, dashboards | Same gates per source |

**✏️ Your call:** phases, gates, dates.

---

## 4. Dataform setup

### 4.1 Repo layout

```
definitions/
  staging/      stg_ga4__events, stg_ga4__event_items, int_ga4__sessions_aggregated,
                stg_google_ads__*, stg_meta_ads__* …
  core/         fct_web_events, fct_web_sessions, fct_web_users, fct_<conversion>s,
                fct_<platform>_campaign_stats, dim_date, dim_traffic_sources,
                dim_<platform>_campaigns
  reporting/    rpt_<subject>_daily …, metrics_register, rpt_data_freshness
  assertions/
includes/
  fields.js     column dictionary: add(), metric(), describe(), columnsFor(table)
  metrics.js    metric register entries + plain-English map + registerSql()
  attribution.js  MODELS, OUTCOMES, SUPPORTED
  channels.js   channel rules (first match wins)
  ads.js        ad platforms + conversion-action map + union helper
  ga4.js        getParam(), event map
  window.js     build-mode date windows, isProtected()
  nulls.js      sentinel helpers
  dates.js, fiscal.js, holidays.js, constants.js
ci/check_fields.js   fails the build on convention breaks
docs/           runbook.md, conventions.md, sources.md, build-safety.md, qa/
ops/            the Cloud Workflow YAML (source of record)
```

### 4.2 Conventions

- **Prefixes:** `ga4_` for GA4 conversion metrics, `web_` for session and page metrics, `ad_` for ad platform metrics. Plural fact and dim names. `_daily` only on reporting tables.
- **One name, one definition:** every core and reporting column lives once in `includes/fields.js`, along with the tables it appears in. Configs use `fields.describe([...])` / `fields.columnsFor("<table>")`.
- **CI (`ci/check_fields.js` on the compiled JSON) fails a PR if:** a column isn't in `fields.js`, a reporting table has a struct, an incremental model hard-codes a date, or an attributed metric breaks the naming rule. Run it in default, `--schema-suffix dev` and `--vars=build_mode=incremental` modes.
- **No stored ratios in reporting tables.** Store the additive parts. Ratios live in `metrics.js` and are computed by the MCP.
- **No NULLs** in fct/dim/rpt. Use sentinels in a fixed precedence order: `_unconsented` → `_na` → `_unknown`. Keep source values like `(not set)` as they are. Metrics are 0 when nothing happened. IDs are STRING.
  - Exception: ad metrics are NULL (not 0) on channels with no connected ad platform, so missing spend never shows as £0.
- **Consent:** mixed tables carry `analytics_consented` (`granted` / `denied` / `_unknown`). Sessions and users are consented-only. Rates use consented rows. No personal data in `mdw_reporting`.
- **Attribution naming:** every attributed number names its model exactly once.
  - Multi-model tables → on the metric: `attribution_<model>_<metric>` (`attribution_first_bookings`).
  - Single-model tables → on the dimensions (`attribution_last_non_direct_channel`), with plain metric names.
  - Spend, impressions and clicks are never attributed. Cost per conversion and ROAS only count conversions on rows that have spend.
- **Facts** keep IDs and source values in structs (`attribution_last_non_direct`, `device`, `geo`, `page` …). **Reporting** is flat: `<struct>_<field>`.
- **Daily reporting tables** are `table` (full rebuild every run), partitioned on `report_date`, with a small date block (calendar month, ISO week, fiscal month and week labels).
- **Tags:** everything production runs gets `daily`, plus a source tag (`ga4`, `google_ads`, `meta_ads`).

### 4.3 Build modes and incremental models

- Variables: `build_mode` = `sample` | `incremental` | `backfill`. `backfill` also needs a `backfill_confirm` variable set, as a safety catch.
- Lookbacks as variables: `ga4_lookback_days` (we used 3), `ads_lookback_days` (30), `meta_lookback_days` (7+).
- Incremental models: `pre_operations` DELETE over `window.startDate(incremental(), "<lookback var>")`. Date filters only come through `window.*`. `protected: window.isProtected()` (full refresh refused outside backfill).
- Dataform 3.0.x: `partitionBy`, `clusterBy` and `requirePartitionFilter` are **top-level config keys**, not inside `bigqueryOptions`. JS assertions look like `assert(name).tags([...]).description(...).query(ctx => ...)`.
- `table` models (dims, reporting, register) rebuild fully every run, so changes to channel rules and definitions restate history automatically.

### 4.4 The metrics register

Each entry in `includes/metrics.js` has a name, formula, inputs, unit, additivity, technical definition, population, synonyms **and a plain-English business definition**. Per-model rates (conversion rate, average value, cost per conversion, ROAS) are generated from `attribution.js`. Dataform builds `metrics_register` from it. If the MCP returns a metric, it must be registered here.

### 4.5 Assertions worth having

- Reconciliation: reporting = core = raw, by day, for GA4 and each ad platform (spend especially).
- Parsing: fail on unknown values (new product names, categories, units), so you hear about them.
- Non-production hostnames: fail if test or staging traffic appears.
- Freshness: each source within N days.

**✏️ Your call:** your prefixes, sentinels, models and conversion map.

---

## 5. Sources

**GA4 export**
- Use only `events_YYYYMMDD` (8-digit suffixes). Exclude intraday.
- Landing times vary widely and are sometimes a day late, hence the event-driven trigger.

**Google Ads (BigQuery Data Transfer Service)**
- `p_ads_*_<customer_id>` tables are **ingestion-time partitioned** (`_PARTITIONTIME`). `_DATA_DATE` doesn't exist on them.
- Useful tables: `Campaign`, `CampaignBasicStats`, `CampaignCrossDeviceStats` (all conversions, impression share), `CampaignConversionStats` (by action, **primary actions only**). Don't combine `CampaignStats` with these, or it double-counts.
- Set the transfer refresh window to 30 days so late conversions get re-read.
- Map conversion action IDs to business outcomes in `includes/ads.js`.

**Meta Ads (BigQuery Data Transfer Service)**
- Tables: `AdInsights`, `AdInsightsActions`, `Campaigns`, `AdAccounts`.
- **Conversions are dated by conversion date** (Google Ads by click date), and that isn't configurable. Say so in caveats.
- Pick one attribution window and use it everywhere (we used 7-day click + 1-day view).
- Count only `offsite_conversion.fb_pixel_*` action types for pixel conversions.
- `ad_clicks` = link clicks.
- Leave out reach and frequency. They aren't additive.
- **The token expires after ~60 days.** Re-authorise on a calendar reminder.
- "Authorised ad accounts only" means the ad account must be listed on the Meta app.

**Every new source dataset:** grant the Dataform runner service account **BigQuery Data Viewer** on it *before* the first run.

---

## 6. Orchestration

1. **Log sink** on the GA4 `events_` table-created event → **Pub/Sub** topic.
2. **Eventarc** trigger → **Cloud Workflow** (`ops/mdw-daily-run.yaml`):
   - wait 10 minutes
   - list workflow invocations and count `RUNNING` yourself (the API rejects a `state` filter); skip if one is running
   - compile the `production` release config **fresh from `main`**
   - invoke tag `daily`, no full refresh, as the runner service account
3. The workflow's service account needs **Service Account User** on the runner service account.
4. **Cloud Monitoring alerts → Slack**: "table landed, run starting" and "Dataform run failed". **Alert on workflow failures too**, because a workflow failure never reaches Dataform.
5. The repo YAML is the source of record. If you edit the live workflow in the Console, update both.

**Result:** anything merged to `main` is live on the next automatic run.

**Checking a run without the Console:** check `__TABLES__.last_modified_time` on core and reporting, and `INFORMATION_SCHEMA.JOBS_BY_PROJECT` filtered to the runner's email. Then every assertion view should return 0 rows.

---

## 7. The MCP server

### 7.1 Layout (`src/<package>/`)

| File | What's in it |
|---|---|
| `config.py` | Name, tool description prefix, table allowlist, granularity columns, period vocabulary, attribution models (mirrors `attribution.js`), escalation contact, caps (`ROW_CAP` 1000, `DEFAULT_LIMIT` 25, `MAX_LIMIT` 200), data start date, env vars |
| `tools.py` | A `Spec` per data tool: base metrics `{name: (SQL, core)}`, `rates` (`Rate(num, den, kind, places, core)`), breakdowns, filters, sorts, lag, fixed `where`, model. The engine: `build_sql` / `run_tool` (one query, `UNNEST` result sets, comparison window, rank and trim). `describe_available_data`, `get_metric_definitions` |
| `helpdesk.py` | `request_help`: known gaps, redirects to other tools, partial answers, drafted data request |
| `server.py` | Server instructions, a `guarded` wrapper (logging, session ID, error shapes), tool signatures and **docstrings** |
| `periods.py` | Time words → dates, fiscal weeks, comparison periods |
| `bq.py` | Dry run → size cap → run with `maximum_bytes_billed`; cached partition list |
| `caveats.py` | Short caveat codes + full wording |
| `auth.py` | Google token check + domain allowlist |
| `audit.py` | One usage-log row per call |
| `shape.py` | `safe_divide`, `pct_change` |

Tests with BigQuery stubbed (pytest), run in GitHub Actions. Dockerfile + `cloudbuild.yaml`. Cloud Run continuous deployment from `main`.

### 7.2 Design rules

- **Read `mdw_reporting` only.** The MCP service account gets BigQuery Job User (project), Data Viewer on `mdw_reporting`, and Data Editor on the log dataset. Nothing else.
- **No free-text SQL.** Caller text only reaches SQL as a bound parameter, or through a fixed mapping chosen by a validated key. Column names only come from the `Spec`.
- **The model never divides.** Rates are computed after the query. Every rate and change is a fraction: `_chg_pct` for counts and values, `_diff` for rates.
- **One query per call.** Totals, every breakdown, the comparison window, ranking and trimming all go in one statement. (Our v1 took 8 calls at 10–75 MB each for a funnel question; v2 took 1 call, ~14 MB, under a second.)
- **Comparisons in SQL**, in the same call, never left to the model.
- **Cost:** dry run, refuse over ~200 MB, `maximum_bytes_billed` as a backstop. BigQuery bills a 10 MB minimum per query. With one query per call, ours runs at under 25p per 1,000 calls.
- **Defaults stated:** last 7 days by default, with `date_defaulted: true`, anchored to the latest date actually in the table rather than today (when the export lands late, anchoring to today returns empty days that look like broken tracking). Every answer states the period, population and model.
- **Know which tier each guardrail sits in.** Infrastructure (read-only service account, byte cap) can't be talked out of. Server code (dry run, size refusal, row cap, defaults) runs every time. The prompt is advisory and will eventually be ignored by some model, so never rely on it alone.
- **Expose breakdowns, not just filters.** If a dimension like device is only a filter, the model has to loop one call per value, and the cheap answer becomes the blended total, which can hide a big gap between segments.
- **Caveats only where they apply.** A caveat on every answer is a caveat nobody reads.
- **Breakdowns must be additive or carry a caveat.**
- **No personal data in responses.**

### 7.3 Tools

| Tool | Purpose |
|---|---|
| `describe_available_data` | Subjects, metrics, breakdowns, filters, coverage, freshness, caveat wording, time words, what it can't answer. Once per conversation |
| `get_channel_performance` | Conversions by channel with `attribution_model` = `last_non_direct` (default) / `first` / `ad_platform` / `compare` |
| `get_web_traffic_performance` | Consented sessions, engagement and landing pages by source/medium, device and so on |
| `get_<funnel>` | Your conversion funnel steps and step rates |
| `get_ad_campaign_performance` | Spend, impressions, clicks, CTR, CPC, platform conversions, ROAS and cost per conversion, by platform and campaign |
| `get_cookie_consent_rates` | Consent rates with the counts behind them |
| `get_metric_definitions` | Plain English by default; `detail="technical"` for formulas |
| `request_help` | The "can't answer" path |

**Common parameters:** `period` (fixed vocabulary: `last_7_days`, `yesterday`, `last_complete_month`, `this_fy_to_date`, `custom` …), `date_from`/`date_to`, `compare_to` (`previous_period`, `last_year`, `custom` + dates), `granularity`, `breakdown_by` (list, up to 4), `metrics`, filters (one value or a list, case-insensitive), `sort_by`, `limit`.

**Response:** `period_used`, `date_defaulted`, `comparison_period`, `totals` (+ comparison and change), `series`, `breakdowns` (with share-of columns and "Top N of M"), `caveats`, `notes`, `data_freshness`, `truncated`.

**Notes that help the model:** partial periods, small bases (< ~100 events), ad conversions still maturing (< 30 days old), empty filters (return the valid values), custom comparisons of different lengths. We used these instead of anomaly flags, which made the model over-claim.

### 7.4 `request_help`

Keyword routing, no query:
1. **Redirect**, with the exact call, when another tool can answer.
2. **Name the specific gap**, not the whole list.
3. **Partial answer:** what you can still say, and the calls that get it.
4. **Drafted data request** to a named contact: subject, question, why it matters, data needed. No drafts for personal-data questions.

Every question gets logged. That's your backlog.

### 7.5 Sign-in: an email-domain allowlist, not an access system

Keep it simple. Google sign-in through Claude's connector only confirms who the person is. It isn't used to grant access to anything.
- The server checks the token was issued to **your** client ID, that the email is verified, and that its domain is on the allowlist (or the exact address is on an extras list). Cache verified tokens for 60 seconds, hashed.
- No user tokens to store or refresh, no per-user BigQuery permissions, no roles. The server queries BigQuery with its own service account. Adding a domain is one environment variable.
- **The client secret lives only in Claude's connector settings.** Never put it on the server or in the repo. Keep any user setup guide that contains it out of git.
- Microsoft 365 organisations: each user needs a Google account created on their work email.
- An unverified OAuth brand doesn't block basic scopes.
- Env vars: public URL, OAuth client ID, allowed domains and emails, dataset, log table, max bytes billed.

### 7.6 Usage log (tool calls, not prompts)

**Don't log users' prompts.** The conversation stays in Claude. Log the tool call and, for `request_help`, a short description of what the person was trying to find out. That's enough context to see what's used, what's missing and what to build next.

A `mcp_logs.tool_calls` table, partitioned by date with ~400-day expiry, kept separate from the `mdw_*` datasets. Columns: call ID, called at, caller email and domain, session ID (Claude's connector sends no MCP session header, so use `tok-` + a hash of the token), tool, params, resolved period, `date_defaulted`, outcome (`ok` / `out_of_scope` / `redirected` / `invalid_parameter` / `query_too_large` / `server_error`), error, rows, truncated, bytes estimated and billed, cache hit, duration, help question, server version. Add a `v_usage_daily` view.

### 7.7 Give it a name

- A short name helps adoption, and it's a bit of fun. The blog post uses "Flippy" as its example ("ask Flippy").
- Put the name in the server instructions and at the start of every tool description. Encourage users to start their questions with it ("Flippy, how did paid social do last month?"). Claude then knows to use this connector's tools straight away, rather than working out whether the question is for this MCP, the BigQuery MCP or a web search. That means fewer wasted calls.
- Make it a name, not a persona. No character or voice, and figures are attributed to the data.
- Give it an avatar: a simple flat logo (ours are an object with a face in a circle). Send it as the MCP server icon and serve it at a public path such as `/<name>.png`. Claude didn't display server icons for custom connectors when we tested, so its real uses are elsewhere: the setup guide and README, launch posts, rollout slides, and artifacts Claude builds from the analyst's data (a small "Data from <name>" badge shows where the figures came from).
- **✏️ Your call:** the name and the avatar.

### 7.8 Who it's for, and the analyst setup

- **Marketers:** this MCP is the next step on from self-serve reporting. They ask in plain English and get answers with context attached.
- **Analysts:** this MCP **plus the BigQuery MCP**. Give analysts a Claude skill that points the BigQuery MCP at the core `fct_` / `dim_` tables, explains your conventions (naming, consent, attribution, sentinels), and keeps it away from raw exports and staging unless needed.

### 7.9 Keep it specialised

- One MCP per domain or audience (marketing, finance, product…), not one do-everything analyst. Every tool description sits in Claude's context on every question, so extra domains cost tokens and make it easier to pick the wrong tool.
- Shared words mean different things across teams ("revenue", "conversion"). Separate MCPs keep each one unambiguous, with its own access rules, caveats and escalation contact.
- Split by audience, not by table, so users aren't juggling lots of connectors.
- **Specialised on top, shared underneath:** every MCP reads the same warehouse and metrics register, so two analysts never give two answers to the same question.

### 7.10 Monitoring

If you run more than one analyst MCP, log them all in the same shape. Then build one monitoring dashboard (we used a Claude dashboard artifact) showing usage over time, tools called, cost per call, failures, and every `request_help` question. That last list is your roadmap.

### 7.11 Shipping

- A push to `main` deploys. Risky changes (large embedded files, anything that could stop the server starting) go via a PR and wait for green tests.
- After renaming a tool or changing its parameters, users must **reconnect the connector**. Test in a fresh chat.
- To change the connector name or auth settings, remove the connector and re-add it.
- Confirm a deploy via `describe_available_data` and `server_version` in the log.

**✏️ Your call:** tools, analyst name, caps, domains, escalation contact.

---

## 8. QA

**Warehouse**
- Reconciliation assertions clean.
- Ad spend by month vs the platform UI, within a tolerance you agree up front. (We accepted 0.01%, explained by later platform adjustments.)
- Two clean automatic runs before calling it live.

**MCP (Gate M)**
- Question bank: each question vs a hand-written query. Numbers match, period stated, caveats present.
- No period given → default used and stated. "This year" → your agreed definition.
- Oversized query → refused or truncated, with a suggestion.
- Data not held → `request_help`, no invented number. Answerable question sent to `request_help` → redirected.
- Non-allowed email → rejected.
- One log row per call, with the correct email, outcome and bytes.
- A typical question takes 1–2 calls, each under ~20 MB.
- **Test as a user in a fresh Claude chat.** Our biggest redesign came from one afternoon of this.

---

## 9. Working with Claude on the build

- **Runbook** (`WAREHOUSE_MCP_RUNBOOK.md` or similar), read first for any change. It covers where everything lives, current sources, models and tools, conventions, build/check/ship steps, deliberate operations, which docs to update, and open items. Update it in the same session.
- **Decisions log:** one line per decision, newest first, with who decided and where the detail lives.
- **Dev before prod:** keep `dev` level with `main`, push model changes to `dev`, run them, check the `_dev` datasets and assertions, then open a PR to `main`.
- **Validate SQL against BigQuery** (dry runs, totals vs hand-written queries) before pushing.
- **If Claude pushes via the GitHub API** (whole-file contents, no git): keep a manifest of changed files, push dependent files in one commit, and verify every blob SHA against `git hash-object`.

---

## 10. Lessons learned

**Dataform and orchestration**
1. `workflowInvocations.list` rejects `filter: "state = RUNNING"` (400). List them and count yourself.
2. The workflow's service account needs **Service Account User** on the runner service account (403 otherwise).
3. Grant the runner **Data Viewer** on every new source dataset before its first run.
4. **Saving release-config variables doesn't recompile.** Make a new compilation before any manual run. Our first backfill ran in sample mode because of this.
5. **Never leave production in backfill mode.** After a reload: set the mode back, delete the confirmation variable, save, recompile.
6. Workflow failures don't trigger Dataform alerts. Alert on the workflow too, and check its executions first.
7. Never start a manual production run while the automatic one is running.
8. When a source is very late, temporarily raise the lookback, run, then set it back.

**BigQuery and models**
9. BigQuery won't replace a table whose partitioning or clustering changed. Drop it first.
10. Dataform never drops deleted models. Drop the tables yourself in prod and dev.
11. Incremental tables don't pick up new or renamed columns, and protected tables refuse full refresh. Either reload deliberately, or rename in place with `CREATE OR REPLACE TABLE … PARTITION BY … CLUSTER BY … AS SELECT …` and check counts and totals.
12. Stale dev tables throw "Name … not found". Full-refresh those tags in dev.
13. In JavaScript, `String.replace` with `$'`-like text in the replacement corrupts SQL. Pass a function instead.
14. Sort out test and internal traffic early: hostnames, `debug_mode`, internal traffic rules, test user IDs and transactions. Use an `is_test_or_internal` flag plus an assertion.
15. Not every anomaly is a pipeline fault. Use reconciliation assertions to rule the warehouse in or out fast, and have a named contact on the site/back-end side.

**Sources**
16. GA4: 8-digit tables only. Landing time varies and can be a day late.
17. Google Ads DTS: `_PARTITIONTIME`, not `_DATA_DATE`. Conversion stats hold primary actions only. Don't mix in `CampaignStats`. Use a 30-day refresh window.
18. Meta DTS: conversion-date attribution, a 60-day token, "authorised accounts only", and a refresh window of 7 days or more.
19. Expect tiny UI vs warehouse gaps from later platform adjustments. Agree the tolerance and record it.

**MCP and Claude**
20. **Tool docstrings are the model's only guide.** Rewrite them before you build features.
21. Claude caches tool lists. Reconnect after renames, and test in a fresh chat.
22. Connector name and auth can't be edited. Remove it and re-add.
23. No MCP session header from Claude's connector. Hash the token for log sessions.
24. Server icons aren't shown for custom connectors (when we tested). Send the avatar anyway, but don't spend time debugging it in Claude.
25. A short name helps adoption. A persona isn't worth it.
26. A cloud sandbox may not reach your Cloud Run URL. Verify through the connector and the log's `server_version`.
27. Individual Claude plans mean everyone handles the client ID and secret. Past ~5–10 users, move to a Team/Enterprise org connector or a managed sign-in service.
28. Push every interdependent file together. We broke `main` twice by pushing part of a change.
29. Unit tests that stub BigQuery won't catch illegal SQL. A reserved keyword used as a column alias took out a whole tool while every test passed. Add a suite that dry-runs every query variant against the real warehouse (it costs pennies).
30. On Windows, the console encoding can crash the server on typographic characters in tool descriptions. It shows up as "server disconnected". Force UTF-8 or keep descriptions plain ASCII.
31. Check what the capability summary tells the model. Ours listed filters as "breakdowns", which taught the model to loop one call per value.
32. If users sign in with Google accounts on Microsoft 365 work addresses, the client's IT doesn't control offboarding. Fine for read-only aggregated numbers; revisit before adding revenue or customer data.

**✏️ Your lessons:**

-
-

---

## 11. Starter checklist

- [ ] Discovery questions answered, red lines agreed in writing
- [ ] Question bank written
- [ ] Datasets + `_dev` twins, service accounts, IAM grants
- [ ] Dataform repo, `includes/` (fields, metrics, attribution, channels, ads, window, nulls), CI check
- [ ] Data transfers on, with the right refresh windows
- [ ] Sample build → Gate A
- [ ] History load + monthly reconciliation → Gate B
- [ ] Event-driven workflow + alerts (workflow and Dataform) → Gate C
- [ ] MCP: specs, one-query engine, caps, `request_help`, auth, usage log, tests, Cloud Run deploy
- [ ] Connected in Claude, QA'd in a fresh chat → Gate M
- [ ] Runbook and decisions log current
- [ ] Calendar reminder for the Meta token

---

## 12. Your spin

Ideas we parked or that you might take further:

- Looker Studio on the same reporting tables, so the dashboard and the AI agree.
- More attribution models (linear, position-based, data-driven).
- Search Console, CRM or back-end conversions, finance revenue, budgets and targets.
- TikTok and Microsoft Ads.
- A fuller orchestrator with an ops dataset and a safety-net run.
- Year-on-year once you have the history.

**✏️ Your additions:**

-
-
-
