NRIネットコム社員が様々な視点で、日々の気づきやナレッジを発信するメディアです

注目のタグ

    【Gemini Enterprise × GA】Cloud Run で Google アナリティクス MCP サーバーを構築する方法

    本記事は  Googleウィーク  4日目の記事です。
    🌐  3日目  ▶▶ 本記事 ▶▶  5日目  💻

    こんにちは、デジタルマーケティング事業に携わっている中山です。

    本記事では、Google アナリティクス MCP サーバーを Google Cloud の Cloud Run 上に構築し、Gemini Enterprise から利用できるようにする方法について解説します。

    今回使用する Google アナリティクス MCP サーバーは、公式リポジトリではローカル環境からの利用を想定した stdio 方式で提供されています。
    一方で、Cloud Run は stdio トランスポートによる MCP サーバーのホスティングには対応しておらず、リモート接続には Streamable HTTP などの HTTP ベースのトランスポートが必要になります。

    そこで本記事では、公式の Google アナリティクス MCP サーバーをベースに、Gemini Enterprise から HTTPS 経由で接続できるよう構成を変更し、Cloud Run 上で利用できるようにする方法をご紹介します。

    ※本記事では、Gemini Enterprise との接続に OAuth を使用し、Cloud Run への未認証アクセスを許可しない構成で検証しています。実際の業務や本番環境で利用する場合は、本記事で紹介する設定に加えて、組織のセキュリティポリシーに基づく認証・認可、権限管理、監視などの検討が必要です。

    本記事の目次は、下記のとおりです。

    1. はじめに

    本構成では、Gemini Enterprise から MCP サーバーへの接続と、MCP サーバーから Google アナリティクス API へのアクセスで、異なる認証・権限を使用します。

    Gemini Enterprise 側に設定する OAuth 2.0 は、Gemini Enterprise からカスタム MCP サーバーへ接続する際の認証設定として使用します。一方、Google アナリティクス API へのアクセスには、Cloud Run の実行サービスアカウントの認証情報が使用されます。そのため、Cloud Run の実行サービスアカウントには、データを参照する必要がある Google アナリティクスのアカウントまたはプロパティに対して、「閲覧者」権限を付与します。

    なお、Gemini Enterprise で OAuth 認証を行ったユーザーの Google アナリティクス権限が、そのまま Google アナリティクス API の呼び出しに引き継がれる構成ではありません。
    MCP サーバーを利用できるユーザーは、Cloud Run の実行サービスアカウントに閲覧権限が付与された Google アナリティクスのデータへアクセスできるため、実行サービスアカウントへ付与する権限は必要最小限とするようにしましょう。

    Google アナリティクス MCP サーバーとは

    Google 社が公開している Google アナリティクス MCP サーバーは、MCP(Model Context Protocol)を介して、Google アナリティクスのデータを Gemini Enterprise などの LLM から利用できるようにする仕組みです。
    これを使用することで、自然言語によるデータの取得や、Google アナリティクスのデータへアクセスできるカスタムエージェントの構築が可能になります。
    Google アナリティクス MCP サーバーの概要や利用例については、次の Google 公式ドキュメントを参照してください。

    developers.google.com

    2. Google アナリティクス MCP サーバーを構築する

    ここからは、Google アナリティクス MCP サーバーを Cloud Run 上に構築する手順に入ります。

    事前に、次の準備を完了してください。

    • Google Cloud プロジェクトを作成する
    • Gemini Enterprise の利用環境を確認する

    ※Cloud Run へデプロイするユーザーには、構成に応じて Cloud Run 管理者とサービスアカウント ユーザーなどの権限が必要です。

    2-1. OAuth 2.0 クライアントを作成する

    Gemini Enterprise と Google アナリティクス MCP サーバーの間で OAuth 2.0 認証を行うため、OAuth 2.0 クライアントを作成します。 Google Cloud コンソールから、[Google Auth Platform] を開き、OAuth 2.0 クライアント ID を作成します。 後ほど Gemini Enterprise でデータストアを作成するときに使用するので、以下の値を控えておいてください。 ①クライアント ID

    ②OAuth クライアントの作成時には、Gemini Enterprise のカスタム MCP サーバーで OAuth 2.0 認証を利用する場合のリダイレクト先として、「承認済みのリダイレクト URI」へ以下を登録します。

     https://vertexaisearch.cloud.google.com/oauth-redirect

    ③クライアント シークレット

    2-2. Cloud Run で実行するためのファイルを準備する

    冒頭で述べたように、Google アナリティクス MCP サーバーの公式リポジトリは、ローカル環境での利用を想定した stdio 方式で構成されています。
    一方、Gemini Enterprise のカスタム MCP データストアの接続では、Streamable HTTP 方式で接続できる HTTPS エンドポイントが必要です。

    そのため、Google アナリティクス MCP サーバーを Cloud Run 上で動作させるため、Google アナリティクス MCP サーバーの公式リポジトリを使用しつつ、今回は以下の表のファイルを追加・修正しています。

    ファイル名 使用用途
    Dockerfile Google アナリティクス MCP サーバーを Cloud Run 上で実行するためのコンテナ イメージを構築する設定ファイル。
    cloudrun_server.py Cloud Run 上で MCP サーバーを実行し、Gemini Enterprise から HTTPS 経由でアクセスできるようにするためのエントリ ポイント ファイル。
    coordinator.py 公式の Google アナリティクス MCP サーバーが提供するツールを調整するファイル。
    deploy.sh Google アナリティクス MCP サーバーを Cloud Run にデプロイするためのシェル スクリプト。

    各ファイルの詳細と役割は次のとおりです。

    • Dockerfile
    FROM python:3.12-slim
    
    ARG OFFICIAL_GA_MCP_REF=main
    
    ENV PYTHONUNBUFFERED=1 \
        PORT=8080
    
    WORKDIR /app
    
    RUN apt-get update \
        && apt-get install -y --no-install-recommends git \
        && rm -rf /var/lib/apt/lists/*
    
    # Pull the official Google Analytics MCP server source.
    # Pin OFFICIAL_GA_MCP_REF to a commit SHA for production reproducibility.
    RUN git clone https://github.com/googleanalytics/google-analytics-mcp.git . \
        && git checkout ${OFFICIAL_GA_MCP_REF}
    
    # Add only the Cloud Run HTTP entrypoint. Official GA tools remain unchanged.
    COPY cloudrun_server.py /app/cloudrun_server.py
    COPY coordinator.py /app/coordinator.py
    
    RUN pip install --no-cache-dir . uvicorn starlette
    
    EXPOSE 8080
    
    CMD ["python", "cloudrun_server.py"]

    Python ライブラリのインストール、ソースコードの配置、および Cloud Run 起動時に実行するプログラムを定義しています。
    本記事では検証のため「main」を指定していますが、「main」は公式リポジトリの更新によって取得内容が変わる可能性があります。
    本番環境で利用する場合は、動作確認済みのコミット SHA に固定してください。

    あわせて、Python パッケージやベースイメージについても、検証済みのバージョンを使用し、コンテナイメージおよび依存パッケージに既知の脆弱性がないことを確認してください。

    • cloudrun_server.py
    from __future__ import annotations
    
    import contextlib
    import os
    from collections.abc import AsyncIterator
    
    import uvicorn
    from starlette.applications import Starlette
    from starlette.responses import JSONResponse
    from starlette.routing import Mount, Route
    from starlette.types import Receive, Scope, Send
    
    import coordinator
    from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
    
    # json_response=False keeps standard Streamable HTTP streaming behavior.
    session_manager = StreamableHTTPSessionManager(
        app=coordinator.app,
        event_store=None,
        json_response=False,
        stateless=True,
    )
    
    
    async def health(_request):
        """Health check endpoint for Cloud Run / Cloud Scheduler."""
        return JSONResponse({"status": "ok", "server": coordinator.app.name})
    
    
    async def handle_mcp(scope: Scope, receive: Receive, send: Send) -> None:
        """ASGI adapter for the /mcp Streamable HTTP endpoint."""
        await session_manager.handle_request(scope, receive, send)
    
    
    @contextlib.asynccontextmanager
    async def lifespan(_app: Starlette) -> AsyncIterator[None]:
        """Start and stop the MCP Streamable HTTP session manager."""
        async with session_manager.run():
            yield
    
    
    app = Starlette(
        routes=[
            Route("/health", health, methods=["GET"]),
            Mount("/mcp", app=handle_mcp),
        ],
        lifespan=lifespan,
    )
    
    
    if __name__ == "__main__":
        port = int(os.environ.get("PORT", "8080"))
        uvicorn.run(app, host="0.0.0.0", port=port)

    公式の MCP サーバー処理を HTTP エンドポイントとして公開するための変換処理を実装しています。

    今回は「/health」はサービスの稼働確認に使用し、「/mcp」は Gemini Enterprise から接続する MCP エンドポイントとして使用します。

    Cloud Run はコンテナに渡される PORT 環境変数のポートでリクエストを待ち受ける必要があるため、アプリケーションでは PORT を取得し、0.0.0.0 で待ち受けます。Cloud Run で HTTP ベースの MCP サーバーをホストすると、HTTPS のサービス URL が割り当てられます。

    • coordinator.py
    # Copyright 2025 Google LLC All Rights Reserved.
    #
    # Licensed under the Apache License, Version 2.0 (the "License");
    # you may not use this file except in compliance with the License.
    # You may obtain a copy of the License at
    #
    #      http://www.apache.org/licenses/LICENSE-2.0
    #
    # Unless required by applicable law or agreed to in writing, software
    # distributed under the License is distributed on an "AS IS" BASIS,
    # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    # See the License for the specific language governing permissions and
    # limitations under the License.
    
    """Module declaring the singleton MCP server.
    
    The singleton allows other modules to register their tools with the same MCP
    server.
    """
    
    # MCP Server Imports
    import json
    import sys
    from json import tool
    from mcp import types as mcp_types  # Use alias to avoid conflict
    from mcp.server.lowlevel import Server
    
    # ADK Tool Imports
    from google.adk.tools.function_tool import FunctionTool
    from google.adk.tools.base_tool import BaseTool
    
    from analytics_mcp.tools.admin.info import (
        get_account_summaries,
        list_google_ads_links,
        get_property_details,
        list_property_annotations,
    )
    from analytics_mcp.tools.reporting.core import (
        run_report,
        _run_report_description,
    )
    from analytics_mcp.tools.reporting.realtime import (
        run_realtime_report,
        _run_realtime_report_description,
    )
    from analytics_mcp.tools.reporting.metadata import (
        get_custom_dimensions_and_metrics,
    )
    from analytics_mcp.tools.reporting.funnel import (
        run_funnel_report,
        _run_funnel_report_description,
    )
    from analytics_mcp.tools.reporting.conversions import (
        run_conversions_report,
        _run_conversions_report_description,
    )
    
    run_report_tool = FunctionTool(run_report)
    run_report_tool.description = _run_report_description()
    
    run_realtime_report_tool = FunctionTool(run_realtime_report)
    run_realtime_report_tool.description = (_run_realtime_report_description())
    
    run_funnel_report_tool = FunctionTool(run_funnel_report)
    run_funnel_report_tool.description = (_run_funnel_report_description())
    
    run_conversions_report_tool = FunctionTool(run_conversions_report)
    run_conversions_report_tool.description = (_run_conversions_report_description())
    
    get_account_summaries_tool = FunctionTool(get_account_summaries)
    
    list_google_ads_links_tool = FunctionTool(list_google_ads_links)
    
    get_property_details_tool = FunctionTool(get_property_details)
    
    list_property_annotations_tool = FunctionTool(list_property_annotations)
    
    get_custom_dimensions_and_metrics_tool = FunctionTool(get_custom_dimensions_and_metrics)
    
    # Instantiate the ADK tools
    tools = [
        get_account_summaries_tool,
        list_google_ads_links_tool,
        get_property_details_tool,
        list_property_annotations_tool,
        get_custom_dimensions_and_metrics_tool,
        run_report_tool,
        run_realtime_report_tool,
        run_funnel_report_tool,
        run_conversions_report_tool,
    ]
    
    tool_map = {t.name: t for t in tools}
    
    app = Server(
        name="Google Analytics MCP Server",
    )
    
    def adk_to_mcp_tool_type_readonly(tool: BaseTool) -> mcp_types.Tool:
        tool_declaration = tool._get_declaration()
        if not tool_declaration:
            input_schema = {}
        elif tool_declaration.parameters_json_schema:
            # Use JSON schema directly if available
            input_schema = tool_declaration.parameters_json_schema
        elif tool_declaration.parameters:
            # Convert from Schema object
            input_schema = gemini_to_json_schema(tool_declaration.parameters)
        else:
            input_schema = {}
        return mcp_types.Tool(
            name=tool.name,
            description=tool.description,
            inputSchema=input_schema,
            annotations=mcp_types.ToolAnnotations(read_only_hint=True)
        )
    
    mcp_tools = [adk_to_mcp_tool_type_readonly(tool) for tool in tools]
    
    def sanitize_mcp_schema_properties(node: dict) -> None:
        """Ensure additionalProperties is a boolean value to satisfy certain MCP clients.
    
        This addresses issues with clients like Claude Desktop that fail when
        additionalProperties is a schema object instead of a boolean.
        """
        if not isinstance(node, dict):
            return
    
        # Check and update the current node
        if "additionalProperties" in node:
            val = node["additionalProperties"]
            if not isinstance(val, bool):
                node["additionalProperties"] = True
    
        # Traverse children
        for key, child in node.items():
            if isinstance(child, dict):
                sanitize_mcp_schema_properties(child)
            elif isinstance(child, list):
                for element in child:
                    if isinstance(element, dict):
                        sanitize_mcp_schema_properties(element)
    
    
    # Update the inputSchema for tools that do not have parameters.
    # TODO: This is a bug in the ADK and can be removed once it is fixed.
    # https://github.com/google/adk-python/issues/948
    for tool in mcp_tools:
        # Check if inputSchema is empty
        if tool.inputSchema == {}:
            tool.inputSchema = {"type": "object", "properties": {}}
        # Fix union type hints generating spurious "type": "null"
        for prop in tool.inputSchema.get("properties", {}).values():
            if "anyOf" in prop and prop.get("type") == "null":
                del prop["type"]
    
        # Ensure additionalProperties is compatible with all MCP clients
        sanitize_mcp_schema_properties(tool.inputSchema)
    
        # Explicitly mark required fields for reporting tools to guide the LLM
        if tool.name == "run_report":
            tool.inputSchema["required"] = [
                "property_id",
                "date_ranges",
                "dimensions",
                "metrics",
            ]
        elif tool.name == "run_realtime_report":
            tool.inputSchema["required"] = ["property_id", "dimensions", "metrics"]
        elif tool.name == "run_conversions_report":
            tool.inputSchema["required"] = [
                "property_id",
                "date_ranges",
                "dimensions",
                "metrics",
                "conversion_spec",
            ]
    
    
    @app.list_tools()
    async def list_tools() -> list[mcp_types.Tool]:
        return mcp_tools
    
    
    @app.call_tool()
    async def call_mcp_tool(name: str, arguments: dict) -> list[mcp_types.Content]:
        if name in tool_map:
            tool = tool_map[name]
            try:
                adk_tool_response = await tool.run_async(
                    args=arguments,
                    tool_context=None,
                )
                # Serialize the ADK tool response to JSON for MCP response
                response_text = json.dumps(adk_tool_response, indent=2)
                # MCP expects a list of mcp_types.Content parts
                return [mcp_types.TextContent(type="text", text=response_text)]
    
            except Exception as e:
                print(
                    f"MCP Server: Error executing ADK tool '{name}': {e}",
                    file=sys.stderr,
                )
                # Return an error message in MCP format
                error_text = json.dumps(
                    {"error": f"Failed to execute tool '{name}': {str(e)}"}
                )
                return [mcp_types.TextContent(type="text", text=error_text)]
    
        error_text = json.dumps(
            {"error": f"Tool '{name}' not implemented by this server."}
        )
        return [mcp_types.TextContent(type="text", text=error_text)]

    今回の構成では、Google アナリティクスの読み取り専用ツールに対して、「readOnlyHint アノテーション」を付与するための変更を加えています。

    Gemini Enterprise では、すべてのアクションがデータを変更する可能性のある操作として扱われるため、デフォルトでは実行時にユーザー確認が必要です。
    ユーザー確認をはさむと、Agent Designer で作成したエージェントからデータの集計結果が返ってこない事象が確認されたため、今回はユーザー確認をスキップするよう改修しています。
    また、本サンプルでは、検証時のトラブルシューティングを目的として、例外内容をレスポンスおよびログへ出力しています。
    本番環境で利用する場合は、クライアントへ返すエラーを一般化し、アクセストークン、クライアント シークレット、プロジェクト情報、Google アナリティクスのデータなどがレスポンスやログへ含まれないようにしてください。

    ※「readOnlyHint」は、読み取り専用ツールの実行前に行われるユーザー確認を省略するためのアノテーションであり、認証やアクセス制御を代替するものではありません。対象ツールが実際にデータを変更しないことを確認したうえで設定してください。 詳細は下記ヘルプページをご参照ください。

    カスタム MCP サーバーのデータストアを設定する  |  Gemini Enterprise  |  Google Cloud Documentation

    • deploy.sh
    #!/usr/bin/env bash
    set -euo pipefail
    
    # ===== 環境に合わせて変更する設定値 =====
    PROJECT_ID="[プロジェクトID]"
    REGION="[リージョン]"
    REPO="[Artifact Registryのリポジトリ名]"
    SERVICE="[Cloud Runのサービス名]"
    RUNTIME_SA_NAME="[サービスアカウント名]"
    
    # 動作確認に使用するCloud Runのリビジョンタグ
    REVISION_TAG="test"
    
    # falseの場合はCloud RunのIAM認証を必要とする
    ALLOW_UNAUTHENTICATED="false"
    # =======================================
    
    RUNTIME_SA="${RUNTIME_SA_NAME}@${PROJECT_ID}.iam.gserviceaccount.com"
    
    IMAGE="${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/${SERVICE}:$(date +%Y%m%d%H%M%S)"
    
    REVISION_SUFFIX="$(date +%Y%m%d%H%M)"
    
    # 操作対象のGoogle Cloudプロジェクトを設定する
    gcloud config set project "${PROJECT_ID}"
    
    # 必要なAPIを有効化する
    gcloud services enable \
      run.googleapis.com \
      artifactregistry.googleapis.com \
      cloudbuild.googleapis.com \
      analyticsadmin.googleapis.com \
      analyticsdata.googleapis.com
    
    # Artifact Registryのリポジトリが存在しない場合のみ作成する
    if ! gcloud artifacts repositories describe "${REPO}" \
      --location "${REGION}" >/dev/null 2>&1; then
    
      gcloud artifacts repositories create "${REPO}" \
        --repository-format=docker \
        --location="${REGION}" \
        --description="MCP server container images"
    fi
    
    # Cloud Runの実行サービスアカウントが存在しない場合のみ作成する
    if ! gcloud iam service-accounts describe "${RUNTIME_SA}" \
      >/dev/null 2>&1; then
    
      gcloud iam service-accounts create "${RUNTIME_SA_NAME}" \
        --display-name="GA MCP Cloud Run Runner"
    fi
    
    # Dockerfileからコンテナイメージをビルドし、
    # Artifact Registryへ保存する
    gcloud builds submit \
      --tag "${IMAGE}"
    
    # Cloud Runの認証設定を切り替える
    AUTH_FLAG="--no-allow-unauthenticated"
    
    if [[ "${ALLOW_UNAUTHENTICATED}" == "true" ]]; then
      AUTH_FLAG="--allow-unauthenticated"
    fi
    
    # 新しいリビジョンへトラフィックを割り当てずにデプロイする
    gcloud run deploy "${SERVICE}" \
      --image "${IMAGE}" \
      --region "${REGION}" \
      --service-account "${RUNTIME_SA}" \
      --port 8080 \
      --ingress all \
      --set-env-vars "GOOGLE_CLOUD_PROJECT=${PROJECT_ID}" \
      --tag "${REVISION_TAG}" \
      --revision-suffix "${REVISION_SUFFIX}" \
      --no-traffic \
      ${AUTH_FLAG}
    
    # デプロイ結果を取得する
    SERVICE_URL=$(
      gcloud run services describe "${SERVICE}" \
        --region "${REGION}" \
        --format="value(status.url)"
    )
    
    LATEST_READY=$(
      gcloud run services describe "${SERVICE}" \
        --region "${REGION}" \
        --format="value(status.latestReadyRevisionName)"
    )
    
    echo ""
    echo "Deployment completed as a no-traffic revision."
    echo "Service: ${SERVICE}"
    echo "Latest ready revision: ${LATEST_READY}"
    echo "MCP URL: ${SERVICE_URL}/mcp"
    echo ""
    echo "Next steps:"
    echo "1. Confirm the logs for the new Cloud Run revision."
    echo "2. Confirm that the MCP server starts successfully."
    echo "3. If there are no problems, shift traffic to the tagged revision:"
    echo "   gcloud run services update-traffic ${SERVICE} \\"
    echo "     --region ${REGION} \\"
    echo "     --to-tags ${REVISION_TAG}=100"
    echo ""
    echo "GA permission reminder:"
    echo "Grant ${RUNTIME_SA} read access to the target Google Analytics properties."

    ALLOW_UNAUTHENTICATEDは、Cloud Run への未認証リクエストを許可するかどうかを指定する設定です。本記事ではfalseを指定し、Cloud Run IAM による認証を必須としています。

    Gemini Enterprise から Cloud Run へ接続するため、Gemini Enterprise のサービスエージェントには、対象サービスの「Cloud Run 起動元(roles/run.invoker)」ロールを付与します。 また、Gemini Enterprise のカスタム MCP データストアには、別途 OAuth を設定します。Cloud Run IAM と OAuth は役割が異なるため、両方の設定が必要な点に注意しましょう。

    あわせて、次の設定値を環境に合わせて変更しましょう。

    ①PROJECT_ID=[プロジェクトID]
    Google Cloud のプロジェクト ID です。
    ②REGION=[リージョン]
    Cloud Run と Artifact Registry を作成するリージョンです。
    ③REPO=[Artifact Registryのリポジトリ名]
    Docker イメージを保存する Artifact Registry のリポジトリ名です。
    ④SERVICE=[Cloud Runのサービス名]
    Cloud Run のサービス名です。
    ※サービスアカウントには、事前に参照対象となる Google アナリティクス プロパティの「閲覧者」権限を付与します。
    参照元プロパティに「閲覧者」権限を付与した場合、紐づけられたサブプロパティへの閲覧も可能になります。
    ⑤RUNTIME_SA_NAME=[サービスアカウント名]
    Cloud Run の実行サービスアカウント名です。

    Artifact Registry は、ソースコードから作成したコンテナイメージを保存するために使用します。Cloud Run は Artifact Registry に保存されたイメージを参照してコンテナを起動します。 初回構築時は、Artifact Registry のリポジトリと Cloud Run 用のサービスアカウントも作成します。

    2-3. Google アナリティクス MCP サーバーを Cloud Run にデプロイする

    準備したファイルを Cloud Shell へアップロードし、Cloud Run へデプロイします。 Google Cloud コンソールから Cloud Shell を起動し、作成したフォルダをアップロードします。

    アップロード後、対象フォルダへ移動し「deploy.sh」を開き、前項で説明した、プロジェクト ID、リージョン、Artifact Registry のリポジトリ名、Cloud Run サービス名、サービスアカウント名を環境に合わせて変更します。

    nano deploy.sh

    編集が完了したら、次のコマンドでdeploy.shに実行権限を付与します。

    chmod +x deploy.sh

    続いて、デプロイスクリプトを実行します。

    ./deploy.sh

    スクリプトの実行により、必要な API の有効化、コンテナイメージのビルド、Artifact Registry への保存、Cloud Run サービスへのデプロイが行われます。

    デプロイが完了したら、Google Cloud コンソールの「Cloud Run」から対象サービスを開き、サービスが正常に稼働していることを確認します。

    3. Google アナリティクス MCP サーバーを Gemini Enterprise に接続する

    3-1. データストア作成にあたっての権限の調整

    Gemini Enterprise でカスタム MCP データストアを作成するには、事前に以下の3つの設定を確認し、必要に応じて変更します。

    • 組織のポリシーをオーバーライドする
      Gemini Enterprise は、デフォルトではマネージド組織のポリシー制約を使用して Model Context Protocol(MCP)データストアの作成をブロックするため、
      カスタム MCP データストアの作成を有効にするには、組織のポリシー管理者がこの制限をオーバーライドする必要があります。

    設定方法については、次の Google Cloud 公式ドキュメントを参照してください。
    docs.cloud.google.com

    • データストアの許可された下り(外向き)FQDN を構成する
      Gemini Enterprise から Google アナリティクス MCP サーバーへ接続できるようにするには、MCP サーバー URL、認証 URL、トークン URL の完全修飾ドメイン名(FQDN)を明示的に許可する必要があります。

    設定方法については、次の Google Cloud 公式ドキュメントを参照してください。
    docs.cloud.google.com

    • 許可するデータソースを構成する
      Gemini Enterprise でカスタム MCP データストアを作成するには、許可されるデータソースに 「custom_mcp」を追加する必要があります。

    設定方法については、次の Google Cloud 公式ドキュメントを参照してください。
    docs.cloud.google.com

    3-2. カスタム MCP データストアを作成する

    権限と組織ポリシーの設定が完了したら、いよいよ Gemini Enterprise でデータストアを作成していきます。

    Gemini Enterprise のアプリ画面の[接続されたデータストア]タブから[+新しいデータストア]を押下します。 [MCP サーバー]配下の[MCP サーバーを追加]を押下します。 データの認証設定のために、下記を入力します。 ①MCP サーバーで OAuth 2.0 認証が必要かどうかを選択する

    ②MCP サーバーの URL
    Cloud Run のデフォルト サービス URL の末尾に「/mcp/」を付けた URL。

    ③認可 URL
    Google の認証・同意画面を呼び出すための URL。以下の URL をコピーして入力欄に貼り付けます。

    https://accounts.google.com/o/oauth2/v2/auth             

    ④認可 URL パラメータ
    Google OAuth でリフレッシュ トークンを取得するため、認可 URL には 「access_type=offline」 を指定します。
    また、すでに認可済みの場合でも、再度同意画面を表示してリフレッシュ トークンを取得できるよう、「prompt=consent」 を指定します。

    &access_type=offline&prompt=consent          

    ⑤トークン URL
    認可コードをアクセス トークンおよびリフレッシュ トークンと交換するためのエンドポイントです。

    https://oauth2.googleapis.com/token          

    ⑥クライアント ID

    ⑦クライアント シークレット

    ⑧アプリに許可するスコープ(権限)
    ※Google アナリティクス API には、以下のスコープが用意されています。

    Google API の OAuth 2.0 スコープ  |  Google for Developers

    ※今回は、Google アナリティクスのデータを閲覧するため、以下のスコープを使用します。

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

    ⑨OAuth 2.0 認証で PKCE(Proof Key for Code Exchange)を使用するかどうかを選択する
    PKCE(Proof Key for Code Exchange)は、認可コードの横取り攻撃を防止するための追加のセキュリティ機能です。

    ※今回は OAuth クライアント シークレットを使用するサーバーサイド認証構成のため、PKCE は使用しません。

    ⑩トークン取得時にクライアント ID とクライアント シークレットを HTTP Basic 認証で送信するかどうかを選択する
    OAuth 2.0 のトークン取得時に、クライアント ID およびクライアント シークレットを Authorization ヘッダー(HTTP Basic 認証)で送信します。

    ※今回は Google OAuth を利用する機密クライアント構成であり、OAuth クライアント シークレットを保持しているため、HTTP Basic 認証を使用します。

    最後に、以下のデータコネクタ情報を入力し、データコネクタを作成します。 ①データコネクタのロケーション
    ②データコネクタ名
    ③タグ(任意)
    ④Sensitive Data Protection ポリシー(任意)

    3-3. アクションを有効化する

    データストアを作成すると、MCP サーバーが公開しているツールが Gemini Enterprise へ取り込まれます。
    ※MCP の仕様では「ツール」と呼ばれますが、Gemini Enterprise のデータストアでは「アクション」として表示されます。

    デフォルトでは、取り込まれたアクションは無効になっているため、利用するアクションを有効化する必要があります。
    [カスタム アクションを再読み込み]を押すと認証用のウィンドウが表示されるので、認証完了後、MCP サーバーのツールが取得され、Gemini Enterprise のデータストアにアクションとして表示されるようになります。

    ※MCP サーバーから取り込まれたアクションは、デフォルトでは実行前にユーザー確認が求められます。データの変更を伴わない読み取り専用ツールについて、ユーザー確認を省略する場合は、「readOnlyHint アノテーション」を設定します。
    設定の詳細については、以下の Google Cloud 公式ドキュメント、および「2-2. Cloud Run で実行するためのファイルを準備する」に掲載しているソース「coordinator.py」を参照してください。

    カスタム MCP サーバーのデータストアを設定する  |  Gemini Enterprise  |  Google Cloud Documentation

    認証完了後は、Gemini Enterprise の画面を開き、作成したカスタム MCP サーバーの[データストア]>[操作]に移動し、
    表示されたアクション一覧から、有効化または無効化できます。

    3-4. Gemini Enterprise から Google アナリティクスのデータを取得する

    最後に、作成したカスタム MCP データストアを Gemini Enterprise アプリへ接続します。 対象となる Gemini Enterprise アプリを開き、[コネクタ]から、作成したデータストアを追加し、チャット画面で有効になっていることを確認します。 接続後はチャットしながら簡単に GA のデータを取得できるほか、過去 7 日間のセッション数を基にした示唆出しも行えることを確認できました。

    4. おわりに

    検証を始める前は、Google 社が提供するサービス同士なので正直なところ、簡単な設定だけで Gemini Enterprise と Google アナリティクス MCP サーバーを接続できるのではないかと考えていました。

    しかし、実際に社内で利用するための検証環境を構築するには、MCP サーバーの接続方式の変更や Cloud Run へのデプロイ、OAuth 2.0 認証、組織ポリシーの設定など、さまざまな要素を確認する必要がありました。

    また実際に接続してみると、専門的なレポート画面を操作しなくても、自然言語を起点に Google アナリティクスのデータへアクセスできるだけでなく、他のサービスと組み合わせた横断的なエージェントを構築し、分析や示唆出しまで行える点に大きな実用性を感じました。

    そのため、Gemini Enterprise と Google アナリティクスを接続することで、これまで Google アナリティクスを日常的に利用していなかった人も含め、より多くの人がデータを効率的かつ柔軟に活用できるようになると感じました。
    私自身、入社2年目でまだ手探りの部分も多くありますが、変化の速い技術を使いこなし、今後も新しい情報を継続的にキャッチしながら、実際の業務に役立てられるよう学習と検証を続けていきたいと思います。

    執筆者:中山 茉優
    Google アナリティクスを中心としたGoogle マーケティング プラットフォーム(GMP)のテクニカルサポートを担当しています。