# Analytics Reporter

Build an AI agent that connects to Google Analytics 4, analyzes traffic data, and generates automated reports on a schedule.

# Analytics Reporter

Build an AI agent that connects to Google Analytics 4, analyzes your website traffic, generates insights, and delivers automated daily and weekly reports.

## What You'll Build

An analytics reporting agent that:
- Connects to Google Analytics 4 (GA4) via MCP tools
- Queries traffic metrics and user behavior data
- Identifies trends and anomalies
- Generates daily and weekly reports
- Creates actionable recommendations

**Time to complete:** 30-45 minutes

## Prerequisites

- A TeamDay account with a [Personal Access Token](https://docs.teamday.ai/guides/api-keys)
- Google Analytics 4 property with data
- Google Cloud project (for API credentials)

## Architecture Overview

```
Scheduled Mission --> Analytics Agent --> GA4 MCP Tools --> GA4 Data API
                          |
                          v
                    Report Generation
                    (insights, trends, recommendations)
```

---

## Step 1: Google Cloud Setup

You need Google Cloud credentials so the agent can query the GA4 Data API.

### 1.1 Enable the GA4 Data API

1. Go to [Google Cloud Console](https://console.cloud.google.com/)
2. Create or select a project
3. Navigate to **APIs & Services > Enable APIs**
4. Search for **Google Analytics Data API** and enable it

Or via CLI:

```bash
gcloud services enable analyticsdata.googleapis.com
```

### 1.2 Create a Service Account (Recommended)

A service account is the simplest approach for server-to-server access:

1. Go to **IAM & Admin > Service Accounts**
2. Click **Create Service Account**
3. Name it "teamday-analytics"
4. Grant the **Viewer** role
5. Click **Create Key** > JSON > Download

Then grant the service account access to your GA4 property:

1. Open [Google Analytics](https://analytics.google.com/) > **Admin > Property Access Management**
2. Add the service account email (e.g., `teamday-analytics@project.iam.gserviceaccount.com`)
3. Grant **Viewer** access

### 1.3 Find Your GA4 Property ID

1. Go to [Google Analytics](https://analytics.google.com/)
2. **Admin > Property Settings**
3. Copy the **Property ID** (a number like `123456789`)

You can also find it in the URL: `https://analytics.google.com/analytics/web/#/p123456789/...`

---

## Step 2: TeamDay Setup

### 2.1 Create a Space

Create a dedicated space for analytics work. You can do this in the TeamDay web app, or via API:

```bash
curl -X POST https://cc.teamday.ai/api/v1/spaces \
  -H "Authorization: Bearer $TEAMDAY_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Analytics Reports"
  }'
```

Save the returned space ID (e.g., `rT4kWm9xBn2p`).

### 2.2 Store GA Credentials as Space Secrets

Store your Google credentials as encrypted space secrets. Secret keys must be `UPPER_SNAKE_CASE`:

```bash
curl -X POST https://cc.teamday.ai/api/v1/spaces/rT4kWm9xBn2p/secrets \
  -H "Authorization: Bearer $TEAMDAY_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "secrets": {
      "GOOGLE_SERVICE_ACCOUNT_KEY": "{...your service account JSON...}",
      "GA_PROPERTY_ID": "123456789"
    }
  }'
```

These secrets are encrypted at rest and injected as environment variables when the agent runs in this space.

---

## Step 3: Create the Analytics Agent

### 3.1 Create the Agent via API

```bash
curl -X POST https://cc.teamday.ai/api/v1/agents \
  -H "Authorization: Bearer $TEAMDAY_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Analytics Reporter",
    "role": "Data Analyst",
    "visibility": "organization",
    "model": "claude-sonnet-4-6",
    "tags": ["analytics", "reporting"],
    "systemPrompt": "You are an expert data analyst specializing in web analytics and user behavior.\n\n## Your Responsibilities\n\n1. **Data Collection** - Query Google Analytics 4 for relevant metrics across specified time periods.\n2. **Analysis** - Identify trends, spot anomalies, calculate growth rates, and compare periods (WoW, MoM).\n3. **Insights** - Explain what the data means in plain language. Highlight opportunities and concerns.\n4. **Reporting** - Structure reports clearly with prioritized findings and recommendations.\n\n## Key Metrics to Track\n\n**Traffic:** Total users, sessions, new vs returning users, pageviews, bounce rate, avg session duration\n**Acquisition:** Traffic sources (organic, direct, referral, social), top referrers, campaign performance\n**Content:** Top pages by views, landing pages, exit pages, engagement by page\n**Conversions:** Goal completions, conversion rates, e-commerce metrics if applicable\n**Technical:** Device breakdown, browser/OS distribution, page load performance\n\n## Analysis Framework\n\nFor each metric, report: current value, comparison to previous period, trend direction, significance, and possible explanations.\n\n## Report Format\n\nStructure every report as:\n1. **Executive Summary** (2-3 sentences)\n2. **Key Highlights** (top 3-4 findings)\n3. **Traffic Overview** (users, sessions, engagement)\n4. **Acquisition Breakdown** (sources table)\n5. **Content Performance** (top pages)\n6. **Recommendations** (prioritized action items)\n\nBe data-driven but explain insights in plain language that any stakeholder can understand."
  }'
```

**Response:**

```json
{
  "success": true,
  "id": "kP7mNx3vQw8j",
  "name": "Analytics Reporter",
  "status": "active",
  "chatUrl": "/agents/kP7mNx3vQw8j/chat"
}
```

Save the agent ID: `kP7mNx3vQw8j`

### 3.2 Add the Agent to Your Space

```bash
curl -X PATCH https://cc.teamday.ai/api/v1/spaces/rT4kWm9xBn2p \
  -H "Authorization: Bearer $TEAMDAY_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "addAgents": ["kP7mNx3vQw8j"]
  }'
```

---

## Step 4: Connect to Google Analytics

The agent needs MCP tools to query the GA4 Data API. There is no official `@modelcontextprotocol/server-google-analytics` package, so you have two options:

### Option A: Use a Community GA4 MCP Server

Several community-built GA4 MCP servers exist. Register one as an MCP instance:

```bash
curl -X POST https://cc.teamday.ai/api/v1/mcps \
  -H "Authorization: Bearer $TEAMDAY_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "mcpType": "google-analytics",
    "name": "Google Analytics",
    "description": "GA4 Data API access for analytics reporting",
    "isActive": true,
    "credentials": {
      "GA_PROPERTY_ID": { "value": "123456789", "isSecret": false },
      "GOOGLE_SERVICE_ACCOUNT_KEY": { "value": "stored-in-space-secrets", "isSecret": true }
    }
  }'
```

Then attach it to your space:

```bash
curl -X PATCH https://cc.teamday.ai/api/v1/spaces/rT4kWm9xBn2p \
  -H "Authorization: Bearer $TEAMDAY_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "addMcps": ["mcpIdFromResponse"]
  }'
```

### Option B: Build a Custom MCP Server

If you need full control, build a custom MCP server that wraps the [GA4 Data API](https://developers.google.com/analytics/devguides/reporting/data/v1). See the [Creating Custom MCP Servers](https://docs.teamday.ai/guides/mcp-servers/creating-custom) guide.

Your custom server would expose tools like `run_report`, `get_realtime_data`, and `list_dimensions_metrics` that the agent can call.

### Verify the Connection

Once configured, test by executing the agent:

```bash
curl -X POST https://cc.teamday.ai/api/v1/agents/kP7mNx3vQw8j/execute \
  -H "Authorization: Bearer $TEAMDAY_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "message": "Test the Google Analytics connection and list available metrics.",
    "spaceId": "rT4kWm9xBn2p"
  }'
```

---

## Step 5: Usage Examples

Once your agent is connected to GA4, here are the kinds of reports and analyses it can produce.

### 5.1 Daily Report

```
You: Generate today's daily analytics report

Agent: Creating comprehensive analytics report...
```

**Example output:**

> ## Daily Analytics Report - February 19, 2026
>
> ### Executive Summary
> Strong performance today with 1,834 users (+12% vs yesterday). Organic traffic
> continues to grow, and engagement metrics are healthy. Notable spike in mobile
> traffic suggests mobile optimization efforts are paying off.
>
> ### Key Highlights
> - **New users increased 22%** - acquisition efforts working
> - **Mobile traffic up 34%** - mobile-first strategy succeeding
> - **Bounce rate on /pricing increased to 61%** - needs attention
> - **Blog engagement up 18%** - content strategy effective
>
> ### Traffic Overview
> | Metric | Today | vs Yesterday |
> |--------|-------|--------------|
> | Users | 1,834 | +12% |
> | New Users | 1,245 | +22% |
> | Sessions | 2,367 | +15% |
> | Pageviews | 6,892 | +18% |
> | Avg Session Duration | 3m 48s | +5% |
> | Bounce Rate | 43.2% | -2.1% |
>
> ### Acquisition Breakdown
> | Source | Users | % of Total | Change |
> |--------|-------|------------|--------|
> | Organic Search | 892 | 48.6% | +15% |
> | Direct | 567 | 30.9% | +8% |
> | Referral | 234 | 12.8% | +23% |
> | Social | 98 | 5.3% | +45% |
> | Email | 43 | 2.3% | +12% |
>
> ### Top Pages
> 1. **/blog/api-best-practices** - 423 views, 4m 32s avg, 32% bounce
> 2. **/docs/getting-started** - 389 views, 5m 12s avg, 28% bounce
> 3. **/pricing** - 267 views, 1m 45s avg, 61% bounce
> 4. **/features/automation** - 198 views, 3m 21s avg, 38% bounce
>
> ### Device Breakdown
> - Desktop: 60.1% | Mobile: 35.5% (+34%) | Tablet: 4.4%
>
> ### Recommendations
> 1. **Optimize /pricing page** - 61% bounce rate is high. Add social proof or test CTA placement.
> 2. **Capitalize on referral traffic** - 23% increase. Identify top referrers and nurture those channels.
> 3. **Continue mobile-first approach** - 34% mobile growth validates the strategy.

### 5.2 Traffic Comparison

```
You: Compare this week's traffic to last week
```

**Example output:**

> ## Weekly Traffic Comparison
> **This Week (Feb 12-18)** vs **Last Week (Feb 5-11)**
>
> ### Overall Traffic
> | Metric | This Week | Last Week | Change |
> |--------|-----------|-----------|--------|
> | Total Users | 12,453 | 10,536 | +18.2% |
> | Sessions | 15,892 | 13,618 | +16.7% |
> | Pageviews | 42,156 | 34,478 | +22.3% |
> | Avg Session Duration | 3m 42s | 3m 25s | +8.3% |
> | Bounce Rate | 45.2% | 48.3% | -3.1% |
> | Pages/Session | 2.65 | 2.37 | +11.8% |
>
> ### Traffic Sources
> 1. **Organic Search:** 6,234 users (+28.4%)
> 2. **Direct:** 3,892 users (+12.1%)
> 3. **Referral:** 1,456 users (+5.3%)
> 4. **Social:** 871 users (+45.2%) - campaign impact
>
> ### Key Findings
> - Strong growth across all metrics
> - Social traffic spike correlates with recent campaign launch
> - Improved engagement indicates better content resonance
> - Monitor site performance as traffic scales

### 5.3 Conversion Analysis

```
You: Analyze which traffic sources convert best over the last 30 days
```

**Example output:**

> ## Conversion Analysis by Traffic Source (Last 30 Days)
>
> | Source | Users | Conversions | Rate | Avg Order Value |
> |--------|-------|-------------|------|-----------------|
> | Email | 1,245 | 156 | **12.5%** | $189 |
> | Paid Search | 1,890 | 132 | **7.0%** | $134 |
> | Organic Search | 15,234 | 892 | **5.9%** | $127 |
> | Referral | 3,456 | 198 | **5.7%** | $145 |
> | Direct | 8,923 | 445 | **5.0%** | $156 |
> | Social | 2,134 | 67 | **3.1%** | $98 |
>
> ### Key Insights
> - **Email is your best converter** (12.5% rate, highest AOV). Increase email frequency and add nurture campaigns.
> - **Paid search outperforms organic** (7.0% vs 5.9%). Consider increasing paid budget on top-performing keywords.
> - **Social traffic underperforms** (3.1% rate, lowest AOV). Refocus social on awareness rather than direct conversion.
> - **Organic drives most total revenue** ($113K, 46%) due to volume. Protect rankings.
>
> ### Recommendation
> Best ROI levers: scale email marketing, optimize paid search bids, and maintain organic SEO.

---

## Step 6: Schedule Reports with Missions

Use [Missions](https://docs.teamday.ai/guides/missions-api-guide) to automate report generation on a schedule.

### 6.1 Daily Report (Every Weekday at 9 AM)

```bash
curl -X POST https://cc.teamday.ai/api/v1/missions \
  -H "Authorization: Bearer $TEAMDAY_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Daily Analytics Report",
    "goal": "Generate a comprehensive daily analytics report for yesterday. Include traffic overview, acquisition breakdown, top pages, engagement metrics, and actionable recommendations. Compare to the previous day and flag any anomalies.",
    "icon": "📊",
    "spaceId": "rT4kWm9xBn2p",
    "characterId": "kP7mNx3vQw8j",
    "schedule": {
      "type": "cron",
      "value": "0 9 * * 1-5"
    }
  }'
```

Note: `characterId` is the agent's ID in the API.

### 6.2 Weekly Summary (Every Monday at 9 AM)

```bash
curl -X POST https://cc.teamday.ai/api/v1/missions \
  -H "Authorization: Bearer $TEAMDAY_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Weekly Analytics Summary",
    "goal": "Generate a comprehensive weekly analytics report comparing the past 7 days to the previous week. Include traffic trends, source breakdown, content performance, conversion analysis, and strategic recommendations.",
    "icon": "📈",
    "spaceId": "rT4kWm9xBn2p",
    "characterId": "kP7mNx3vQw8j",
    "schedule": {
      "type": "cron",
      "value": "0 9 * * 1"
    }
  }'
```

**Common cron schedules:**
- `0 9 * * 1-5` - Weekdays at 9 AM
- `0 9 * * 1` - Every Monday at 9 AM
- `0 9 1 * *` - First day of each month at 9 AM

You can also run a one-off report:

```bash
curl -X POST https://cc.teamday.ai/api/v1/missions \
  -H "Authorization: Bearer $TEAMDAY_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "February Traffic Deep Dive",
    "goal": "Analyze all February 2026 traffic data. Focus on organic search trends, top-performing content, and month-over-month growth. Provide strategic recommendations for March.",
    "spaceId": "rT4kWm9xBn2p",
    "characterId": "kP7mNx3vQw8j",
    "schedule": {
      "type": "once"
    }
  }'
```

---

## Extending the Agent

Once the core analytics reporter is working, you can extend it:

- **Slack notifications** - Add a Slack MCP server to the space so the agent can post reports directly to a channel.
- **Email delivery** - Configure an email MCP or use the agent to write reports to a shared file in the space.
- **Multi-property** - Store multiple GA property IDs as secrets and instruct the agent to report across properties.
- **Anomaly detection** - Schedule a mission that runs every 6 hours to check for traffic drops >20% or spikes >50% compared to the same period yesterday.

---

## Troubleshooting

### Authentication Failed (401)

- Verify your service account key JSON is valid and correctly stored in space secrets
- Ensure the GA4 Data API is enabled in your Google Cloud project
- Confirm the service account has Viewer access to the GA4 property

### No Data Returned

- Check that the GA4 property has data for the requested date range
- Verify the property ID is correct (it should be a number like `123456789`)
- Ensure you are querying a GA4 property, not a Universal Analytics property
- GA4 data can have a 24-48 hour processing delay for some metrics

### Data Doesn't Match the GA UI

- Ensure date ranges and timezones match exactly
- Account for data processing delay (some metrics take 24-48 hours to finalize)
- Check that no filters or segments are applied differently

### MCP Connection Timeout

- Verify network connectivity from the agent's sandbox
- Check Google Cloud API quotas (default: 25,000 requests/day)
- Ensure the MCP server process is running and configured correctly

---

## Cost Estimation

**Google Analytics Data API:**
- Free tier: 25,000 requests/day
- A typical daily report uses ~10 API requests
- Monthly cost: $0 (well within free tier)

**TeamDay agent execution:**
- Daily report: ~8,000 input tokens, ~3,000 output tokens
- Cost per report: ~$0.12
- Monthly (30 daily reports): ~$3.60

**Estimated total: ~$4/month** for daily automated analytics reporting.

---

## Next Steps

- [BigQuery Insights Example](https://docs.teamday.ai/examples/bigquery-insights) - Analyze historical data at scale
- [Code Review Bot](https://docs.teamday.ai/examples/code-review-bot) - Automate code reviews with AI
- [Creating Custom MCP Servers](https://docs.teamday.ai/guides/mcp-servers/creating-custom) - Build your own GA4 tools
- [Missions API Guide](https://docs.teamday.ai/guides/missions-api-guide) - Advanced scheduling and automation

## Resources

- [Google Analytics Data API docs](https://developers.google.com/analytics/devguides/reporting/data/v1)
- [GA4 Dimensions & Metrics reference](https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema)
- [TeamDay API Reference](https://docs.teamday.ai/api)
- [MCP Protocol Documentation](https://modelcontextprotocol.io/)
