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
  • 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
  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:

gcloud services enable analyticsdata.googleapis.com

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 > 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
  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:

curl -X POST https://us.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:

curl -X POST https://us.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

curl -X POST https://us.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:

{
  "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

curl -X PATCH https://us.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:

curl -X POST https://us.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:

curl -X PATCH https://us.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. See the Creating Custom MCP Servers 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:

curl -X POST https://us.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

MetricTodayvs Yesterday
Users1,834+12%
New Users1,245+22%
Sessions2,367+15%
Pageviews6,892+18%
Avg Session Duration3m 48s+5%
Bounce Rate43.2%-2.1%

Acquisition Breakdown

SourceUsers% of TotalChange
Organic Search89248.6%+15%
Direct56730.9%+8%
Referral23412.8%+23%
Social985.3%+45%
Email432.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

MetricThis WeekLast WeekChange
Total Users12,45310,536+18.2%
Sessions15,89213,618+16.7%
Pageviews42,15634,478+22.3%
Avg Session Duration3m 42s3m 25s+8.3%
Bounce Rate45.2%48.3%-3.1%
Pages/Session2.652.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)

SourceUsersConversionsRateAvg Order Value
Email1,24515612.5%$189
Paid Search1,8901327.0%$134
Organic Search15,2348925.9%$127
Referral3,4561985.7%$145
Direct8,9234455.0%$156
Social2,134673.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 to automate report generation on a schedule.

6.1 Daily Report (Every Weekday at 9 AM)

curl -X POST https://us.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"
    }
  }'

6.2 Weekly Summary (Every Monday at 9 AM)

curl -X POST https://us.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:

curl -X POST https://us.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

Resources