← Back to blog Analytics

How to Connect Google Analytics to Gemini CLI: Ask Your GA4 Data Anything

Julià Pujol July 27, 2025 9 min read
Share
How to Connect Google Analytics to Gemini CLI: Ask Your GA4 Data Anything

The official MCP GA4 server documentation can be too technical for users with minimal coding experience. This guide provides a clear, step-by-step walkthrough to make the setup process simple and straightforward.

The Google Analytics 4 interface is powerful, but it’s not always fast. Answering a simple question often requires a multi-click journey through reports and explorations. For teams that move at the speed of thought, this friction is a significant bottleneck.

What if you could just… ask?

This guide provides a definitive, step-by-step walkthrough for creating a powerful conversational analytics assistant. We will securely connect the Gemini CLI to your live GA4 data using an efficient, on-demand architecture. The end result is a tool that allows you to open a terminal and ask complex questions in plain English, getting immediate and accurate answers.

The Business Case: Why a Conversational Interface?

Before diving into the technical setup, let’s frame the value:

1) Speed to Insight: Get immediate answers to tactical questions. No more clicking, configuring, and waiting for reports to load. This is invaluable during meetings or when a quick data point is needed to inform a decision.

2) Democratizing Data: A natural language interface empowers team members who aren’t GA4 power users to self-serve their data needs, freeing up your analytics team for more strategic, deep-dive analysis.

3) Frictionless Exploration: Conversational queries encourage a more fluid, iterative approach to data exploration. You can follow your curiosity, asking follow-up questions and digging into trends without losing your analytical flow in a complex UI.

The Architecture: An On-Demand, “Serverless” Approach

Our approach uses the two key components from the official documentation, but adds a third one: a custom script to create a more automated bridge between the Gemini CLI and your GA4 property.

1) Gemini CLI: This will be our conversational interface. Think of it like accessing the Gemini web interface, but directly in your terminal. It has the same powerful natural language capabilities, with the key difference that it’s connected to your local computer and can be configured to use external tools.

2) Google Analytics MCP: The open-source MCP GA4 project that contains a pre-built library of functions that know how to securely query the GA4 Admin and Data APIs.

3) Our “On-Demand” Client Script: This is the magic glue. Instead of running a persistent server to host the GA4 tools (as suggested in the official documentation), we will write a simple Python script that spins up the tool server, executes a single query, and shuts down instantly.

Why use this on-demand script instead of the official “always-on” server method? It’s simpler for personal use, you don’t have to manually start and stop a local server, and the script handles the server connection automatically for each query you make.

Part 1: Getting the basics

Please note that the commands provided in this walkthrough are for a macOS environment. The steps for Windows are very similar, requiring only minor changes to the commands. For any specific translations you might need, your favorite AI assistant can easily provide the Windows equivalent ;)

Install Homebrew (If you don’t have it): Open your terminal and run this one-line command (to fix “permission denied” errors – if asked to, run “sudo chown -R $USER /usr/local/var/homebrew” to grant your current user ownership of that Homebrew directory.):

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

Install All Required Tools: Once Homebrew is ready, this command block will install (if you don’t already have them) Git, the correct Python version (3.10), the Google Cloud SDK, the latest Node.js version, and the Gemini CLI:

# Install Git, Python 3.10, and the Google Cloud SDK
brew install git
brew install python@3.10
brew install --cask google-cloud-sdk
brew install node

# Install the Gemini CLI
npm install -g @google/gemini-cli

Authenticate with GCP, Select Project & Create Service Account: With everything installed, you need to authorize the tools to use your Google Cloud Service Account:

# 1) Authenticate gcloud
gcloud auth login

# List your GCP projects (After running gcloud projects list, identify the YOUR_PROJECT_ID shown in the first (leftmost) column that corresponds to the project you want to work with, and use that value in your subsequent commands.)
gcloud projects list

# 2) Set your active project (replace YOUR_PROJECT_ID)
gcloud config set project YOUR_PROJECT_ID

# 3) Export for downstream tools (replace YOUR_PROJECT_ID)
export GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID"

# 4) Create a service account for GA4 access
gcloud iam service-accounts create ga4-mcp-server \
  --display-name="GA4 MCP On-Demand Server"

# 5) Grant to the service account GA4 and cloud rights 
gcloud projects add-iam-policy-binding YOUR_PROJECT_ID \
  --member="serviceAccount:ga4-mcp-server@YOUR_PROJECT_ID.iam.gserviceaccount.com" \
  --role="roles/analytics.viewer"

# 6) Enable Gemini API in your Google Cloud project
gcloud services enable cloudaicompanion.googleapis.com --project=YOUR_PROJECT_ID

# 7) Enable Google Analytics Admin API in your Google Cloud project
gcloud services enable analyticsadmin.googleapis.com --project=YOUR_PROJECT_ID

# 8) Enable Google Analytics Reporting API in your Google Cloud project
gcloud services enable analyticsdata.googleapis.com --project=YOUR_PROJECT_ID

Grant the Service Account acces to your GA4 property/s: To grant your new service account read‑only access to your Analytics data:

1) In the GA4 web interface, click the Admin gear icon (bottom‑left).

2) Under the Property column, select Property Access Management.

3) Click the + button and choose Add users.

4) In the Email address field, paste your service account’s email (for example: ga4-mcp-server@YOUR_PROJECT_ID. iam.gserviceaccount.com).

5) Under Roles, check Viewer.

6) Click Add to save.

Part 2: Building the assistant

Now, we’ll set up the project directory and apply the new script and some critical fixes to the source code.

Create a Project Directory:

mkdir ~/gemini-ga4-assistant 

Clone locally the GA4 MCP repo & Download the Service Account Key you’ve created before:

git clone https://github.com/googleanalytics/google-analytics-mcp.git
cd google-analytics-mcp
gcloud iam service-accounts keys create ga4-credentials.json --iam-account="ga4-mcp-server@YOUR_PROJECT_ID.iam.gserviceaccount.com"

Patch the License Format: The project’s configuration has an outdated license format that will cause installation to fail. Run this command to fix it.

sed -i.bak 's/license = "Apache-2.0"/license = { text = "Apache-2.0" }/' pyproject.toml

Create & Activate Virtual Environment:

python3.10 -m venv .venv 
source .venv/bin/activate

Install Dependencies:

pip install .

Create our light-way script to communciate with GA4 MCP:

cat << 'EOF' > ga4_tool.py
import asyncio
import sys
from pathlib import Path
import json

sys.path.append(str(Path(__file__).parent.resolve()))
from mcp.client.session import ClientSession
from mcp.client.stdio import stdio_client, StdioServerParameters

CREDENTIALS_FILE = "../ga4-credentials.json"

async def query_ga4(prompt_args: list[str]):
    mcp_root = Path(__file__).parent.resolve()
    credentials_path = mcp_root.parent / "google-analytics-mcp/ga4-credentials.json"
    venv_python_path = mcp_root / ".venv" / "bin" / "python"

    if not venv_python_path.exists():
        print(f"Error: Python virtual environment not found at {venv_python_path}")
        return
    if not credentials_path.exists():
        print(f"Error: Credentials file not found at {credentials_path}. Ensure it's in the 'gemini-ga4-assistant' root folder.")
        return

    server_params = StdioServerParameters(
        command=str(venv_python_path),
        args=["-m", "analytics_mcp.server"],
        cwd=mcp_root,
        env={"GOOGLE_APPLICATION_CREDENTIALS": str(credentials_path)},
    )

    try:
        async with stdio_client(server_params) as (read, write):
            async with ClientSession(read, write) as session:
                await session.initialize()
                if not prompt_args:
                    print("Available tools:")
                    list_tools_result = await session.list_tools()
                    for tool in list_tools_result.tools: print(f"- {tool.name}: {tool.description}")
                    return

                tool_name, arg_pairs = prompt_args[0], prompt_args[1:]
                if len(arg_pairs) % 2 != 0:
                    print(f"Error: Arguments for '{tool_name}' must be in key-value pairs.")
                    return
                arguments = {arg_pairs[i]: arg_pairs[i+1] for i in range(0, len(arg_pairs), 2)}
                result = await session.call_tool(tool_name, arguments=arguments if arguments else None)

                if result.isError:
                    print(f"Tool Error: The tool '{tool_name}' returned an error. Please check the stderr output for details.")
                elif result.structuredContent:
                    print(json.dumps(result.structuredContent, indent=2))
                else:
                    print(f"Tool '{tool_name}' executed successfully with no structured output.")
    except Exception as e:
        print(f"A critical error occurred: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    asyncio.run(query_ga4(sys.argv[1:]))
EOF

Part 3: Using Your New GA4 Assistant

Your on-demand assistant is ready! Just run Gemni CLI:

gemini

When prompted to authenticate, select the Login with Google option for the easiest method. A new browser window will open, allowing you to sign in with your standard Google account credentials to continue:

Once the chat prompt appears, a great first step is to ask it to list all the Google Analytics properties you have access to: (example: “Use the ga4_tool.py script to list all the Google Analytics properties I have access to“):

Now you can ask your new assistant any question you’d like. You can request specific reports, like a table of conversions by channel with absolute and percentage values, or the average session duration by campaign. But don’t stop there; ask for strategic advice on how to improve user journeys, identify where users are dropping off, or how to best distribute your budget.

The AI generated insights provide a fantastic strategic starting point by using your complete GA4 data context, ensuring you’re never facing a blank page. However, these insights should be treated as a foundation, not a final answer. For the best results, we strongly recommend using the Gemini Pro model, as there is a significant difference in quality compared to the Flash model.

Our Thoughts: From Local Assistant to Team Wide Platform

While our on-demand, “serverless-style” approach is perfect and straightforward for individual use on a local machine, the persistent server model described in the official documentation is the foundation for scaling this solution.

By containerizing the mcp-server-ga4 and deploying it to a cloud service like Google Cloud Run, you could create a secure, centralized API endpoint. This would allow your entire team or even other automated applications to make authenticated requests to your GA4 data, transforming this personal assistant into a robust, shared analytics service.

Of course, the quality of these insights depends entirely on the quality of your data. This requires a Google Analytics 4 setup that you can trust, built on tracking best practices.

Ready to take the next step? If you’d like to scale this solution for your entire team, or if you need help building a GA4 data foundation you can truly rely on, get in touch with us!

If you would rather have this working for your whole team, with the semantic layer that keeps every answer consistent, that is what our conversational analytics service builds.

Get in touch

Questions? A project in mind? Talk to us.

  • Analytics, tracking or data questions: real humans answer, fast
  • Enterprise: audits, sGTM, GA4 360, BigQuery and MMM engagements
  • Tell us your stack and goals, we reply within one business day