Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(tools): add traffic-sim for verifying posthog instrumentation (#56745)

Lucas Ricoy381573492316
diff --git a/.mcp.json b/.mcp.json
index f0fa9d1990d1..a1b79e824e39 100644
--- a/.mcp.json
+++ b/.mcp.json
@@ -3,6 +3,10 @@
"phrocs": {
"command": "uv",
"args": ["run", "python", "tools/phrocs/mcp_server.py"]
+ },
+ "traffic-sim": {
+ "command": "uv",
+ "args": ["run", "python", "tools/traffic-sim/mcp_server.py"]
}
}
}
diff --git a/tools/traffic-sim/.gitignore b/tools/traffic-sim/.gitignore
new file mode 100644
index 000000000000..5a5e73f4bb07
--- /dev/null
+++ b/tools/traffic-sim/.gitignore
@@ -0,0 +1,4 @@
+results/
+browserstack.yml
+__pycache__/
+*.pyc
diff --git a/tools/traffic-sim/Makefile b/tools/traffic-sim/Makefile
new file mode 100644
index 000000000000..256f3a194bc2
--- /dev/null
+++ b/tools/traffic-sim/Makefile
@@ -0,0 +1,51 @@
+.PHONY: help new-user returning-user check-loading test test-integration mcp-server clean
+
+PYTHON ?= uv run python
+
+help:
+ @echo "traffic-sim — verify PostHog instrumentation by driving a real browser"
+ @echo ""
+ @echo "Targets:"
+ @echo " make new-user URL=... Run new-user scenario (override VISITS, INTERVAL)"
+ @echo " make returning-user URL=... Run returning-user scenario (override PAGE_VIEWS, INTERVAL)"
+ @echo " make check-loading URL=... Inspect how PostHog loads on URL(s)"
+ @echo " make test Run unit tests (no network)"
+ @echo " make test-integration Run integration test (spawns local fixture page)"
+ @echo " make mcp-server Start the MCP server in stdio mode"
+ @echo " make clean Remove results/ directory"
+ @echo ""
+ @echo "Variables:"
+ @echo " URL=https://example.com Required for the three scenarios"
+ @echo " VISITS=10 Override new-user visit count"
+ @echo " PAGE_VIEWS=5 Override returning-user page-view count"
+ @echo " INTERVAL=60 Override seconds between visits"
+ @echo " POSTHOG_HOST=https://... Override PostHog ingestion host"
+
+VISITS ?= 3
+PAGE_VIEWS ?= 3
+INTERVAL ?= 5
+POSTHOG_HOST ?= https://us.i.posthog.com
+
+new-user:
+ @if [ -z "$(URL)" ]; then echo "URL=... is required"; exit 1; fi
+ $(PYTHON) cli.py new-user --url "$(URL)" --visits $(VISITS) --interval $(INTERVAL) --posthog-host "$(POSTHOG_HOST)"
+
+returning-user:
+ @if [ -z "$(URL)" ]; then echo "URL=... is required"; exit 1; fi
+ $(PYTHON) cli.py returning-user --url "$(URL)" --page-views $(PAGE_VIEWS) --interval $(INTERVAL) --posthog-host "$(POSTHOG_HOST)"
+
+check-loading:
+ @if [ -z "$(URL)" ]; then echo "URL=... is required (or pass --urls-file ...)"; exit 1; fi
+ $(PYTHON) cli.py check-loading --url "$(URL)" --posthog-host "$(POSTHOG_HOST)"
+
+test:
+ $(PYTHON) -m pytest tests/test_cli.py -q
+
+test-integration:
+ $(PYTHON) -m pytest tests/test_integration.py -q
+
+mcp-server:
+ $(PYTHON) mcp_server.py
+
+clean:
+ rm -rf results/
diff --git a/tools/traffic-sim/README.md b/tools/traffic-sim/README.md
new file mode 100644
index 000000000000..f37f66be76c3
--- /dev/null
+++ b/tools/traffic-sim/README.md
@@ -0,0 +1,117 @@
+# traffic-sim
+
+Drive a real browser at a URL and verify that PostHog instrumentation is firing
+correctly. Useful right after `npx @posthog/wizard`, after a deploy that touches
+tracking code, or any time you need an answer to _"is my PostHog instrumentation
+actually working?"_.
+
+Three scenarios:
+
+- **`new-user`** — each visit uses a fresh browser context (no cookies). Matches
+ a stream of unique visitors.
+- **`returning-user`** — all page views share the same context. Matches one
+ visitor browsing several pages in a session.
+- **`check-loading`** — inspects the PostHog snippet across multiple URLs:
+ load method, init config, runtime state. Catches pages where the snippet is
+ missing or pointing at the wrong project.
+
+The same three operations are exposed as MCP tools (see [Use from Claude Code](#use-from-claude-code))
+and as Claude Code skills (see [`skills/`](./skills/)).
+
+## Install
+
+The tool runs from the PostHog monorepo and shares its Python environment.
+First time:
+
+```sh
+uv sync
+uv run playwright install chromium
+```
+
+For `--cloud` (BrowserStack) runs, install the optional extras:
+
+```sh
+uv pip install browserstack-sdk pyyaml
+```
+
+…and either set `BROWSERSTACK_USERNAME` / `BROWSERSTACK_ACCESS_KEY` in your
+shell, or copy `browserstack.yml.example` to `browserstack.yml`.
+
+## Use from the CLI
+
+```sh
+# Confirm the snippet loads on every URL you care about
+uv run python tools/traffic-sim/cli.py check-loading \
+ --url https://example.com/ \
+ --url https://example.com/pricing \
+ --url https://example.com/blog
+
+# Send 3 fresh-browser visits, 5s apart
+uv run python tools/traffic-sim/cli.py new-user \
+ --url https://example.com/ --visits 3 --interval 5
+
+# Send 5 page views from a single returning user
+uv run python tools/traffic-sim/cli.py returning-user \
+ --url https://example.com/ --page-views 5 --interval 5
+```
+
+Or via the Makefile (from inside `tools/traffic-sim/`):
+
+```sh
+make check-loading URL=https://example.com/
+make new-user URL=https://example.com/ VISITS=3 INTERVAL=5
+make returning-user URL=https://example.com/ PAGE_VIEWS=5 INTERVAL=5
+```
+
+### Common options
+
+- `--posthog-host https://eu.i.posthog.com` — for the EU cloud.
+- `--posthog-host https://ph.example.com` — for self-hosted reverse proxies.
+- `--urls-file urls.json` — load a list of URLs from a JSON file
+ (flat list or `{base_url, categories}` shape; see [`urls.example.json`](./urls.example.json)).
+- `--headed` — show the browser window. Useful for live-debugging.
+- `--verbose` — print every PostHog request and console line.
+- `--cloud` — run on BrowserStack instead of locally (requires the cloud extras).
+
+## Use from Claude Code
+
+The MCP server is registered in the monorepo's `.mcp.json` and exposes three
+tools:
+
+| Tool | Purpose |
+| ------------------------- | ------------------------------------------------------------------ |
+| `simulate_new_user` | Send N fresh-browser visits and report which PostHog events fired. |
+| `simulate_returning_user` | Send N page views in one session and report events. |
+| `check_posthog_loading` | Inspect how PostHog is loaded across one or more URLs. |
+
+Each tool returns a structured summary including `verified: true|false`,
+event counts, and any errors. See [`skills/`](./skills/) for orchestration
+patterns including the headline `verify-posthog-instrumentation` skill.
+
+## Output
+
+Run reports are saved as JSON under `results/` in this directory. The
+filename embeds the scenario, run id, and timestamp, e.g.
+`results/check-loading_a1b2c3d4_20260428_143000.json`.
+
+## What this tool does NOT do
+
+- Send your own events to PostHog. The tool _observes_ what the customer's
+ PostHog snippet emits — it does not inject any test traffic into your
+ PostHog project beyond what your site naturally fires.
+- Validate session recordings. We report whether session recording is
+ enabled in the init config, but we don't watch the recording itself.
+- Drive custom user flows (e.g. signup). Add per-flow scripts on top.
+
+## Layout
+
+```text
+tools/traffic-sim/
+├── cli.py Three subcommands: new-user, returning-user, check-loading.
+├── mcp_server.py FastMCP server exposing the same operations as MCP tools.
+├── console-snippet.js Paste-into-DevTools helper for one-off manual inspection.
+├── browserstack.yml.example Template for --cloud credentials.
+├── urls.example.json Example URL list for --urls-file.
+├── skills/ Claude Code skills wrapping the MCP tools.
+└── tests/ Unit tests + a Playwright integration smoke test.
+```
diff --git a/tools/traffic-sim/browserstack.yml.example b/tools/traffic-sim/browserstack.yml.example
new file mode 100644
index 000000000000..56c5f2b6a0ae
--- /dev/null
+++ b/tools/traffic-sim/browserstack.yml.example
@@ -0,0 +1,6 @@
+# BrowserStack credentials for `traffic-sim --cloud`.
+# Copy to browserstack.yml and fill in real values, OR set BROWSERSTACK_USERNAME
+# and BROWSERSTACK_ACCESS_KEY in your shell environment.
+# Get credentials from https://www.browserstack.com/accounts/settings.
+userName: YOUR_BROWSERSTACK_USERNAME
+accessKey: YOUR_BROWSERSTACK_ACCESS_KEY
diff --git a/tools/traffic-sim/cli.py b/tools/traffic-sim/cli.py
new file mode 100644
index 000000000000..7d7ecd3beac1
--- /dev/null
+++ b/tools/traffic-sim/cli.py
@@ -0,0 +1,818 @@
+#!/usr/bin/env python3
+# ruff: noqa: T201
+"""Drive a real browser at a URL and verify PostHog instrumentation.
+
+Three scenarios:
+ new-user Each visit uses a fresh browser context (no cookies).
+ returning-user All page views share the same context (cookies persist).
+ check-loading Inspect how the PostHog snippet is loaded across pages.
+
+Optional cloud runner (`--cloud`) uses BrowserStack and reports the
+verification result back to the BrowserStack session. Requires the
+browserstack-sdk dependency to be installed.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import sys
+import json
+import time
+import uuid
+import random
+import asyncio
+import argparse
+import urllib.parse
+from collections import Counter
+from dataclasses import asdict, dataclass, field
+from datetime import UTC, datetime
+from pathlib import Path
+from urllib.parse import parse_qs, urlencode, urlparse, urlunparse
+
+from playwright.async_api import Browser, BrowserContext, Page, async_playwright
+
+DEFAULT_TIMEOUT_MS = 120_000
+DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com"
+DEFAULT_POSTHOG_DOMAINS = ("posthog.com", "i.posthog.com")
+
+USER_AGENT = (
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
+ "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
+)
+
+RESULTS_DIR = Path(__file__).parent / "results"
+
+
+# Detects PostHog presence and configuration on a page. Returns a dict shaped
+# like {loaded, load_method, init_config, runtime_state, ...}.
+POSTHOG_DETECT_JS = r"""
+() => {
+ const scripts = [...document.querySelectorAll('script')];
+ const posthogScripts = scripts.filter(s => {
+ const src = (s.src || '').toLowerCase();
+ const id = (s.id || '').toLowerCase();
+ const text = (s.textContent || '').toLowerCase();
+ return src.includes('posthog') || src.includes('array.js') ||
+ id.includes('posthog') || text.includes('posthog') ||
+ text.includes('phc_') || text.includes('ph_init');
+ });
+ const hasPosthogInitId = !!document.getElementById('posthog-init');
+ const snippetPattern = /!function\s*\([a-z],[a-z]\)\s*\{[^}]*__SV/;
+ let hasWebSnippet = false;
+ let snippetLocation = null;
+ for (const s of posthogScripts) {
+ if (snippetPattern.test(s.textContent || '')) {
+ hasWebSnippet = true;
+ snippetLocation = s.parentElement ? s.parentElement.tagName.toLowerCase() : null;
+ break;
+ }
+ }
+ let initConfig = null;
+ for (const s of posthogScripts) {
+ const text = s.textContent || '';
+ const m = text.match(/posthog\.init\s*\(\s*['"]([^'"]+)['"]\s*,\s*(\{[\s\S]*?\})\s*\)/);
+ if (m) {
+ try {
+ const raw = m[2].replace(/(\w+)\s*:/g, '"$1":').replace(/'/g, '"').replace(/,\s*}/g, '}');
+ const p = JSON.parse(raw);
+ initConfig = {
+ api_key: m[1],
+ api_host: p.api_host || null,
+ person_profiles: p.person_profiles || null,
+ };
+ } catch (e) {
+ initConfig = {api_key: m[1]};
+ }
+ break;
+ }
+ }
+ if (!initConfig && window.posthog && window.posthog.config) {
+ const c = window.posthog.config;
+ initConfig = {
+ api_key: c.token || null,
+ api_host: c.api_host || null,
+ person_profiles: c.person_profiles || null,
+ };
+ }
+ const arrScript = posthogScripts.find(s => s.src && s.src.includes('array'));
+ const defined = typeof window.posthog !== 'undefined';
+ const runtimeState = defined && window.posthog
+ ? {
+ defined: true,
+ loaded: !!window.posthog.__loaded,
+ distinct_id: window.posthog.get_distinct_id ? window.posthog.get_distinct_id() : null,
+ config_api_host: window.posthog.config ? window.posthog.config.api_host : null,
+ }
+ : {defined: false, loaded: false};
+ let loadMethod = 'none';
+ if (runtimeState.loaded && hasPosthogInitId) loadMethod = 'head_snippet';
+ else if (runtimeState.loaded && hasWebSnippet) loadMethod = 'snippet';
+ else if (runtimeState.loaded && arrScript) loadMethod = 'array_js_only';
+ else if (runtimeState.loaded) loadMethod = 'unknown';
+ return {
+ loaded: runtimeState.loaded,
+ load_method: loadMethod,
+ has_posthog_init_id: hasPosthogInitId,
+ has_web_snippet: hasWebSnippet,
+ snippet_location: snippetLocation,
+ array_js_src: arrScript ? arrScript.src : null,
+ script_tag_count: posthogScripts.length,
+ init_config: initConfig,
+ runtime_state: runtimeState,
+ };
+}
+"""
+
+
+@dataclass
+class AnalyticsRequest:
+ timestamp: str
+ url: str
+ method: str
+ status: int | None = None
+ events: list[str] = field(default_factory=list)
+
+
+@dataclass
+class ConsoleLine:
+ timestamp: str
+ type: str
+ text: str
+ is_posthog: bool = False
+
+
+@dataclass
+class VisitResult:
+ visit_number: int
+ scenario: str
+ url: str
+ timestamp: str
+ page_load_ms: float | None = None
+ posthog_requests: list[AnalyticsRequest] = field(default_factory=list)
+ console_lines: list[ConsoleLine] = field(default_factory=list)
+ error: str | None = None
+
+
+class AnalyticsCapture:
+ """Captures PostHog network requests and console output from a page."""
+
+ def __init__(self, posthog_domains: tuple[str, ...], verbose: bool = False):
+ self.posthog_domains = posthog_domains
+ self.verbose = verbose
+ self.posthog_requests: list[AnalyticsRequest] = []
+ self.console_lines: list[ConsoleLine] = []
+ # Keyed by id(request) so concurrent in-flight requests to the same
+ # URL (e.g. successive /batch/ flushes) don't overwrite each other.
+ self._pending: dict[int, AnalyticsRequest] = {}
+
+ def attach(self, page: Page) -> None:
+ page.on("request", self._on_request)
+ page.on("response", self._on_response)
+ page.on("console", self._on_console)
+
+ def _is_posthog(self, url: str) -> bool:
+ # Match on parsed hostname rather than substring so URLs that merely
+ # contain a PostHog domain in their path (e.g. an open-redirect) are
+ # not misclassified as PostHog ingestion traffic.
+ try:
+ host = (urlparse(url).hostname or "").lower()
+ except ValueError:
+ return False
+ return any(host == d or host.endswith("." + d) for d in self.posthog_domains)
+
+ def _on_request(self, request) -> None:
+ if not self._is_posthog(request.url):
+ return
+ req = AnalyticsRequest(
+ timestamp=datetime.now(UTC).isoformat(),
+ url=request.url,
+ method=request.method,
+ )
+ if request.post_data:
+ try:
+ data = json.loads(request.post_data)
+ if isinstance(data, dict) and "batch" in data:
+ req.events = [e.get("event", "unknown") for e in data["batch"]]
+ elif isinstance(data, dict) and "event" in data:
+ req.events = [data["event"]]
+ except (json.JSONDecodeError, TypeError):
+ pass
+ self._pending[id(request)] = req
+ if self.verbose:
+ tags = ", ".join(req.events) or "unknown"
+ print(f" [PostHog] {request.method} {_short_url(request.url)} events=[{tags}]")
+
+ def _on_response(self, response) -> None:
+ if not self._is_posthog(response.url):
+ return
+ req = self._pending.pop(id(response.request), None)
+ if req is None:
+ return
+ req.status = response.status
+ self.posthog_requests.append(req)
+ if self.verbose:
+ marker = "✓" if response.status in (200, 204) else "✗"
+ print(f" [PostHog] {marker} {response.status} {_short_url(response.url)}")
+
+ def _on_console(self, msg) -> None:
+ text = msg.text
+ is_posthog = "posthog" in text.lower() or "[PostHog]" in text
+ line = ConsoleLine(
+ timestamp=datetime.now(UTC).isoformat(),
+ type=msg.type,
+ text=text,
+ is_posthog=is_posthog,
+ )
+ self.console_lines.append(line)
+ if self.verbose and is_posthog:
+ print(f" [Console] {text[:100]}{'…' if len(text) > 100 else ''}")
+
+
+def _short_url(url: str, max_len: int = 60) -> str:
+ return url if len(url) <= max_len else url[: max_len - 1] + "…"
+
+
+def _redact_api_key(value: str | None) -> str:
+ # PostHog project tokens are public by design, but CodeQL flags raw-token
+ # logging via `py/clear-text-logging-sensitive-data`. Render a fixed
+ # placeholder instead so log output reflects only whether a token is set.
+ return "set" if value else "none"
+
+
+def extract_posthog_events_from_console(lines: list[ConsoleLine]) -> list[str]:
+ pattern = re.compile(r'\[PostHog\.js\] send "(\$?\w+)"')
+ return [m.group(1) for line in lines if line.is_posthog for m in pattern.finditer(line.text)]
+
+
+def add_tracking_params(url: str, run_id: str, scenario: str) -> str:
+ parsed = urlparse(url)
+ params = parse_qs(parsed.query)
+ params["__posthog_debug"] = ["true"]
+ params["run_id"] = [run_id]
+ params["scenario"] = [scenario]
+ return urlunparse(parsed._replace(query=urlencode(params, doseq=True)))
+
+
+async def simulate_user_behavior(page: Page) -> None:
+ await asyncio.sleep(random.uniform(1.0, 2.0))
+ for _ in range(random.randint(2, 4)):
+ await page.evaluate(f"window.scrollBy(0, {random.randint(100, 400)})")
+ await asyncio.sleep(random.uniform(0.3, 0.8))
+ await asyncio.sleep(random.uniform(1.0, 3.0))
+
+
+# ---- BrowserStack (optional --cloud) ------------------------------------------
+
+
+def _load_browserstack_yaml() -> tuple[str | None, str | None]:
+ # Falls back to browserstack.yml next to this file (matches the shipped
+ # browserstack.yml.example). Env vars take precedence; YAML is the
+ # documented file-based path. Parsed manually to avoid a PyYAML dep.
+ yml_path = Path(__file__).parent / "browserstack.yml"
+ if not yml_path.exists():
+ return None, None
+ username: str | None = None
+ access_key: str | None = None
+ try:
+ for raw in yml_path.read_text().splitlines():
+ line = raw.split("#", 1)[0].strip()
+ if not line or ":" not in line:
+ continue
+ key, _, value = line.partition(":")
+ value = value.strip().strip('"').strip("'")
+ if key.strip() == "userName":
+ username = value or None
+ elif key.strip() == "accessKey":
+ access_key = value or None
+ except OSError:
+ return None, None
+ return username, access_key
+
+
+def _build_browserstack_cdp_url() -> str:
+ username = os.environ.get("BROWSERSTACK_USERNAME")
+ access_key = os.environ.get("BROWSERSTACK_ACCESS_KEY")
+ if not username or not access_key:
+ yml_user, yml_key = _load_browserstack_yaml()
+ username = username or yml_user
+ access_key = access_key or yml_key
+ if not username or not access_key:
+ raise RuntimeError(
+ "--cloud requires BROWSERSTACK_USERNAME and BROWSERSTACK_ACCESS_KEY env vars, "
+ "or a browserstack.yml file with userName/accessKey next to cli.py"
+ )
+ try:
+ import playwright # type: ignore[import-untyped]
+
+ pw_version = getattr(playwright, "__version__", "1.54.0")
+ except Exception:
+ pw_version = "1.54.0"
+ caps = {
+ "browser": "chrome",
+ "browser_version": "latest",
+ "os": "Windows",
+ "os_version": "11",
+ "name": "PostHog instrumentation check",
+ "build": f"traffic-sim-{datetime.now().strftime('%Y%m%d-%H%M')}",
+ "browserstack.username": username,
+ "browserstack.accessKey": access_key,
+ "browserstack.playwrightVersion": pw_version,
+ "browserstack.debug": "true",
+ "browserstack.networkLogs": "true",
+ "browserstack.consoleLogs": "info",
+ }
+ return f"wss://cdp.browserstack.com/playwright?caps={urllib.parse.quote(json.dumps(caps))}"
+
+
+async def _annotate_browserstack(page: Page, text: str, level: str = "info") -> None:
+ payload = json.dumps({"action": "annotate", "arguments": {"data": text, "level": level}})
+ await page.evaluate("_ => {}", f"browserstack_executor: {payload}")
+
+
+async def _set_browserstack_status(page: Page, passed: bool, reason: str = "") -> None:
+ status = "passed" if passed else "failed"
+ payload = json.dumps({"action": "setSessionStatus", "arguments": {"status": status, "reason": reason}})
+ await page.evaluate("_ => {}", f"browserstack_executor: {payload}")
+
+
+async def _report_cloud(page: Page, capture: AnalyticsCapture) -> None:
+ events = extract_posthog_events_from_console(capture.console_lines)
+ counts = Counter(events)
+ pageviews = counts.get("$pageview", 0)
+ breakdown = ", ".join(f"{k}: {v}" for k, v in sorted(counts.items())) or "none"
+ await _annotate_browserstack(page, f"PostHog events — {breakdown}")
+ passed = pageviews > 0
+ reason = f"{pageviews} $pageview event(s)" if passed else "no $pageview events"
+ await _set_browserstack_status(page, passed, reason)
+
+
+# ---- Browser setup -------------------------------------------------------------
+
+
+async def _launch(p, *, cloud: bool, headless: bool) -> Browser:
+ if cloud:
+ return await p.chromium.connect(_build_browserstack_cdp_url())
+ return await p.chromium.launch(headless=headless)
+
+
+async def _new_context(browser: Browser) -> BrowserContext:
+ context = await browser.new_context(
+ user_agent=USER_AGENT,
+ viewport={"width": 1920, "height": 1080},
+ locale="en-US",
+ timezone_id="America/New_York",
+ )
+ # Strip the webdriver flag so SPAs that look at navigator.webdriver
+ # don't suppress events on us.
+ await context.add_init_script("Object.defineProperty(navigator, 'webdriver', { get: () => undefined });")
+ return context
+
+
+# ---- Scenarios -----------------------------------------------------------------
+
+
+async def run_new_user(
+ *,
+ urls: list[str],
+ visits: int,
+ interval: float,
+ headless: bool,
+ verbose: bool,
+ cloud: bool,
+ timeout_ms: int,
+ run_id: str,
+ posthog_domains: tuple[str, ...],
+) -> list[VisitResult]:
+ results: list[VisitResult] = []
+ async with async_playwright() as p:
+ browser = await _launch(p, cloud=cloud, headless=headless)
+ try:
+ for i in range(visits):
+ url = add_tracking_params(random.choice(urls), run_id, "new-user")
+ result = await _do_visit(
+ browser=browser,
+ url=url,
+ visit_number=i + 1,
+ scenario="new-user",
+ fresh_context=True,
+ verbose=verbose,
+ cloud=cloud,
+ timeout_ms=timeout_ms,
+ posthog_domains=posthog_domains,
+ )
+ results.append(result)
+ _print_visit_summary(result)
+ if i < visits - 1:
+ print(f" Waiting {interval}s before next visit…")
+ await asyncio.sleep(interval)
+ finally:
+ await browser.close()
+ return results
+
+
+async def run_returning_user(
+ *,
+ urls: list[str],
+ page_views: int,
+ interval: float,
+ headless: bool,
+ verbose: bool,
+ cloud: bool,
+ timeout_ms: int,
+ run_id: str,
+ posthog_domains: tuple[str, ...],
+) -> list[VisitResult]:
+ results: list[VisitResult] = []
+ async with async_playwright() as p:
+ browser = await _launch(p, cloud=cloud, headless=headless)
+ context = await _new_context(browser)
+ try:
+ for i in range(page_views):
+ url = add_tracking_params(random.choice(urls), run_id, "returning-user")
+ result = await _do_visit(
+ browser=browser,
+ url=url,
+ visit_number=i + 1,
+ scenario="returning-user",
+ fresh_context=False,
+ shared_context=context,
+ verbose=verbose,
+ cloud=cloud,
+ timeout_ms=timeout_ms,
+ posthog_domains=posthog_domains,
+ )
+ results.append(result)
+ _print_visit_summary(result)
+ if i < page_views - 1:
+ print(f" Waiting {interval}s before next page view…")
+ await asyncio.sleep(interval)
+ finally:
+ await context.close()
+ await browser.close()
+ return results
+
+
+async def _do_visit(
+ *,
+ browser: Browser,
+ url: str,
+ visit_number: int,
+ scenario: str,
+ fresh_context: bool,
+ verbose: bool,
+ cloud: bool,
+ timeout_ms: int,
+ posthog_domains: tuple[str, ...],
+ shared_context: BrowserContext | None = None,
+) -> VisitResult:
+ timestamp = datetime.now(UTC).isoformat()
+ parsed = urlparse(url)
+ print(f"\n[{datetime.now().strftime('%H:%M:%S')}] {scenario} {visit_number} | {parsed.netloc}{parsed.path}")
+ result = VisitResult(visit_number=visit_number, scenario=scenario, url=url, timestamp=timestamp)
+ context = await _new_context(browser) if fresh_context else shared_context
+ assert context is not None
+ page: Page | None = None
+ try:
+ page = await context.new_page()
+ capture = AnalyticsCapture(posthog_domains=posthog_domains, verbose=verbose)
+ capture.attach(page)
+ start = time.perf_counter()
+ await page.goto(url, wait_until="load", timeout=timeout_ms)
+ result.page_load_ms = (time.perf_counter() - start) * 1000
+ await asyncio.sleep(5.0)
+ await simulate_user_behavior(page)
+ await asyncio.sleep(3.0)
+ result.posthog_requests = capture.posthog_requests
+ result.console_lines = capture.console_lines
+ if cloud:
+ await _report_cloud(page, capture)
+ except Exception as exc:
+ result.error = str(exc)
+ print(f" Error: {exc}")
+ if cloud and page is not None:
+ try:
+ await _set_browserstack_status(page, False, str(exc))
+ except Exception:
+ pass
+ finally:
+ if fresh_context:
+ try:
+ await context.close()
+ except Exception:
+ pass
+ elif page is not None:
+ try:
+ await page.close()
+ except Exception:
+ pass
+ return result
+
+
+async def run_check_loading(
+ *,
+ urls: list[str],
+ headless: bool,
+ verbose: bool,
+ cloud: bool,
+ timeout_ms: int,
+ run_id: str,
+ posthog_domains: tuple[str, ...],
+) -> dict[str, dict]:
+ pages: dict[str, dict] = {}
+ async with async_playwright() as p:
+ browser = await _launch(p, cloud=cloud, headless=headless)
+ context = await _new_context(browser)
+ try:
+ for i, url in enumerate(urls):
+ parsed = urlparse(url)
+ short = f"{parsed.hostname}{parsed.path}" if parsed.hostname else parsed.path or "/"
+ print(f"\n[{datetime.now().strftime('%H:%M:%S')}] ({i + 1}/{len(urls)}) {short}")
+ page = await context.new_page()
+ try:
+ await page.goto(url, wait_until="load", timeout=timeout_ms)
+ await asyncio.sleep(5.0)
+ detection = await page.evaluate(POSTHOG_DETECT_JS)
+ detection["url"] = url
+ detection["error"] = None
+ pages[url] = detection
+ loaded = detection.get("runtime_state", {}).get("loaded", False)
+ if verbose:
+ cfg = detection.get("init_config") or {}
+ print(
+ f" loaded={loaded} method={detection['load_method']} "
+ f"snippet_in={detection.get('snippet_location') or '-'} "
+ f"api_key={_redact_api_key(cfg.get('api_key'))} api_host={cfg.get('api_host', 'none')}"
+ )
+ else:
+ marker = "✓" if loaded else "✗"
+ print(f" {marker} method={detection['load_method']}")
+ except Exception as exc:
+ pages[url] = {"url": url, "error": str(exc)}
+ print(f" Error: {exc}")
+ finally:
+ await page.close()
+ finally:
+ await context.close()
+ await browser.close()
+ _print_check_loading_table(pages)
+ return pages
+
+
+def _print_check_loading_table(pages: dict[str, dict]) -> None:
+ print()
+ print("=" * 100)
+ print("POSTHOG LOADING")
+ print("=" * 100)
+ print(f"{'URL':<55} {'Loaded':<8} {'Method':<14} {'Snippet In':<12} {'API key':<14}")
+ print("-" * 100)
+ for url, data in pages.items():
+ label = url if len(url) <= 55 else url[:54] + "…"
+ if data.get("error"):
+ print(f"{label:<55} ERROR {data['error'][:40]}")
+ continue
+ loaded = "yes" if data.get("runtime_state", {}).get("loaded", False) else "no"
+ method = data.get("load_method", "-")
+ snip = data.get("snippet_location") or "-"
+ cfg = data.get("init_config") or {}
+ key = _redact_api_key(cfg.get("api_key"))
+ print(f"{label:<55} {loaded:<8} {method:<14} {snip:<12} {key:<14}")
+
+
+# ---- Output --------------------------------------------------------------------
+
+
+def _print_visit_summary(result: VisitResult) -> None:
+ load = f"{result.page_load_ms:.0f}ms" if result.page_load_ms else "n/a"
+ network_events = [e for r in result.posthog_requests for e in r.events]
+ events = network_events or extract_posthog_events_from_console(result.console_lines)
+ counts = Counter(events)
+ breakdown = ", ".join(f"{k}: {v}" for k, v in sorted(counts.items())) or "none"
+ success = sum(1 for r in result.posthog_requests if r.status in (200, 204))
+ print(f" Page load: {load}")
+ print(f" PostHog requests: {len(result.posthog_requests)} ({success} OK)")
+ print(f" PostHog events: {breakdown}")
+ if result.error:
+ print(f" Error: {result.error}")
+
+
+def _summary_dict(results: list[VisitResult]) -> dict:
+ return {
+ "posthog_requests": sum(len(r.posthog_requests) for r in results),
+ "posthog_requests_ok": sum(sum(1 for req in r.posthog_requests if req.status in (200, 204)) for r in results),
+ "errors": sum(1 for r in results if r.error),
+ }
+
+
+def _save_visits(results: list[VisitResult], scenario: str, run_id: str) -> Path:
+ RESULTS_DIR.mkdir(exist_ok=True)
+ filename = RESULTS_DIR / f"{scenario}_{run_id}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
+ data = {
+ "run_id": run_id,
+ "scenario": scenario,
+ "timestamp": datetime.now(UTC).isoformat(),
+ "total_visits": len(results),
+ "summary": _summary_dict(results),
+ "visits": [asdict(r) for r in results],
+ }
+ filename.write_text(json.dumps(data, indent=2))
+ print(f"\nResults saved to: {filename}")
+ return filename
+
+
+def _save_check_loading_report(pages: dict[str, dict], run_id: str) -> Path:
+ RESULTS_DIR.mkdir(exist_ok=True)
+ filename = RESULTS_DIR / f"check-loading_{run_id}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
+ report = {
+ "run_id": run_id,
+ "timestamp": datetime.now(UTC).isoformat(),
+ "total_urls": len(pages),
+ "pages": pages,
+ }
+ filename.write_text(json.dumps(report, indent=2))
+ print(f"\nReport saved to: {filename}")
+ return filename
+
+
+# ---- URL loading ---------------------------------------------------------------
+
+
+def load_urls(urls_arg: list[str] | None, urls_file: str | None) -> list[str]:
+ if urls_arg:
+ return urls_arg
+ if urls_file:
+ return _load_urls_file(urls_file)
+ raise ValueError("Provide either --url <URL> ... or --urls-file <PATH>")
+
+
+def _load_urls_file(path: str) -> list[str]:
+ """Load URLs from a JSON file. Two accepted shapes:
+ 1) flat list: ["https://example.com/", ...]
+ 2) grouped: {"base_url": "...", "categories": {"cat": ["/path", ...]}, "extra_urls": [...]}
+ """
+ with open(path) as f:
+ data = json.load(f)
+ if isinstance(data, list):
+ if not data:
+ raise ValueError(f"No URLs found in {path}")
+ return data
+ base = (data.get("base_url") or "").rstrip("/")
+ urls: list[str] = []
+ for paths in data.get("categories", {}).values():
+ urls.extend(f"{base}{p}" for p in paths)
+ urls.extend(data.get("extra_urls", []))
+ if not urls:
+ raise ValueError(f"No URLs found in {path}")
+ return urls
+
+
+def resolve_posthog_domains(host: str) -> tuple[str, ...]:
+ """Build the set of hostnames we treat as PostHog network traffic.
+
+ Always includes the cloud defaults (posthog.com / i.posthog.com) so events
+ sent to the PostHog cloud are caught even when --posthog-host points at
+ a custom reverse proxy.
+ """
+ extras: tuple[str, ...] = ()
+ if host:
+ netloc = (urlparse(host).hostname or host).lower()
+ if netloc and not any(netloc == d or netloc.endswith("." + d) for d in DEFAULT_POSTHOG_DOMAINS):
+ extras = (netloc,)
+ return DEFAULT_POSTHOG_DOMAINS + extras
+
+
+# ---- CLI -----------------------------------------------------------------------
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ prog="traffic-sim",
+ description="Drive a real browser at a URL and verify PostHog instrumentation.",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ epilog="""
+Examples:
+ traffic-sim new-user --url https://example.com --visits 3
+ traffic-sim returning-user --url https://example.com --page-views 5
+ traffic-sim check-loading --urls-file urls.json
+""",
+ )
+ sub = parser.add_subparsers(dest="scenario", required=True)
+
+ nu = sub.add_parser("new-user", help="Each visit uses a fresh browser context.")
+ nu.add_argument("--visits", type=int, default=10)
+ nu.add_argument("--interval", type=float, default=60.0)
+
+ ru = sub.add_parser("returning-user", help="All page views share the same browser context.")
+ ru.add_argument("--page-views", type=int, default=5)
+ ru.add_argument("--interval", type=float, default=30.0)
+
+ cl = sub.add_parser("check-loading", help="Inspect how the PostHog snippet is loaded.")
+
+ for s in (nu, ru, cl):
+ s.add_argument(
+ "--url",
+ action="append",
+ dest="urls",
+ default=None,
+ help="Target URL (repeatable). Mutually exclusive with --urls-file.",
+ )
+ s.add_argument(
+ "--urls-file",
+ type=str,
+ default=None,
+ help="JSON file of URLs (flat list or {base_url, categories} object).",
+ )
+ s.add_argument(
+ "--posthog-host",
+ type=str,
+ default=DEFAULT_POSTHOG_HOST,
+ help=f"PostHog ingestion host (default: {DEFAULT_POSTHOG_HOST}).",
+ )
+ s.add_argument(
+ "--cloud",
+ action="store_true",
+ help="Run on BrowserStack (requires BROWSERSTACK_USERNAME/ACCESS_KEY env vars).",
+ )
+ s.add_argument("--headed", action="store_true", help="Show browser window (default: headless).")
+ s.add_argument("--verbose", action="store_true", help="Print every PostHog request and console line.")
+ s.add_argument("--timeout", type=int, default=120, help="Page load timeout in seconds (default: 120).")
+
+ return parser
+
+
+async def main_async(argv: list[str] | None = None) -> int:
+ args = build_parser().parse_args(argv)
+
+ headless = not args.headed
+ timeout_ms = args.timeout * 1000
+ run_id = uuid.uuid4().hex[:8]
+ urls = load_urls(args.urls, args.urls_file)
+ posthog_domains = resolve_posthog_domains(args.posthog_host)
+
+ print("PostHog Traffic Simulation")
+ print(f"Scenario: {args.scenario}")
+ print(f"Run ID: {run_id}")
+ print(f"URLs: {len(urls)}")
+ print(f"PostHog host: {args.posthog_host}")
+ print(f"Headless: {headless}")
+ print("=" * 60)
+
+ if args.scenario == "check-loading":
+ pages = await run_check_loading(
+ urls=urls,
+ headless=headless,
+ verbose=args.verbose,
+ cloud=args.cloud,
+ timeout_ms=timeout_ms,
+ run_id=run_id,
+ posthog_domains=posthog_domains,
+ )
+ _save_check_loading_report(pages, run_id)
+ return 0
+
+ if args.scenario == "new-user":
+ results = await run_new_user(
+ urls=urls,
+ visits=args.visits,
+ interval=args.interval,
+ headless=headless,
+ verbose=args.verbose,
+ cloud=args.cloud,
+ timeout_ms=timeout_ms,
+ run_id=run_id,
+ posthog_domains=posthog_domains,
+ )
+ else:
+ results = await run_returning_user(
+ urls=urls,
+ page_views=args.page_views,
+ interval=args.interval,
+ headless=headless,
+ verbose=args.verbose,
+ cloud=args.cloud,
+ timeout_ms=timeout_ms,
+ run_id=run_id,
+ posthog_domains=posthog_domains,
+ )
+
+ print("\n" + "=" * 60)
+ print("SUMMARY")
+ print("=" * 60)
+ summary = _summary_dict(results)
+ print(f"Run ID: {run_id}")
+ print(f"Total visits: {len(results)}")
+ print(f"PostHog requests: {summary['posthog_requests']} ({summary['posthog_requests_ok']} OK)")
+ print(f"Errors: {summary['errors']}")
+ _save_visits(results, args.scenario, run_id)
+ return 0
+
+
+def main() -> int:
+ try:
+ return asyncio.run(main_async())
+ except KeyboardInterrupt:
+ return 130
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/traffic-sim/console-snippet.js b/tools/traffic-sim/console-snippet.js
new file mode 100644
index 000000000000..b1df08ba447e
--- /dev/null
+++ b/tools/traffic-sim/console-snippet.js
@@ -0,0 +1,110 @@
+// PostHog Loading Inspector — paste into browser DevTools console.
+// Extracts script tags, init config, runtime state, and load method.
+(() => {
+ const scripts = [...document.querySelectorAll("script")];
+
+ const posthogScripts = scripts.filter((s) => {
+ const src = (s.src || "").toLowerCase();
+ const id = (s.id || "").toLowerCase();
+ const text = (s.textContent || "").toLowerCase();
+ return (
+ src.includes("posthog") ||
+ src.includes("array.js") ||
+ id.includes("posthog") ||
+ text.includes("posthog") ||
+ text.includes("phc_") ||
+ text.includes("ph_init")
+ );
+ });
+
+ const hasPosthogInitId = !!document.getElementById("posthog-init");
+
+ const hasNextJsHydration = scripts.some((s) => {
+ const text = s.textContent || "";
+ return text.includes("self.__next_s") && text.includes("posthog");
+ });
+
+ let initConfig = null;
+ for (const s of posthogScripts) {
+ const text = s.textContent || "";
+ const initMatch = text.match(
+ /posthog\.init\s*\(\s*['"]([^'"]+)['"]\s*,\s*(\{[\s\S]*?\})\s*\)/
+ );
+ if (initMatch) {
+ try {
+ const configStr = initMatch[2]
+ .replace(/(\w+)\s*:/g, '"$1":')
+ .replace(/'/g, '"')
+ .replace(/,\s*}/g, "}");
+ const parsed = JSON.parse(configStr);
+ initConfig = {
+ api_key: initMatch[1],
+ api_host: parsed.api_host || null,
+ ui_host: parsed.ui_host || null,
+ person_profiles: parsed.person_profiles || null,
+ session_recording: parsed.session_recording || null,
+ };
+ } catch {
+ initConfig = { api_key: initMatch[1], raw: initMatch[2] };
+ }
+ break;
+ }
+ }
+
+ if (!initConfig && window.posthog && window.posthog.config) {
+ const c = window.posthog.config;
+ initConfig = {
+ api_key: c.token || null,
+ api_host: c.api_host || null,
+ ui_host: c.ui_host || null,
+ person_profiles: c.person_profiles || null,
+ session_recording: c.session_recording || null,
+ };
+ }
+
+ const arrayjsScript = posthogScripts.find(
+ (s) => s.src && s.src.includes("array")
+ );
+
+ const runtimeDefined = typeof window.posthog !== "undefined";
+ let runtimeState = { defined: runtimeDefined, loaded: false };
+ if (runtimeDefined && window.posthog) {
+ runtimeState = {
+ defined: true,
+ loaded: !!window.posthog.__loaded,
+ distinct_id: window.posthog.get_distinct_id
+ ? window.posthog.get_distinct_id()
+ : null,
+ config_api_host: window.posthog.config
+ ? window.posthog.config.api_host
+ : null,
+ };
+ }
+
+ let loadMethod = "none";
+ if (runtimeState.loaded && hasPosthogInitId) {
+ loadMethod = "snippet";
+ } else if (runtimeState.loaded) {
+ loadMethod = "npm";
+ }
+
+ const result = {
+ url: window.location.href,
+ script_tag_count: posthogScripts.length,
+ has_posthog_init_id: hasPosthogInitId,
+ has_nextjs_hydration: hasNextJsHydration,
+ init_config: initConfig,
+ runtime_state: runtimeState,
+ load_method: loadMethod,
+ arrayjs_src: arrayjsScript ? arrayjsScript.src : null,
+ script_details: posthogScripts.map((s) => ({
+ id: s.id || null,
+ src: s.src || null,
+ type: s.type || null,
+ text_preview: (s.textContent || "").slice(0, 200),
+ })),
+ };
+
+ console.info(JSON.stringify(result, null, 2));
+ return result;
+})();
diff --git a/tools/traffic-sim/mcp_server.py b/tools/traffic-sim/mcp_server.py
new file mode 100644
index 000000000000..8bb27b7e9239
--- /dev/null
+++ b/tools/traffic-sim/mcp_server.py
@@ -0,0 +1,200 @@
+#!/usr/bin/env python3
+"""Local MCP server for traffic-sim — verify PostHog instrumentation from any MCP client.
+
+Exposes three tools that wrap the CLI handlers:
+- simulate_new_user
+- simulate_returning_user
+- check_posthog_loading
+
+Each tool launches a Playwright browser, drives it against the given URL,
+and returns a structured summary of what PostHog events fired.
+
+Run via Claude Code's .mcp.json (invoked automatically by the MCP client):
+ uv run python tools/traffic-sim/mcp_server.py
+"""
+
+from __future__ import annotations
+
+import sys
+import uuid
+from collections import Counter
+from pathlib import Path
+from typing import Any
+
+# Make the sibling cli module importable when this file is run directly
+# (e.g. by `uv run python tools/traffic-sim/mcp_server.py`).
+sys.path.insert(0, str(Path(__file__).parent))
+
+from mcp.server.fastmcp import FastMCP # noqa: E402
+
+import cli # noqa: E402
+
+mcp = FastMCP(
+ "traffic-sim",
+ instructions=(
+ "Drive a real browser at a URL and verify PostHog instrumentation. "
+ "Use simulate_new_user / simulate_returning_user to send traffic and "
+ "watch which events fire. Use check_posthog_loading to inspect how "
+ "the PostHog snippet is loaded across pages."
+ ),
+)
+
+
+def _summarize_visits(results: list[cli.VisitResult]) -> dict[str, Any]:
+ network_events: list[str] = []
+ console_events: list[str] = []
+ visits_with_pageview = 0
+ for r in results:
+ visit_network = [e for req in r.posthog_requests for e in req.events]
+ visit_console = cli.extract_posthog_events_from_console(r.console_lines)
+ network_events.extend(visit_network)
+ console_events.extend(visit_console)
+ visit_events = visit_network or visit_console
+ if "$pageview" in visit_events:
+ visits_with_pageview += 1
+ events = network_events or console_events
+ counts = Counter(events)
+ success = sum(sum(1 for req in r.posthog_requests if req.status in (200, 204)) for r in results)
+ requests = sum(len(r.posthog_requests) for r in results)
+ errors = [r.error for r in results if r.error]
+ return {
+ "total_visits": len(results),
+ "posthog_requests": requests,
+ "posthog_requests_ok": success,
+ "events_by_type": dict(sorted(counts.items())),
+ "pageviews": counts.get("$pageview", 0),
+ "errors": errors,
+ # verified: every visit captured at least one $pageview, and none errored.
+ "verified": bool(results) and visits_with_pageview == len(results) and not errors,
+ }
+
+
+async def simulate_new_user(
+ url: str,
+ visits: int = 3,
+ interval: float = 5.0,
+ posthog_host: str = cli.DEFAULT_POSTHOG_HOST,
+ verbose: bool = False,
+) -> dict[str, Any]:
+ """Send N fresh-browser visits to a URL and report which PostHog events fired.
+
+ Each visit uses a brand-new browser context (no cookies, no localStorage),
+ so this matches a stream of unique visitors.
+
+ Args:
+ url: Target URL to visit. Repeat the call to spread across multiple URLs.
+ visits: Number of visits (default 3). Each visit takes ~10s plus interval.
+ interval: Seconds to wait between visits (default 5).
+ posthog_host: PostHog ingestion host. Defaults to https://us.i.posthog.com.
+ Set to https://eu.i.posthog.com for the EU cloud, or your
+ self-hosted host (e.g. https://ph.example.com).
+ verbose: Print every PostHog request and console line to stderr.
+ """
+ run_id = uuid.uuid4().hex[:8]
+ posthog_domains = cli.resolve_posthog_domains(posthog_host)
+ results = await cli.run_new_user(
+ urls=[url],
+ visits=visits,
+ interval=interval,
+ headless=True,
+ verbose=verbose,
+ cloud=False,
+ timeout_ms=cli.DEFAULT_TIMEOUT_MS,
+ run_id=run_id,
+ posthog_domains=posthog_domains,
+ )
+ return {"run_id": run_id, "scenario": "new-user", **_summarize_visits(results)}
+
+
+async def simulate_returning_user(
+ url: str,
+ page_views: int = 3,
+ interval: float = 5.0,
+ posthog_host: str = cli.DEFAULT_POSTHOG_HOST,
+ verbose: bool = False,
+) -> dict[str, Any]:
+ """Send N page views from a single returning user and report which PostHog events fired.
+
+ All page views share the same browser context, so cookies persist —
+ this matches a single visitor browsing multiple pages in a session.
+
+ Args:
+ url: Target URL to visit. Repeat the call to spread across multiple URLs.
+ page_views: Number of page views (default 3).
+ interval: Seconds to wait between page views (default 5).
+ posthog_host: PostHog ingestion host. Defaults to https://us.i.posthog.com.
+ verbose: Print every PostHog request and console line to stderr.
+ """
+ run_id = uuid.uuid4().hex[:8]
+ posthog_domains = cli.resolve_posthog_domains(posthog_host)
+ results = await cli.run_returning_user(
+ urls=[url],
+ page_views=page_views,
+ interval=interval,
+ headless=True,
+ verbose=verbose,
+ cloud=False,
+ timeout_ms=cli.DEFAULT_TIMEOUT_MS,
+ run_id=run_id,
+ posthog_domains=posthog_domains,
+ )
+ return {"run_id": run_id, "scenario": "returning-user", **_summarize_visits(results)}
+
+
+async def check_posthog_loading(
+ urls: list[str],
+ posthog_host: str = cli.DEFAULT_POSTHOG_HOST,
+ verbose: bool = False,
+) -> dict[str, Any]:
+ """Inspect how the PostHog snippet is loaded on each URL.
+
+ For each URL, returns whether posthog is detected, how it was loaded
+ (head_snippet / snippet / array_js_only), the init config, and runtime
+ state. Use this to confirm that all pages on a site initialize PostHog
+ consistently (catches misconfigurations like a missing snippet on /pricing).
+
+ Args:
+ urls: List of target URLs to inspect.
+ posthog_host: PostHog ingestion host. Defaults to https://us.i.posthog.com.
+ verbose: Print extra detail per page to stderr.
+ """
+ if not urls:
+ return {"error": "Provide at least one URL."}
+ run_id = uuid.uuid4().hex[:8]
+ posthog_domains = cli.resolve_posthog_domains(posthog_host)
+ pages = await cli.run_check_loading(
+ urls=urls,
+ headless=True,
+ verbose=verbose,
+ cloud=False,
+ timeout_ms=cli.DEFAULT_TIMEOUT_MS,
+ run_id=run_id,
+ posthog_domains=posthog_domains,
+ )
+ loaded: list[str] = []
+ not_loaded: list[str] = []
+ errors: list[dict[str, str]] = []
+ load_methods: Counter[str] = Counter()
+ for url, page in pages.items():
+ if page.get("error"):
+ errors.append({"url": url, "error": page["error"]})
+ continue
+ if page.get("runtime_state", {}).get("loaded"):
+ loaded.append(url)
+ else:
+ not_loaded.append(url)
+ load_methods[page.get("load_method", "unknown")] += 1
+ summary = {
+ "loaded": loaded,
+ "not_loaded": not_loaded,
+ "errors": errors,
+ "load_methods": dict(load_methods),
+ }
+ return {"run_id": run_id, "summary": summary, "pages": pages}
+
+
+if __name__ == "__main__":
+ mcp.run()
diff --git a/tools/traffic-sim/skills/README.md b/tools/traffic-sim/skills/README.md
new file mode 100644
index 000000000000..7d4028518449
--- /dev/null
+++ b/tools/traffic-sim/skills/README.md
@@ -0,0 +1,11 @@
+# traffic-sim skills
+
+Skills that wrap the [traffic-sim](../README.md) MCP tools for verifying PostHog
+instrumentation on a website.
+
+| Skill | Purpose |
+| --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
+| [verify-posthog-instrumentation](./verify-posthog-instrumentation/SKILL.md) | End-to-end orchestrator: confirms loading, then sends synthetic traffic. Start here. |
+| [check-posthog-loading](./check-posthog-loading/SKILL.md) | Inspect how PostHog is loaded on each URL (load method, init config). |
+| [simulate-new-user](./simulate-new-user/SKILL.md) | Send fresh-browser visits and confirm `$pageview` fires for new visitors. |
+| [simulate-returning-user](./simulate-returning-user/SKILL.md) | Send single-session multi-page traffic and confirm cookies + session stitching work. |
diff --git a/tools/traffic-sim/skills/check-posthog-loading/SKILL.md b/tools/traffic-sim/skills/check-posthog-loading/SKILL.md
new file mode 100644
index 000000000000..4f0c0559c953
--- /dev/null
+++ b/tools/traffic-sim/skills/check-posthog-loading/SKILL.md
@@ -0,0 +1,54 @@
+---
+name: check-posthog-loading
+description: >
+ Inspect how the PostHog JavaScript SDK is loaded across a list of URLs.
+ Use to confirm consistent installation across pages, find pages missing
+ the snippet, detect mismatched API keys or hosts between pages, and verify
+ the load method (head snippet vs deferred vs array.js).
+---
+
+# Check PostHog loading
+
+For each URL, navigates a real browser to the page, waits for PostHog to
+initialize, and reports:
+
+- Whether `window.posthog` is defined and `__loaded`.
+- Which load method was used: `head_snippet`, `snippet`, `array_js_only`, or `none`.
+- Where in the document the snippet lives (`head` / `body`).
+- The init config: `api_key`, `api_host`, `person_profiles`.
+- Runtime state including the assigned `distinct_id`.
+
+## When to use
+
+- Sanity-check a fresh install — does the snippet actually load on every page?
+- After a page-template change — did one page lose the snippet?
+- When investigating split data — are some pages pointing at a different
+ `api_host` or `api_key` than others?
+- Onboarding a new customer — confirm SDK is wired up before debugging events.
+
+## How to invoke
+
+Call the `check_posthog_loading` MCP tool with:
+
+- `urls` (required) — list of URLs to inspect.
+- `posthog_host` (default `https://us.i.posthog.com`).
+
+Returns a structured summary with which URLs loaded successfully, which
+didn't, and the load-method distribution.
+
+## Interpreting the result
+
+Look for these red flags:
+
+- **Empty `loaded` list, full `not_loaded` list** — snippet not present
+ anywhere. Re-run install or check that the layout includes the snippet.
+- **Mixed `loaded` / `not_loaded`** — snippet missing from some pages.
+ Common cause: a page rendered by a different template or layout.
+- **Multiple distinct `api_key` values across pages** — a page is pointing
+ at the wrong PostHog project.
+- **Multiple distinct `api_host` values** — a page is pointing at the wrong
+ ingestion endpoint (e.g. EU cloud vs US cloud, or vs a self-hosted reverse
+ proxy). This causes events to land in different projects than expected.
+- **`load_method: array_js_only`** with no init config — `array.js` was
+ loaded but `posthog.init()` was never called. Common with manual installs
+ that miss the second half.
diff --git a/tools/traffic-sim/skills/simulate-new-user/SKILL.md b/tools/traffic-sim/skills/simulate-new-user/SKILL.md
new file mode 100644
index 000000000000..8e35f36bbda6
--- /dev/null
+++ b/tools/traffic-sim/skills/simulate-new-user/SKILL.md
@@ -0,0 +1,59 @@
+---
+name: simulate-new-user
+description: >
+ Send synthetic first-time-visitor traffic to a URL and confirm that PostHog
+ $pageview events fire. Use when a customer wants to verify that anonymous
+ visitor tracking works, after deploying instrumentation changes, or when
+ debugging "events not arriving" reports.
+---
+
+# Simulate new-user traffic
+
+Drives a fresh browser context for each visit (no cookies, no localStorage),
+goes to the given URL, scrolls a bit, and reports which PostHog events fired.
+Each visit looks to PostHog like a brand-new anonymous visitor.
+
+## When to use
+
+- Confirm `$pageview` fires on the first visit (no cookies present).
+- Confirm an anonymous `distinct_id` is generated and a PostHog request
+ is sent within a few seconds of page load.
+- Reproduce "events not showing up for new users" reports.
+
+## How to invoke
+
+Call the `simulate_new_user` MCP tool with:
+
+- `url` (required) — the page to visit, e.g. `https://example.com/pricing`.
+- `visits` (default `3`) — number of fresh-context visits.
+- `interval` (default `5.0`) — seconds between visits.
+- `posthog_host` (default `https://us.i.posthog.com`) — set to
+ `https://eu.i.posthog.com` for the EU cloud, or your self-hosted host
+ (e.g. `https://ph.example.com`).
+
+Each visit takes ~10s of Playwright time plus the interval, so plan accordingly.
+
+## Interpreting the result
+
+The tool returns a structured summary:
+
+```jsonc
+{
+ "run_id": "a1b2c3d4",
+ "scenario": "new-user",
+ "total_visits": 3,
+ "posthog_requests": 6,
+ "posthog_requests_ok": 6,
+ "events_by_type": { "$pageview": 3, "$autocapture": 3 },
+ "pageviews": 3,
+ "errors": [],
+ "verified": true,
+}
+```
+
+- `verified: true` means at least one `$pageview` was captured per visit and
+ no errors occurred — the new-user flow works.
+- `verified: false` with `pageviews: 0` means PostHog isn't firing pageviews.
+ Run `check_posthog_loading` next to see whether the snippet is even loaded.
+- `posthog_requests_ok < posthog_requests` means PostHog returned non-2xx
+ responses. Check the project's ingestion limits and api_host configuration.
diff --git a/tools/traffic-sim/skills/simulate-returning-user/SKILL.md b/tools/traffic-sim/skills/simulate-returning-user/SKILL.md
new file mode 100644
index 000000000000..c37fff2feffa
--- /dev/null
+++ b/tools/traffic-sim/skills/simulate-returning-user/SKILL.md
@@ -0,0 +1,48 @@
+---
+name: simulate-returning-user
+description: >
+ Send synthetic single-session multi-page traffic to a URL and confirm
+ PostHog $pageview events fire across page views. Use when verifying that
+ cookies persist correctly, that the same distinct_id is reused across
+ navigations, or when debugging session-stitching issues.
+---
+
+# Simulate returning-user traffic
+
+Drives a single browser context across N page views (cookies and localStorage
+persist), navigating between pages and reporting which PostHog events fired.
+This matches the behavior of a single visitor browsing multiple pages on the
+same site.
+
+## When to use
+
+- Confirm that PostHog reuses the same `distinct_id` across page views in a
+ session (no fresh anonymous IDs per page).
+- Confirm `$pageview` fires on every page view, not just the first.
+- Reproduce "session not stitching" or "events split across multiple users"
+ reports.
+
+## How to invoke
+
+Call the `simulate_returning_user` MCP tool with:
+
+- `url` (required) — the page to visit each iteration.
+- `page_views` (default `3`) — number of page views in the session.
+- `interval` (default `5.0`) — seconds between page views.
+- `posthog_host` (default `https://us.i.posthog.com`).
+
+To exercise multi-page navigation, call the tool once per URL — the cookies
+won't carry across calls (each call is a separate Playwright context). For
+true multi-page browsing within one session, edit the URL list passed to the
+underlying CLI: `traffic-sim returning-user --url A --url B --url C`.
+
+## Interpreting the result
+
+The structured response shape matches `simulate_new_user`. Key signals:
+
+- `verified: true` and `pageviews >= page_views` — the session works.
+- Same `distinct_id` across all pageviews (visible in PostHog UI under the
+ run_id query param) — session stitching works.
+- Different `distinct_id` per visit — likely a cookie domain or
+ storage-permissions issue. Inspect the raw `posthog_requests` for `$session_id`
+ values to diagnose.
diff --git a/tools/traffic-sim/skills/verify-posthog-instrumentation/SKILL.md b/tools/traffic-sim/skills/verify-posthog-instrumentation/SKILL.md
new file mode 100644
index 000000000000..704232ab095c
--- /dev/null
+++ b/tools/traffic-sim/skills/verify-posthog-instrumentation/SKILL.md
@@ -0,0 +1,78 @@
+---
+name: verify-posthog-instrumentation
+description: >
+ Use this skill to verify that PostHog instrumentation is firing correctly on
+ a website. Drives a real browser at one or more URLs, observes which PostHog
+ events actually arrive, and reports a pass/fail summary. Use after installing
+ the PostHog SDK on a site, after a deploy that touches tracking code, or when
+ events appear missing in the PostHog dashboard.
+---
+
+# Verify PostHog instrumentation
+
+End-to-end check that the PostHog SDK is loaded and emitting events as expected.
+This skill orchestrates the three traffic-sim tools to give a complete picture
+of a site's instrumentation health.
+
+## When to use
+
+- After running `npx @posthog/wizard` to confirm the install actually works.
+- After a deploy that touches analytics, tracking, or layout code.
+- When a customer reports "I'm not seeing events in PostHog" — to disambiguate
+ between snippet issues, network issues, or filtering issues.
+- As a smoke test before launching a new site or marketing page.
+
+## Workflow
+
+### Step 1 — Confirm the snippet is loaded everywhere
+
+Run the `check_posthog_loading` MCP tool against the URLs you care about
+(homepage, key product pages, login, checkout, marketing pages). It returns
+which pages have PostHog initialized, the load method (head_snippet / snippet
+/ array_js_only), and the init config.
+
+Look for:
+
+- Pages where `loaded: false` — PostHog is missing from those pages.
+- Inconsistent `api_key` values across pages — multiple projects in use.
+- Inconsistent `api_host` values across pages — events going to different ingestion endpoints.
+
+### Step 2 — Send synthetic traffic and confirm events arrive
+
+Pick one URL where Step 1 confirmed PostHog is loaded. Call:
+
+- `simulate_new_user` — a few fresh-browser visits. Confirms `$pageview`
+ fires for first-time visitors and that an anonymous distinct_id is assigned.
+- `simulate_returning_user` — a few page views in a single session. Confirms
+ cookies persist and `$pageview` keeps firing across navigations.
+
+The tools return `verified: true` when at least one `$pageview` was captured
+and there were no errors.
+
+### Step 3 — Cross-check in PostHog
+
+If Steps 1 and 2 pass but events don't show up in the PostHog UI, the issue
+is downstream of the snippet:
+
+- Check for ingestion lag (events can take ~30s to appear).
+- Check that the `api_host` matches the project's ingestion host.
+- Check feature flag and ingestion warnings in the PostHog UI.
+
+## What "verified" means in this skill
+
+A site is verified when:
+
+1. `check_posthog_loading` reports `loaded: true` on every URL we expect.
+2. `simulate_new_user` and `simulate_returning_user` both return at least one
+ `$pageview` event per visit, with no errors.
+3. (Optional) The events appear in the PostHog UI within 1-2 minutes.
+
+## What this skill does not check
+
+- Whether your custom events (e.g. `signup_completed`) are being sent —
+ the tool watches for any PostHog event, but you'd need to drive the actual
+ user flow to see custom events fire. Use it as a starting point, then add
+ user-flow simulation on top.
+- Server-side ingestion. The tool only sees what the browser SDK sends.
+- Session recording quality. The tool reports whether recording is enabled
+ in the init config but doesn't validate the recording itself.
diff --git a/tools/traffic-sim/tests/__init__.py b/tools/traffic-sim/tests/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/tools/traffic-sim/tests/conftest.py b/tools/traffic-sim/tests/conftest.py
new file mode 100644
index 000000000000..0e116e2a1af9
--- /dev/null
+++ b/tools/traffic-sim/tests/conftest.py
@@ -0,0 +1,4 @@
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).parent.parent))
diff --git a/tools/traffic-sim/tests/test_cli.py b/tools/traffic-sim/tests/test_cli.py
new file mode 100644
index 000000000000..5ffce34b6830
--- /dev/null
+++ b/tools/traffic-sim/tests/test_cli.py
@@ -0,0 +1,246 @@
+"""Unit tests for traffic-sim cli helpers — no network, no Playwright."""
+
+import json
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+
+import cli
+
+
+class TestExtractPosthogEventsFromConsole:
+ @pytest.mark.parametrize(
+ "lines,expected",
+ [
+ ([], []),
+ (
+ [cli.ConsoleLine(timestamp="t", type="log", text='[PostHog.js] send "$pageview"', is_posthog=True)],
+ ["$pageview"],
+ ),
+ (
+ [
+ cli.ConsoleLine(timestamp="t", type="log", text='[PostHog.js] send "$pageview"', is_posthog=True),
+ cli.ConsoleLine(
+ timestamp="t", type="log", text='[PostHog.js] send "$autocapture"', is_posthog=True
+ ),
+ ],
+ ["$pageview", "$autocapture"],
+ ),
+ (
+ # Custom event names without $ prefix.
+ [
+ cli.ConsoleLine(
+ timestamp="t", type="log", text='[PostHog.js] send "signup_completed"', is_posthog=True
+ )
+ ],
+ ["signup_completed"],
+ ),
+ (
+ # Non-posthog console lines are ignored even if they look similar.
+ [cli.ConsoleLine(timestamp="t", type="log", text='[PostHog.js] send "$pageview"', is_posthog=False)],
+ [],
+ ),
+ ],
+ )
+ def test_extracts_event_names(self, lines, expected):
+ assert cli.extract_posthog_events_from_console(lines) == expected
+
+
+class TestAddTrackingParams:
+ def test_adds_required_params(self):
+ url = cli.add_tracking_params("https://example.com/foo", "abc123", "new-user")
+ params = parse_qs(urlparse(url).query)
+ assert params["__posthog_debug"] == ["true"]
+ assert params["run_id"] == ["abc123"]
+ assert params["scenario"] == ["new-user"]
+
+ def test_preserves_existing_query_params(self):
+ url = cli.add_tracking_params("https://example.com/foo?utm_source=x", "id", "scen")
+ params = parse_qs(urlparse(url).query)
+ assert params["utm_source"] == ["x"]
+ assert params["__posthog_debug"] == ["true"]
+
+
+class TestResolvePosthogDomains:
+ def test_empty_host_returns_defaults(self):
+ assert cli.resolve_posthog_domains("") == cli.DEFAULT_POSTHOG_DOMAINS
+
+ def test_default_host_does_not_add_extras(self):
+ # us.i.posthog.com is a subdomain of i.posthog.com, so no extra needed.
+ domains = cli.resolve_posthog_domains("https://us.i.posthog.com")
+ assert domains == cli.DEFAULT_POSTHOG_DOMAINS
+
+ def test_custom_host_adds_netloc(self):
+ domains = cli.resolve_posthog_domains("https://ph.example.com")
+ assert domains == (*cli.DEFAULT_POSTHOG_DOMAINS, "ph.example.com")
+
+ def test_eu_cloud_does_not_add_extras(self):
+ domains = cli.resolve_posthog_domains("https://eu.i.posthog.com")
+ assert domains == cli.DEFAULT_POSTHOG_DOMAINS
+
+
+class TestLoadUrlsFile:
+ def test_flat_list(self, tmp_path):
+ path = tmp_path / "urls.json"
+ path.write_text(json.dumps(["https://example.com/", "https://example.com/about"]))
+ assert cli._load_urls_file(str(path)) == ["https://example.com/", "https://example.com/about"]
+
+ def test_grouped_form(self, tmp_path):
+ path = tmp_path / "urls.json"
+ path.write_text(
+ json.dumps(
+ {
+ "base_url": "https://example.com",
+ "categories": {"main": ["/", "/about"], "marketing": ["/pricing"]},
+ "extra_urls": ["https://example.com/blog/post-1"],
+ }
+ )
+ )
+ urls = cli._load_urls_file(str(path))
+ assert sorted(urls) == sorted(
+ [
+ "https://example.com/",
+ "https://example.com/about",
+ "https://example.com/pricing",
+ "https://example.com/blog/post-1",
+ ]
+ )
+
+ def test_grouped_form_strips_trailing_slash_from_base(self, tmp_path):
+ path = tmp_path / "urls.json"
+ path.write_text(
+ json.dumps(
+ {
+ "base_url": "https://example.com/",
+ "categories": {"main": ["/about"]},
+ }
+ )
+ )
+ urls = cli._load_urls_file(str(path))
+ assert urls == ["https://example.com/about"]
+
+ @pytest.mark.parametrize(
+ "payload",
+ [
+ [],
+ {"base_url": "https://example.com"},
+ ],
+ )
+ def test_empty_payload_raises(self, tmp_path, payload):
+ path = tmp_path / "urls.json"
+ path.write_text(json.dumps(payload))
+ with pytest.raises(ValueError, match="No URLs found"):
+ cli._load_urls_file(str(path))
+
+
+class TestLoadUrls:
+ def test_args_take_precedence(self, tmp_path):
+ path = tmp_path / "urls.json"
+ path.write_text(json.dumps(["https://from-file.example.com/"]))
+ result = cli.load_urls(["https://from-arg.example.com/"], str(path))
+ assert result == ["https://from-arg.example.com/"]
+
+ def test_falls_back_to_file(self, tmp_path):
+ path = tmp_path / "urls.json"
+ path.write_text(json.dumps(["https://from-file.example.com/"]))
+ assert cli.load_urls(None, str(path)) == ["https://from-file.example.com/"]
+
+ def test_neither_raises(self):
+ with pytest.raises(ValueError, match="--url"):
+ cli.load_urls(None, None)
+
+
+class TestBuildParser:
+ @pytest.mark.parametrize("scenario", ["new-user", "returning-user", "check-loading"])
+ def test_parses_each_subcommand(self, scenario):
+ args = cli.build_parser().parse_args([scenario, "--url", "https://example.com"])
+ assert args.scenario == scenario
+ assert args.urls == ["https://example.com"]
+
+ def test_repeatable_url_flag(self):
+ args = cli.build_parser().parse_args(
+ [
+ "new-user",
+ "--url",
+ "https://a.com",
+ "--url",
+ "https://b.com",
+ ]
+ )
+ assert args.urls == ["https://a.com", "https://b.com"]
+
+ def test_new_user_defaults(self):
+ args = cli.build_parser().parse_args(["new-user", "--url", "https://example.com"])
+ assert args.visits == 10
+ assert args.interval == 60.0
+ assert not args.cloud
+ assert not args.headed
+ assert args.timeout == 120
+
+ def test_returning_user_defaults(self):
+ args = cli.build_parser().parse_args(["returning-user", "--url", "https://example.com"])
+ assert args.page_views == 5
+ assert args.interval == 30.0
+
+ def test_posthog_host_default(self):
+ args = cli.build_parser().parse_args(["check-loading", "--url", "https://example.com"])
+ assert args.posthog_host == cli.DEFAULT_POSTHOG_HOST
+
+ def test_custom_posthog_host(self):
+ args = cli.build_parser().parse_args(
+ [
+ "check-loading",
+ "--url",
+ "https://example.com",
+ "--posthog-host",
+ "https://eu.i.posthog.com",
+ ]
+ )
+ assert args.posthog_host == "https://eu.i.posthog.com"
+
+
+class TestAnalyticsCapture:
+ def test_is_posthog_matches_default_domains(self):
+ cap = cli.AnalyticsCapture(posthog_domains=cli.DEFAULT_POSTHOG_DOMAINS)
+ assert cap._is_posthog("https://us.i.posthog.com/capture/")
+ assert cap._is_posthog("https://app.posthog.com/decide/")
+ assert not cap._is_posthog("https://google-analytics.com/collect")
+ assert not cap._is_posthog("https://example.com/api")
+
+ def test_is_posthog_matches_custom_domain(self):
+ cap = cli.AnalyticsCapture(posthog_domains=("posthog.com", "ph.example.com"))
+ assert cap._is_posthog("https://ph.example.com/i/v0/e/")
+ assert cap._is_posthog("https://us.i.posthog.com/capture/")
+ assert not cap._is_posthog("https://other.example.com/api")
+
+ @pytest.mark.parametrize(
+ "url",
+ [
+ # Hostname containing posthog.com as a path/query component is not a match.
+ "https://evil.com/posthog.com/capture",
+ "https://evil.com/?proxy=us.i.posthog.com",
+ # Hostname that merely ends with posthog.com without a leading dot is not a match.
+ "https://notposthog.com/capture",
+ # Subdomain attack: posthog.com placed before the registered domain.
+ "https://posthog.com.evil.com/capture",
+ ],
+ )
+ def test_is_posthog_rejects_lookalike_urls(self, url):
+ cap = cli.AnalyticsCapture(posthog_domains=cli.DEFAULT_POSTHOG_DOMAINS)
+ assert not cap._is_posthog(url)
+
+
+class TestLoadBrowserstackYaml:
+ def test_returns_none_when_file_missing(self, monkeypatch, tmp_path):
+ monkeypatch.setattr(cli, "__file__", str(tmp_path / "cli.py"))
+ assert cli._load_browserstack_yaml() == (None, None)
+
+ def test_parses_username_and_access_key(self, monkeypatch, tmp_path):
+ (tmp_path / "browserstack.yml").write_text("# example header\nuserName: alice\naccessKey: 'secret-123'\n")
+ monkeypatch.setattr(cli, "__file__", str(tmp_path / "cli.py"))
+ assert cli._load_browserstack_yaml() == ("alice", "secret-123")
+
+ def test_skips_placeholder_blanks(self, monkeypatch, tmp_path):
+ (tmp_path / "browserstack.yml").write_text("userName:\naccessKey: \n")
+ monkeypatch.setattr(cli, "__file__", str(tmp_path / "cli.py"))
+ assert cli._load_browserstack_yaml() == (None, None)
diff --git a/tools/traffic-sim/tests/test_integration.py b/tools/traffic-sim/tests/test_integration.py
new file mode 100644
index 000000000000..d277953ab8f7
--- /dev/null
+++ b/tools/traffic-sim/tests/test_integration.py
@@ -0,0 +1,83 @@
+"""End-to-end integration test: spin up a local fixture page with a stub
+PostHog snippet, run check-loading against it, and assert the snippet was
+detected. Skipped automatically when Playwright isn't installed.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import threading
+import http.server
+import socketserver
+
+import pytest
+
+playwright = pytest.importorskip(
+ "playwright.async_api",
+ reason="Playwright not installed; run `playwright install chromium` first.",
+)
+
+import cli # noqa: E402
+
+FIXTURE_HTML = """<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <title>traffic-sim fixture</title>
+ <script id="posthog-init">
+ // Stub posthog object so the detector reports loaded=true without
+ // hitting the network during tests.
+ window.posthog = {
+ __loaded: true,
+ config: {token: 'phc_test_fixture', api_host: 'https://example.com'},
+ get_distinct_id: function() { return 'test-distinct-id'; },
+ };
+ </script>
+</head>
+<body>
+ <h1>Hello from the fixture</h1>
+</body>
+</html>
+"""
+
+
+def fixture_server(tmp_path):
+ """Serve FIXTURE_HTML on a localhost port. Yields the URL."""
+ fixture_dir = tmp_path / "site"
+ fixture_dir.mkdir()
+ (fixture_dir / "index.html").write_text(FIXTURE_HTML)
+
+ handler = lambda *a, **kw: http.server.SimpleHTTPRequestHandler(*a, directory=str(fixture_dir), **kw)
+ httpd = socketserver.TCPServer(("127.0.0.1", 0), handler)
+ port = httpd.server_address[1]
+ thread = threading.Thread(target=httpd.serve_forever, daemon=True)
+ thread.start()
+ try:
+ yield f"http://127.0.0.1:{port}/"
+ finally:
+ httpd.shutdown()
+ httpd.server_close()
+
+
+def test_check_loading_detects_stubbed_posthog(fixture_server):
+ """check-loading against a fixture page reports posthog as loaded."""
+ pages = asyncio.run(
+ cli.run_check_loading(
+ urls=[fixture_server],
+ headless=True,
+ verbose=False,
+ cloud=False,
+ timeout_ms=30_000,
+ run_id="itest",
+ posthog_domains=cli.DEFAULT_POSTHOG_DOMAINS,
+ )
+ )
+ assert len(pages) == 1
+ page_data = next(iter(pages.values()))
+ assert page_data.get("error") is None
+ assert page_data["runtime_state"]["loaded"] is True
+ # The stub uses #posthog-init script tag, which we treat as head_snippet.
+ assert page_data["load_method"] == "head_snippet"
+ assert page_data["init_config"]["api_key"] == "phc_test_fixture"
diff --git a/tools/traffic-sim/tests/test_mcp_server.py b/tools/traffic-sim/tests/test_mcp_server.py
new file mode 100644
index 000000000000..c377016da5ba
--- /dev/null
+++ b/tools/traffic-sim/tests/test_mcp_server.py
@@ -0,0 +1,49 @@
+"""Unit tests for mcp_server helpers — no Playwright, no MCP transport."""
+
+import pytest
+
+import mcp_server
+
+import cli
+
+
+def _visit(visit_number: int, events: list[str], error: str | None = None) -> cli.VisitResult:
+ requests = (
+ [
+ cli.AnalyticsRequest(
+ timestamp="t", url="https://us.i.posthog.com/i/v0/e/", method="POST", status=200, events=events
+ )
+ ]
+ if events
+ else []
+ )
+ return cli.VisitResult(
+ visit_number=visit_number,
+ scenario="new-user",
+ url="https://example.com",
+ timestamp="t",
+ posthog_requests=requests,
+ error=error,
+ )
+
+
+class TestSummarizeVisitsVerified:
+ @pytest.mark.parametrize(
+ "results,expected_verified,expected_pageviews",
+ [
+ ([], False, 0),
+ ([_visit(1, ["$pageview"])], True, 1),
+ ([_visit(1, ["$pageview"]), _visit(2, ["$pageview"])], True, 2),
+ # Only one of three visits captured a pageview — must NOT be verified.
+ ([_visit(1, ["$pageview"]), _visit(2, []), _visit(3, [])], False, 1),
+ # Pageview present but a sibling visit errored — not verified.
+ ([_visit(1, ["$pageview"]), _visit(2, ["$pageview"], error="boom")], False, 2),
+ # Non-pageview events alone don't satisfy verified.
+ ([_visit(1, ["$autocapture"])], False, 0),
+ ],
+ )
+ def test_verified_requires_pageview_per_visit(self, results, expected_verified, expected_pageviews):
+ summary = mcp_server._summarize_visits(results)
+ assert summary["verified"] is expected_verified
+ assert summary["pageviews"] == expected_pageviews
+ assert summary["total_visits"] == len(results)
diff --git a/tools/traffic-sim/urls.example.json b/tools/traffic-sim/urls.example.json
new file mode 100644
index 000000000000..9c04fc787a15
--- /dev/null
+++ b/tools/traffic-sim/urls.example.json
@@ -0,0 +1 @@
+["https://example.com/", "https://example.com/pricing", "https://example.com/blog", "https://example.com/about"]