GeminiでGoogle Analytics MCPサーバを使ってデータ分析をする

はじめに

Google Analytics MCPサーバは、Google AnalyticsのデータをModel Context Protocol(MCP)経由でLLMに提供する実験的なツールである。 これにより、Geminiなどの生成AIに自然言語でGoogle Analyticsのデータ分析を依頼できる。

本記事では、Google Analytics MCPサーバの設定からGeminiでの使用方法まで解説する。

環境

Windows 11 
WSL2 Ubuntu 24.04 LTS
Gemini CLI
Google Cloud Project
Google Analytics プロパティ

Google Analytics MCPサーバとは

Google Analytics MCPサーバは、以下のAPIを使用してLLM向けのツールを提供する。

提供されるツール

アカウント・プロパティ情報の取得

  • get_account_summaries: Google Analyticsのアカウント・プロパティ情報を取得
  • get_property_details: プロパティの詳細情報を返す
  • list_google_ads_links: プロパティのGoogle Ads連携リストを取得

コアレポートの実行

  • run_report: Data APIを使用してGoogle Analyticsレポートを実行
  • get_custom_dimensions_and_metrics: プロパティのカスタムディメンション・指標を取得

リアルタイムレポートの実行

  • run_realtime_report: リアルタイムレポートを実行

セットアップ手順

1. Python環境の構築

pipxをインストールする。

# WSL2 Ubuntu/Debian
sudo apt update
sudo apt install pipx

# pipxのパスを通す
pipx ensurepath
ログ
sudo apt install pipx                                                                ✔ │ 7s │ 21:19:58
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following packages were automatically installed and are no longer required:
  crack-common gyp libcares2 libdouble-conversion3 libgl1-amber-dri libglapi-mesa libjs-async libjs-events
  libjs-inherits libjs-is-typedarray libjs-prettify libjs-regenerate libjs-source-map libjs-sprintf-js
  libjs-typedarray-to-buffer libllvm17t64 liblttng-ust-common1t64 liblttng-ust-ctl5t64 liblttng-ust1t64
  libmd4c0 libnotify-bin libpcre2-16-0 libqt5core5t64 libqt5dbus5t64 libqt5gui5t64 libqt5network5t64
  libqt5qml5 libqt5qmlmodels5 libqt5quick5 libqt5svg5 libqt5waylandclient5 libqt5waylandcompositor5
  libqt5widgets5t64 libqt5x11extras5 libre2-10 libssl-dev libuv1-dev libxcb-damage0 libxcb-xinerama0
  libxcb-xinput0 mesa-utils-bin node-abbrev node-ampproject-remapping node-ansi-regex node-ansi-styles
  node-aproba node-are-we-there-yet node-arrify node-async node-async-each node-auto-bind
  node-babel-plugin-add-module-exports node-babel7-runtime node-balanced-match node-base64-js
  node-binary-extensions node-brace-expansion node-busboy node-camelcase node-caniuse-lite node-chownr
  node-chrome-trace-event node-ci-info node-cjs-module-lexer node-cli-boxes node-cli-cursor node-clone
  node-collection-visit node-color-convert node-color-name node-colors node-commander node-commondir
  node-concat-stream node-console-control-strings node-convert-source-map node-core-js node-core-js-pure
  node-core-util-is node-data-uri-to-buffer node-decompress-response node-deep-is node-defaults
  node-define-property node-delegates node-depd node-diff node-electron-to-chromium node-encoding
  node-end-of-stream node-err-code node-error-ex node-es-module-lexer node-escape-string-regexp
  node-eslint-utils node-eslint-visitor-keys node-esquery node-estraverse node-esutils node-events
  node-fancy-log node-fast-deep-equal node-fast-levenshtein node-fetch node-find-up node-flatted
  node-foreground-child node-fs-readdir-recursive node-fs-write-stream-atomic node-fs.realpath
  node-function-bind node-get-caller-file node-get-stream node-get-value node-glob node-globals node-got
  node-graceful-fs node-growl node-has-flag node-has-unicode node-has-value node-has-values
  node-hosted-git-info node-iconv-lite node-ieee754 node-iferr node-imurmurhash node-indent-string
  node-inflight node-inherits node-ini node-interpret node-ip node-ip-regex node-is-arrayish
  node-is-binary-path node-is-buffer node-is-descriptor node-is-extglob node-is-path-cwd node-is-plain-obj
  node-is-plain-object node-is-stream node-is-typedarray node-is-windows node-isarray node-isexe
  node-isobject node-js-tokens node-json-buffer node-json-parse-better-errors node-json-schema
  node-json-schema-traverse node-json-stable-stringify node-jsonify node-jsonparse node-kind-of node-levn
  node-loader-runner node-locate-path node-lodash-packages node-lowercase-keys node-lru-cache
  node-map-visit node-memfs node-merge-stream node-mimic-response node-minimatch node-minimist
  node-minipass node-mute-stream node-n3 node-negotiator node-npm-run-path node-object-inspect
  node-object-visit node-once node-optimist node-optionator node-osenv node-p-cancelable node-p-limit
  node-p-locate node-p-map node-pascalcase node-path-dirname node-path-exists node-path-is-absolute
  node-path-is-inside node-path-type node-pify node-pkg-dir node-postcss-value-parser node-prelude-ls
  node-process-nextick-args node-promise-inflight node-promise-retry node-promzard node-prr node-pump
  node-punycode node-quick-lru node-randombytes node-read node-readable-stream node-rechoir
  node-regenerator-runtime node-regenerator-transform node-regexpp node-regjsgen node-repeat-string
  node-require-directory node-require-from-string node-resolve node-resolve-cwd node-resolve-from
  node-restore-cursor node-resumer node-retry node-run-queue node-safe-buffer node-serialize-javascript
  node-set-blocking node-set-immediate-shim node-shebang-command node-shebang-regex node-shell-quote
  node-signal-exit node-slash node-slice-ansi node-source-list-map node-source-map node-spdx-correct
  node-spdx-exceptions node-spdx-expression-parse node-spdx-license-ids node-sprintf-js node-ssri
  node-stack-utils node-string-decoder node-strip-bom node-supports-color node-tapable node-terser
  node-text-table node-through node-time-stamp node-to-fast-properties node-tslib node-type-check
  node-typedarray node-typedarray-to-buffer node-undici node-unicode-canonical-property-names-ecmascript
  node-unicode-match-property-value-ecmascript node-unicode-property-aliases-ecmascript node-unset-value
  node-uri-js node-util-deprecate node-uuid node-v8flags node-validate-npm-package-license node-wcwidth.js
  node-webpack-sources node-wordwrap node-wrappy node-write-file-atomic node-xtend node-y18n node-yallist
  node-yaml nodejs-doc qt5-gtk-platformtheme qttranslations5-l10n qtwayland5 xbitmaps
Use 'sudo apt autoremove' to remove them.
The following additional packages will be installed:
  python3-argcomplete python3-packaging python3-pip-whl python3-platformdirs python3-setuptools-whl
  python3-userpath python3-venv python3.12-venv
The following NEW packages will be installed:
  pipx python3-argcomplete python3-packaging python3-pip-whl python3-platformdirs python3-setuptools-whl
  python3-userpath python3-venv python3.12-venv
0 upgraded, 9 newly installed, 0 to remove and 8 not upgraded.
Need to get 3313 kB of archives.
After this operation, 6665 kB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://archive.ubuntu.com/ubuntu noble-updates/universe amd64 python3-pip-whl all 24.0+dfsg-1ubuntu1.2 [1703 kB]
Get:2 http://archive.ubuntu.com/ubuntu noble-updates/universe amd64 python3-setuptools-whl all 68.1.2-2ubuntu1.2 [716 kB]
Get:3 http://archive.ubuntu.com/ubuntu noble-updates/universe amd64 python3.12-venv amd64 3.12.3-1ubuntu0.7 [5680 B]
Get:4 http://archive.ubuntu.com/ubuntu noble-updates/universe amd64 python3-venv amd64 3.12.3-0ubuntu2 [1034 B]
Get:5 http://archive.ubuntu.com/ubuntu noble-updates/universe amd64 python3-argcomplete all 3.1.4-1ubuntu0.1 [33.8 kB]
Get:6 http://archive.ubuntu.com/ubuntu noble/main amd64 python3-packaging all 24.0-1 [41.1 kB]
Get:7 http://archive.ubuntu.com/ubuntu noble/main amd64 python3-platformdirs all 4.2.0-1 [16.1 kB]
Get:8 http://archive.ubuntu.com/ubuntu noble/universe amd64 python3-userpath all 1.9.1-1 [9416 B]
Get:9 http://archive.ubuntu.com/ubuntu noble/universe amd64 pipx all 1.4.3-1 [787 kB]
Fetched 3313 kB in 4s (917 kB/s)
Selecting previously unselected package python3-pip-whl.
(Reading database ... 114626 files and directories currently installed.)
Preparing to unpack .../0-python3-pip-whl_24.0+dfsg-1ubuntu1.2_all.deb ...
Unpacking python3-pip-whl (24.0+dfsg-1ubuntu1.2) ...
Selecting previously unselected package python3-setuptools-whl.
Preparing to unpack .../1-python3-setuptools-whl_68.1.2-2ubuntu1.2_all.deb ...
Unpacking python3-setuptools-whl (68.1.2-2ubuntu1.2) ...
Selecting previously unselected package python3.12-venv.
Preparing to unpack .../2-python3.12-venv_3.12.3-1ubuntu0.7_amd64.deb ...
Unpacking python3.12-venv (3.12.3-1ubuntu0.7) ...
Selecting previously unselected package python3-venv.
Preparing to unpack .../3-python3-venv_3.12.3-0ubuntu2_amd64.deb ...
Unpacking python3-venv (3.12.3-0ubuntu2) ...
Selecting previously unselected package python3-argcomplete.
Preparing to unpack .../4-python3-argcomplete_3.1.4-1ubuntu0.1_all.deb ...
Unpacking python3-argcomplete (3.1.4-1ubuntu0.1) ...
Selecting previously unselected package python3-packaging.
Preparing to unpack .../5-python3-packaging_24.0-1_all.deb ...
Unpacking python3-packaging (24.0-1) ...
Selecting previously unselected package python3-platformdirs.
Preparing to unpack .../6-python3-platformdirs_4.2.0-1_all.deb ...
Unpacking python3-platformdirs (4.2.0-1) ...
Selecting previously unselected package python3-userpath.
Preparing to unpack .../7-python3-userpath_1.9.1-1_all.deb ...
Unpacking python3-userpath (1.9.1-1) ...
Selecting previously unselected package pipx.
Preparing to unpack .../8-pipx_1.4.3-1_all.deb ...
Unpacking pipx (1.4.3-1) ...
Setting up python3-setuptools-whl (68.1.2-2ubuntu1.2) ...
Setting up python3-pip-whl (24.0+dfsg-1ubuntu1.2) ...
Setting up python3-platformdirs (4.2.0-1) ...
Setting up python3-packaging (24.0-1) ...
Setting up python3-argcomplete (3.1.4-1ubuntu0.1) ...
Setting up python3-userpath (1.9.1-1) ...
Setting up python3.12-venv (3.12.3-1ubuntu0.7) ...
Setting up python3-venv (3.12.3-0ubuntu2) ...
Setting up pipx (1.4.3-1) ...
Processing triggers for man-db (2.12.0-4build2) ...
ログ2
 ~  pipx ensurepath                                                                      ✔ │ 8s │ 21:20:10
/home/kbushi/.local/bin is already in PATH.

⚠️  All pipx binary directories have been added to PATH. If you are sure you want to proceed, try again
with the '--force' flag.

Otherwise pipx is ready to go! ✨ 🌟 ✨

2. gCloud CLIをインストールする

curl -O https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/google-cloud-cli-linux-x86_64.tar.gz
tar -xf google-cloud-cli-linux-x86_64.tar.gz
./google-cloud-sdk/install.sh
./google-cloud-sdk/bin/gcloud init

3. Google Cloud APIの有効化

Google Cloud プロジェクトで以下のAPIを有効にする。

  1. Google Analytics Admin API
  2. Google Analytics Data API

4. OAuthクライアントIDの発行

Google Analytics Admin API にアクセスし、「管理」を選択する。

publish-oauth-id-01

認証情報を作成→「OAuthクライアントID」を選択する

publish-oauth-id-02
publish-oauth-id-03

「アプリケーションの種類」と「名前」を入力して作成をする

今回は、「デスクトップアプリ」、「gemini」とした。

publish-oauth-id-04

JSONをダウンロードする

publish-oauth-id-05

5. 認証情報の設定

Application Default Credentials(ADC)を設定する。 認証情報にはGoogle Analytics読み取り専用スコープが必要である。

https://www.googleapis.com/auth/analytics.readonly

今回は、OAuth クライアントを使用した認証 を使ってログインをした。

OAuth クライアントを使用した認証

YOUR_CLIENT_JSON_FILE は 先ほど発行したOAuthクライアントIDのJSONファイルのパスを指定する。

gcloud auth application-default login \
  --scopes https://www.googleapis.com/auth/analytics.readonly,https://www.googleapis.com/auth/cloud-platform \
  --client-id-file=YOUR_CLIENT_JSON_FILE

6. Geminiの設定

Gemini CLIのインストール

以下の記事で既にインストール済み
WSLでGemini CLIを使ってみる

MCP設定ファイルの作成

~/.gemini/settings.jsonを作成・編集し、MCPサーバを追加する。

{
  "mcpServers": {
    "analytics-mcp": {
      "command": "pipx",
      "args": [
        "run",
        "--spec",
        "git+https://github.com/googleanalytics/google-analytics-mcp.git",
        "google-analytics-mcp"
      ]
    }
  }
}

環境変数の設定(オプション)

特定の認証情報を常に使用したい場合は、環境変数を設定する。

{
  "mcpServers": {
    "analytics-mcp": {
      "command": "pipx",
      "args": [
        "run",
        "--spec",
        "git+https://github.com/googleanalytics/google-analytics-mcp.git",
        "google-analytics-mcp"
      ],
      "env": {
        "GOOGLE_APPLICATION_CREDENTIALS": "PATH_TO_ADC_JSON",
        "GOOGLE_CLOUD_PROJECT": "YOUR_PROJECT_ID"
      }
    }
  }
}

実際に使ってみる

MCPサーバの確認

Gemini CLIを起動し、/mcpと入力する。 analytics-mcpがリストに表示されることを確認する。

gemini
/mcp

下記の表示となればOK

ℹ Configured MCP servers:

  🟢 analytics-mcp - Ready (6 tools)
    - get_account_summaries
    - list_google_ads_links
    - get_property_details
    - get_custom_dimensions_and_metrics
    - run_realtime_report
    - run_report

サンプルプロンプト

サーバの機能確認

analytics-mcpサーバは何ができますか?

プロパティ情報の取得

名前に'xyz'が含まれるGoogle Analyticsプロパティの詳細を教えてください

データ分析

過去180日間でGoogle Analyticsプロパティの最も人気のあるイベントは何ですか?

ユーザー分析

過去6か月間のユーザーの大部分はログインしていましたか?

設定確認

プロパティのカスタムディメンションとカスタム指標は何ですか?

Google Analytics MCPを使ってみる

本日のアクティブユーザー数を取得

プロンプト

Analytics MCPサーバを使って今日のアクセス数を教えてください。

結果
> Analytics MCPサーバを使って今日のアクセス数を教えてください。

✦ Google AnalyticsのプロパティIDを教えていただけますか?


  また、「アクセス数」として、以下のどの指標を確認したいですか?
   - activeUsers:アクティブユーザー数
   - sessions:セッション数
   - screenPageViews:ページビュー数

> [プロパティID]

✦ 承知いたしました。どの指標でレポートを生成しますか?

> アクティブユーザー数

✦ 承知いたしました。本日のアクティブユーザー数を取得します。
 ╭───────────────────────────────────────────────────────────────────────────────────────────────────╮
 │ ✔  run_report (analytics-mcp MCP Server) {"metrics":["activeUsers"],"dimensions":["date"],"prope… │
 │                                                                                                   │
 │    {                                                                                              │
 │      "dimension_headers": [                                                                       │
 │        {                                                                                          │
 │          "name": "date"                                                                           │
 │        }                                                                                          │
 │      ],                                                                                           │
 │      "metric_headers": [                                                                          │
 │        {                                                                                          │
 │          "name": "activeUsers",                                                                   │
 │          "type_": "TYPE_INTEGER"                                                                  │
 │        }                                                                                          │
 │      ],                                                                                           │
 │      "rows": [                                                                                    │
 │        {                                                                                          │
 │          "dimension_values": [                                                                    │
 │            {                                                                                      │
 │              "value": "20250816"                                                                  │
 │            }                                                                                      │
 │          ],                                                                                       │
 │          "metric_values": [                                                                       │
 │            {                                                                                      │
 │              "value": "53"                                                                        │
 │            }                                                                                      │
 │          ]                                                                                        │
 │        }                                                                                          │
 │      ],                                                                                           │
 │      "row_count": 1,                                                                              │
 │      "metadata": {                                                                                │
 │        "currency_code": "JPY",                                                                    │
 │        "time_zone": "Asia/Tokyo",                                                                 │
 │        "data_loss_from_other_row": false,                                                         │
 │        "sampling_metadatas": []                                                                   │
 │      },                                                                                           │
 │      "kind": "analyticsData#runReport",                                                           │
 │      "totals": [],                                                                                │
 │      "maximums": [],                                                                              │
 │      "minimums": []                                                                               │
 │    }                                                                                              │
 ╰───────────────────────────────────────────────────────────────────────────────────────────────────╯
✦ 本日のアクティブユーザー数は53人です。

1週間のアクティブユーザ数

1週間分のアクティブユーザ数のグラフをつくってください

結果
> 1週間分のアクティブユーザ数のグラフをつくってください

✦ はい、過去1週間分のアクティブユーザー数を取得します。
 ╭───────────────────────────────────────────────────────────────────────────────────────────────────╮
 │ ✔  run_report (analytics-mcp MCP Server) {"property_id":"[プロパティID]","date_ranges":[{"end_date":"… │
 │                                                                                                   │
 │    ... first 20 lines hidden ...                                                                  │
 │            {                                                                                      │
 │              "value": "275"                                                                       │
 │            }                                                                                      │
 │          ]                                                                                        │
 │        },                                                                                         │
 │        {                                                                                          │
 │          "dimension_values": [                                                                    │
 │            {                                                                                      │
 │              "value": "20250814"                                                                  │
 │            }                                                                                      │
 │          ],                                                                                       │
 │          "metric_values": [                                                                       │
 │            {                                                                                      │
 │              "value": "216"                                                                       │
 │            }                                                                                      │
 │          ]                                                                                        │
 │        },                                                                                         │
 │        {                                                                                          │
 │          "dimension_values": [                                                                    │
 │            {                                                                                      │
 │              "value": "20250813"                                                                  │
 │            }                                                                                      │
 │          ],                                                                                       │
 │          "metric_values": [                                                                       │
 │            {                                                                                      │
 │              "value": "203"                                                                       │
 │            }                                                                                      │
 │          ]                                                                                        │
 │        },                                                                                         │
 │        {                                                                                          │
 │          "dimension_values": [                                                                    │
 │            {                                                                                      │
 │              "value": "20250812"                                                                  │
 │            }                                                                                      │
 │          ],                                                                                       │
 │          "metric_values": [                                                                       │
 │            {                                                                                      │
 │              "value": "199"                                                                       │
 │            }                                                                                      │
 │          ]                                                                                        │
 │        },                                                                                         │
 │        {                                                                                          │
 │          "dimension_values": [                                                                    │
 │            {                                                                                      │
 │              "value": "20250811"                                                                  │
 │            }                                                                                      │
 │          ],                                                                                       │
 │          "metric_values": [                                                                       │
 │            {                                                                                      │
 │              "value": "85"                                                                        │
 │            }                                                                                      │
 │          ]                                                                                        │
 │        },                                                                                         │
 │        {                                                                                          │
 │          "dimension_values": [                                                                    │
 │            {                                                                                      │
 │              "value": "20250809"                                                                  │
 │            }                                                                                      │
 │          ],                                                                                       │
 │          "metric_values": [                                                                       │
 │            {                                                                                      │
 │              "value": "76"                                                                        │
 │            }                                                                                      │
 │          ]                                                                                        │
 │        },                                                                                         │
 │        {                                                                                          │
 │          "dimension_values": [                                                                    │
 │            {                                                                                      │
 │              "value": "20250810"                                                                  │
 │            }                                                                                      │
 │          ],                                                                                       │
 │          "metric_values": [                                                                       │
 │            {                                                                                      │
 │              "value": "74"                                                                        │
 │            }                                                                                      │
 │          ]                                                                                        │
 │        },                                                                                         │
 │        {                                                                                          │
 │          "dimension_values": [                                                                    │
 │            {                                                                                      │
 │              "value": "20250816"                                                                  │
 │            }                                                                                      │
 │          ],                                                                                       │
 │          "metric_values": [                                                                       │
 │            {                                                                                      │
 │              "value": "54"                                                                        │
 │            }                                                                                      │
 │          ]                                                                                        │
 │        }                                                                                          │
 │      ],                                                                                           │
 │      "row_count": 8,                                                                              │
 │      "metadata": {                                                                                │
 │        "currency_code": "JPY",                                                                    │
 │        "time_zone": "Asia/Tokyo",                                                                 │
 │        "data_loss_from_other_row": false,                                                         │
 │        "sampling_metadatas": []                                                                   │
 │      },                                                                                           │
 │      "kind": "analyticsData#runReport",                                                           │
 │      "totals": [],                                                                                │
 │      "maximums": [],                                                                              │
 │      "minimums": []                                                                               │
 │    }                                                                                              │
 ╰───────────────────────────────────────────────────────────────────────────────────────────────────╯
✦ グラフを作成する機能はありませんが、過去1週間分のアクティブユーザー数はこちらです。


  | 日付 | アクティブユーザー数 |
  |---|---|
  | 2025/08/15 | 275 |
  | 2025/08/14 | 216 |
  | 2025/08/13 | 203 |
  | 2025/08/12 | 199 |
  | 2025/08/11 | 85 |
  | 2025/08/09 | 76 |
  | 2025/08/10 | 74 |
  | 2025/08/16 | 54 |

トラブルシューティング

認証エラーが発生する場合

  1. ADCが正しく設定されているか確認
  2. 必要なスコープが含まれているか確認
  3. Google Analytics プロパティへのアクセス権限があるか確認

MCPサーバが表示されない場合

  1. pipxが正しくインストールされているか確認
  2. ~/.gemini/settings.jsonの構文が正しいか確認
  3. ネットワーク接続を確認

レポート実行でエラーが出る場合

  1. プロパティIDが正しいか確認
  2. 指定したディメンション・指標が存在するか確認
  3. 日付範囲が有効な範囲内か確認

参考

おわりに

Google Analytics MCPサーバを使ってみると、Geminiから自然言語で色々な形で取得できるので楽になった。 普通にGeminiに「今月のアクセス数教えて」って聞くだけで、データを取ってきてくれるのはかなり便利…!

今まではGoogle Analyticsの管理画面を開いて、あれこれクリックしながらデータを探していたけど、これなら質問するだけでOKなのが良い。
特に複雑な分析をしたいときに、LLMがデータの意味を解釈してくれるのがありがたい。

まだ導入したばかりなので、色々と不慣れなところもあるがデータ分析の敷居がグッと下がるので、これから少しずつ使っていきたい。
後、OAuthクライアントIDとか発行したけど、サービスアカウントのキー発行のやり方もあるようだった。
今回は、まあ安全で簡単なやり方をしたがこのやり方でよかったのかも含めて後で見直そうかな。

Hugo で構築されています。
テーマ StackJimmy によって設計されています。