使用 BigQuery MCP 建構 Google 搜尋趨勢分析師代理程式

1. 總覽

在本程式碼實驗室中,您將使用 Google ADK 建構 Google 搜尋趨勢分析師代理。這個代理會運用 BigQuery MCP 伺服器,動態探索及執行查詢 Google 搜尋趨勢公開資料集 (bigquery-public-data.google_trends) 的工具。

課程內容

  • 如何設定 ADK 開發專案。
  • 如何使用 BigQuery 的代管 MCP 伺服器。
  • 如何建構使用 MCP 工具的代理程式。
  • 如何在本機執行代理程式以進行測試。
  • 如何將代理程式部署至 Google Cloud Run。

軟硬體需求

  • 已啟用計費功能的 Google Cloud 雲端專案
  • 網路瀏覽器,例如 Chrome
  • 如果您是在自己的電腦上執行程式碼,而非 Cloud Shell,則需要 Python 3.11 以上版本和 uv

本程式碼實驗室適合對 Python 和 Google Cloud 有基本認識的中級開發人員。

完成這個程式碼研究室大約需要 20 分鐘。

本程式碼研究室建立的資源費用應低於 $5 美元。

2. 設定環境

建立 Google Cloud 專案

  1. 在 Google Cloud 控制台的專案選擇器頁面中,選取或建立 Google Cloud 專案。
  2. 確認 Cloud 專案已啟用計費功能。瞭解如何檢查專案是否已啟用計費功能。

驗證及設定 gcloud

登入 Google 帳戶、設定有效專案,並設定應用程式預設憑證。

gcloud auth login
gcloud auth application-default login

注意:gcloud auth login 會驗證 gcloud CLI 指令,而 gcloud auth application-default login 則會驗證本機應用程式程式碼。

設定 Google Cloud 專案:

gcloud config set project <YOUR_PROJECT_ID>

啟用必要的 API

啟用 Cloud Run、Artifact Registry、BigQuery 和 Gemini Enterprise 的必要 Google Cloud API。

gcloud services enable run.googleapis.com \
                       cloudbuild.googleapis.com \
                       artifactregistry.googleapis.com \
                       bigquery.googleapis.com \
                       aiplatform.googleapis.com

啟用 BigQuery API 時,系統會一併啟用 BigQuery 遠端 MCP 伺服器,因此您不需要另外執行步驟。

建立專案資料夾

首先,請為代理建立根資料夾,以及代理實作的內部資料夾。

mkdir -p ~/google-trends-agent/google_trends
cd ~/google-trends-agent
uv init --bare

uv 會為這個程式碼研究室建立獨立的 Python 環境,因此您不需要啟用任何項目。在 Python 指令前加上 uv run。

設定專案設定

執行下列指令,使用專案和位置資訊建立 google_trends/.env。GOOGLE_GENAI_USE_ENTERPRISE=True透過您的 Google Cloud 專案呼叫 Gemini,並使用 Cloud IAM 進行驗證,而非 GEMINI_API_KEY。ADK 會自動載入這個檔案,因此設定也會在新終端機中生效。

cat > ~/google-trends-agent/google_trends/.env <<EOF
GOOGLE_CLOUD_PROJECT=$(gcloud config get project)
GOOGLE_CLOUD_LOCATION=global
GOOGLE_GENAI_USE_ENTERPRISE=True
EOF

3. 建立代理程式碼

建立一個名為 google_trends/__init__.py 的空檔案:

touch google_trends/__init__.py

接著,建立名為 google_trends/agent.py 的檔案,並貼上下列程式碼:

import os
import textwrap
import warnings
from datetime import date

import google.auth
from google.adk.agents import LlmAgent
from google.adk.apps import App
from google.adk.models import Gemini
from google.adk.tools.mcp_tool import McpToolset
from google.adk.tools.mcp_tool.mcp_session_manager import StreamableHTTPConnectionParams
from google.auth.transport.requests import Request
from google.genai import types

# Suppress experimental ADK credential warnings
warnings.filterwarnings("ignore")

def get_agent_instruction(project_id: str) -> str:
    """Generates a clear and formatted prompt for the data analyst."""
    instruction = f"""
    # ROLE
    You are a Google Search Trends Analyst. Your mission is to provide clear answers using SQL data.

    # DATA CONSTRAINTS
    - BigQuery tool `execute_sql` requires explicit billing project mapping. Use: '{project_id}'.
    - Target dataset strictly: `bigquery-public-data.google_trends`

    # SCHEMA DISCOVERY (CRITICAL)
    1. DO NOT call `get_table_info` or `list_table_ids` (Triggers Permission Errors).
    2. Run `SELECT * FROM table LIMIT 0` via `execute_sql` for field definition mapping.

    # OUTPUT PRESENTATION
    - Render purely as a cleanly aligned Markdown table.
    - Use clear and descriptive headers for each column.
    - Remove conversational preambles. Output only the results.
    """
    return textwrap.dedent(instruction).strip()

credentials, _ = google.auth.default(
    scopes=["https://www.googleapis.com/auth/cloud-platform"]
)

def get_auth_headers(context=None) -> dict[str, str]:
    """Fetch auth headers, refreshing the access token when it expires."""
    if not credentials.valid:
        credentials.refresh(Request())

    return {"Authorization": f"Bearer {credentials.token}"}

def get_todays_date() -> str:
    """Returns today's date in YYYY-MM-DD format."""
    return date.today().isoformat()

# --- Application Initialization ---
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT")
if not project_id:
    raise ValueError("GOOGLE_CLOUD_PROJECT environment variable is not set")

mcp_headers = {
    "Content-Type": "application/json",
    "Accept": "application/json, text/event-stream",
}

# Configure BigQuery Tools via MCP
bq_tools = McpToolset(
    connection_params=StreamableHTTPConnectionParams(
        url="https://bigquery.googleapis.com/mcp",
        headers=mcp_headers,
    ),
    # Called for each MCP request, so the token stays fresh on long-running servers
    header_provider=get_auth_headers,
)

# Initialize the LLM Agent
root_agent = LlmAgent(
    name="google_trends",
    model=Gemini(
        model="gemini-3.8-flash",
        retry_options=types.HttpRetryOptions(attempts=5),
    ),
    tools=[get_todays_date, bq_tools],
    instruction=get_agent_instruction(project_id),
)

# Create the ADK App
app = App(name=root_agent.name, root_agent=root_agent)

4. 執行代理程式

在這個步驟中,您將安裝依附元件並執行代理程式,在電腦 (或 Google Cloud Shell) 上驗證代理程式的行為。

  • 前往應用程式根目錄 (google-trends-agent):
cd ~/google-trends-agent
  • 安裝必要的 Python 套件:
uv add google-auth "google-adk[mcp]"

我們會使用 ADK Web 測試新代理程式。

如要在本機開發及測試,請執行下列指令:

uv run adk web

如要在 Google Cloud Shell 中進行開發和測試,請執行下列指令:

uv run adk web --allow_origins="*"

這項操作會啟動 ADK 網路伺服器。你可以使用本機網頁介面 (通常位於 http://localhost:8000) 與代理程式互動。

注意:您也可以使用較簡單的 uv run adk run google_trends 指令測試代理程式。

5. 部署至 Cloud Run

請按照下列步驟,將代理程式安全地部署至 Google Cloud Run。

授予權限

Cloud Run 需要權限才能呼叫 Gemini 和使用 BigQuery MCP 工具。

# Get your project ID and number automatically
PROJECT_ID=$(gcloud config get project)
PROJECT_NUMBER=$(gcloud projects describe ${PROJECT_ID} --format='value(projectNumber)')

# Model access: To talk to the Gemini model
gcloud projects add-iam-policy-binding ${PROJECT_ID} \
  --member="serviceAccount:${PROJECT_NUMBER}-compute@developer.gserviceaccount.com" \
  --role="roles/aiplatform.user"

# MCP & BigQuery: To execute tools and run SQL jobs
gcloud projects add-iam-policy-binding ${PROJECT_ID} \
  --member="serviceAccount:${PROJECT_NUMBER}-compute@developer.gserviceaccount.com" \
  --role="roles/mcp.toolUser"

gcloud projects add-iam-policy-binding ${PROJECT_ID} \
  --member="serviceAccount:${PROJECT_NUMBER}-compute@developer.gserviceaccount.com" \
  --role="roles/bigquery.jobUser"

gcloud projects add-iam-policy-binding ${PROJECT_ID} \
  --member="serviceAccount:${PROJECT_NUMBER}-compute@developer.gserviceaccount.com" \
  --role="roles/bigquery.dataViewer"

建立 Dockerfile

在專案的根目錄 (google-trends-agent) 中,建立名為 Dockerfile 的檔案,並貼上下列內容:

FROM python:3.11-slim
WORKDIR /app

# Create a non-root user
RUN adduser --disabled-password --gecos "" myuser
USER myuser
ENV PATH="/home/myuser/.local/bin:$PATH"

# Copy the agent folder into the container
COPY --chown=myuser:myuser google_trends/ /app/agents/google_trends/

# Install the python packages
RUN pip install google-auth "google-adk[mcp]"

# Set environment variables
ENV GOOGLE_CLOUD_LOCATION=global
ENV GOOGLE_GENAI_USE_ENTERPRISE=True

# Expose port
EXPOSE 8080

# Run ADK web server
CMD ["adk", "web", "--port=8080", "--host=0.0.0.0", "/app/agents"]

部署代理

從根目錄執行下列指令,這會將代理程式容器化並部署至 Cloud Run。

gcloud run deploy google-trends-agent \
  --source . \
  --region us-west1 \
  --allow-unauthenticated \
  --set-env-vars="GOOGLE_CLOUD_PROJECT=$(gcloud config get project)"

快速驗證

部署完成後,控制台會輸出「服務網址」。在瀏覽器中開啟這個網址,您會看到與在本機上相同的互動式 UI,但現在是在雲端執行!

您也可以監控記錄,確保一切運作順暢:

gcloud logging read "resource.type=cloud_run_revision AND resource.labels.service_name=google-trends-agent" --limit 10

6. 清除

如要避免產生持續性費用,請刪除本程式碼研究室建立的資源。

刪除 Cloud Run 服務:

gcloud run services delete google-trends-agent --region us-west1

如果您是特地為了這個程式碼研究室建立專案,可以刪除整個專案:

gcloud projects delete <YOUR_PROJECT_ID>

您也可以刪除與這個程式碼研究室相關的所有檔案:

cd ~
rm -rf ~/google-trends-agent

7. 恭喜

恭喜!您已成功建構及部署 Google 搜尋趨勢分析師代理程式。

目前所學內容

  • 如何使用 MCP 動態擴充代理能力
  • 如何使用 Google ADK 建構及提供 LLM 代理
  • 如何在 Cloud Run 上部署及擴充代理

後續步驟

  • 嘗試修改代理程式,查詢不同的 BigQuery 資料集
  • 新增更多 MCP 工具,擴充代理的功能

參考文件