使用 Gemini 和 Cloud Run 中的 BigQuery MCP 伺服器建構及部署 AI 代理

1. 簡介

課程內容

Cloud Run 是全代管的無伺服器運算平台,可讓您執行容器化應用程式和服務,不必管理任何基礎架構。

Agent Development Kit (ADK) 是開放原始碼的代理開發框架,可讓您建構、偵錯及部署企業級的可靠 AI 代理。

BigQuery 是全代管的無伺服器企業資料倉儲,可供您儲存、查詢及分析龐大的資料集。

Model Context Protocol (MCP) 可將大型語言模型 (LLM) 和 AI 應用程式/代理程式與外部資料來源的連結方式標準化。MCP 伺服器可讓您使用工具、資源和提示,執行動作並從後端服務取得最新資料。BigQuery MCP 伺服器可讓 AI 代理直接安全地分析 BigQuery 中的資料。這項全代管 MCP 伺服器可免去管理負擔,讓您專心開發智慧代理程式。

2. 設定和需求條件

首先,請設定預設專案和 Cloud Run 區域:

# set the project
gcloud config set project YOUR_PROJECT_ID

YOUR_PROJECT_ID 替換為 Google Cloud 專案 ID。

# set Cloud Run region
gcloud config set run/region CLOUD-RUN-REGION

CLOUD-RUN-REGION 替換成其中一個 Cloud Run 支援的地區

以下是本程式碼研究室會用到的環境變數。您可以將這些變數儲存在環境檔案中,然後「來源」該檔案。請務必正確設定專案 ID 值,並視需要設定區域。

# Cloud Project Id and Cloud Run region
export GOOGLE_CLOUD_PROJECT="${GOOGLE_CLOUD_PROJECT:-$(gcloud config get-value project -q)}"
export GOOGLE_CLOUD_REGION="${GOOGLE_CLOUD_REGION:-$(CR_REGION=$(gcloud config get-value run/region -q 2>/dev/null); echo "${CR_REGION:-us-central1}")}"
# Gemini API in Agent Platform
export GOOGLE_GENAI_USE_ENTERPRISE="True" # Use Agent Platform
export GOOGLE_CLOUD_LOCATION="global" # Use global Gemini API endpoint

啟用本程式碼研究室所需的 API。API 變更可能需要 2 到 3 分鐘才會生效。

gcloud services enable --project "${GOOGLE_CLOUD_PROJECT}" \
    run.googleapis.com \
    cloudbuild.googleapis.com \
    artifactregistry.googleapis.com \
    bigquery.googleapis.com \
    aiplatform.googleapis.com

3. 使用 Agent Development Kit 建立資料代理

編寫代理程式碼

在 Cloud Shell 終端機或本機終端機中,為代理程式應用程式建立根目錄:

mkdir data_agent

開啟 Cloud Shell 編輯器或其他文字編輯器,然後在 data_agent 目錄中建立 agent.py

data_agent/
    agent.py

agent.py

import os

from google.adk.agents import LlmAgent
from google.adk.tools.mcp_tool.mcp_toolset import McpToolset
from google.adk.tools.mcp_tool.mcp_session_manager import StreamableHTTPConnectionParams

import google.auth
from google.auth.transport.requests import Request

# Fetch Application Default Credentials (ADC)
# to use as agent's own identity for accessing BigQuery MCP Server
_application_default_credentials, project_id = google.auth.default()
_request = Request()
_application_default_credentials.refresh(_request)

# Retrieve Google Cloud project to use.
project_id = os.getenv("GOOGLE_CLOUD_PROJECT", project_id)
if not project_id:
    raise ValueError("GOOGLE_CLOUD_PROJECT environment variable is not set.")

# Builds authentication headers for MCP Server requests,
# and refreshes credentials if needed.
def _adc_auth_header_provider(context = None) -> dict[str, str]:
    if not _application_default_credentials.valid:
        _application_default_credentials.refresh(_request)

    return {
        "Authorization": f"Bearer {_application_default_credentials.token}",
        "x-goog-user-project": project_id
    }

# Initialize the MCP Toolset with the connection parameters
bigquery_toolset = McpToolset(
    connection_params=StreamableHTTPConnectionParams(
        url="https://bigquery.googleapis.com/mcp",
        tool_filter=[
            'get_dataset_info',
            'list_table_ids',
            'get_table_info',
            # Using readonly is a security measure to prevent accidental data modification.
            'execute_sql_readonly',
        ]
    ),
    header_provider=_adc_auth_header_provider # Auth header provider function
)

# Configure the agent

system_instruction = f"""
You are a helpful assistant that can answer questions about data in BigQuery.
To answer the user's question, use data you have access to by using tools `list_table_ids` and `get_table_info`.
Your data is in `bigquery-public-data.new_york_citibike` dataset (Citi Bike trips and stations in the NYC area.)

Plan of action:
0. ALWAYS start by analyzing dataset.
1. Analyze your data, investigate schema and dimensions by querying distrinct values of columns using `execute_sql_readonly`.
   Output information about tables, columns, their data types and sets of values (for dimensions).
   Note which columns can be joined or used in aggregations/filters, and what type conversion may be needed for joining or aggregating.
   DO NOT MAKE ASSUMPTIONS ABOUT DATA (structure, type, values, relationships) BASED ON YOUR PRIOR KNOWLEDGE. ALWAYS VERIFY YOUR ASSUMPTIONS.
2. Understand and interpret the user's question.
3. Formulate a plan to answer the user's question.
4. Write a SQL query to retrieve relevant data in necessary form.
   This is where you must pay extra attention to column types and dimensions' sets of values.
5. Retrieve data by generating BigQuery SQL and using `execute_sql_readonly`.
   Always use Dry Run to verify SQL correctness.
   Use `{project_id}` to run BigQuery queries (`project_id` parameter of `execute_sql_readonly`).

Do not use LaTeX in your responses. When giving a final answer, use Markdown.
"""

root_agent = LlmAgent(
    model="gemini-3.6-flash",
    name="data_agent",
    instruction=system_instruction,
    description="A helpful assistant that can answer questions using NYC Citibike data.",
    tools=[bigquery_toolset]
)

ADK 也需要 __init__.pyrequirements.txt 才能部署:

  • __init__.py 必須匯入代理程式。
  • requirements.txt 列出 Python 依附元件:google-adk 適用於 Agent Development Kit,mcp 適用於 Model Context Protocol 用戶端。

這些指令可協助您建立 __init__.pyrequirements.txt

echo "from . import agent" > data_agent/__init__.py
echo -e "google-adk==2.4.*\nmcp==1.29.*" > data_agent/requirements.txt

最終的資料夾結構應如下所示:

data_agent/
    __init__.py
    agent.py
    requirements.txt

在本機試用代理程式

Agent Development Kit 隨附 adk CLI 工具,也就是用於測試代理的互動式終端機介面。這項功能適用於快速測試、指令碼互動和 CI/CD 管道。其中一項功能是 adk web - ADK 網頁介面,可讓您以簡單的方式互動式開發及偵錯代理程式。ADK Web 不適用於正式環境部署,但可讓您輕鬆試用代理程式。

這個指令會啟動 adk web,在通訊埠 8080 啟動本機網路伺服器。

uv tool run --with "mcp==1.29.*" --from "google-adk[mcp]==2.4.*" adk web --allow_origins="*" --port 8080 .

服務啟動後,開啟本機 ADK 網頁:http://localhost:8080/。

如果您使用 Google Cloud Shell,請按一下「網頁預覽」網頁預覽 按鈕,然後選取「透過以下通訊埠預覽:8080」選單項目。

在 ADK 網頁版 UI 中,詢問代理可存取的資料:

What data do you have?

代理程式會使用 BigQuery MCP 工具探索 citibike 資料集。畫面會顯示 Citibike 資料集中可用的資料表和欄位概覽。

4. 將代理程式部署至 Cloud Run

這項指令會使用 ADK CLI 將代理部署至 Cloud Run。

uv tool run --from google-adk==2.4.0 \
  adk deploy cloud_run \
      --with_ui \
      --project $GOOGLE_CLOUD_PROJECT \
      --region $GOOGLE_CLOUD_REGION \
      --service_name bq-data-agent \
      --app_name data_agent \
      data_agent \
      -- \
      --allow-unauthenticated \
      --max-instances 1 \
      --set-env-vars GOOGLE_GENAI_USE_ENTERPRISE=True,GOOGLE_CLOUD_PROJECT="${GOOGLE_CLOUD_PROJECT},GOOGLE_CLOUD_LOCATION=${GOOGLE_CLOUD_LOCATION}"

試用代理

我們使用 --with_ui 選項部署代理程式。使用 ADK 網頁介面部署代理。

  1. 在網路瀏覽器中開啟代理程式網址。adk deploy 指令傳回的網址,您也可以執行 gcloud run services 指令來擷取網址:
gcloud run services describe bq-data-agent \
  --project $GOOGLE_CLOUD_PROJECT \
  --region $GOOGLE_CLOUD_REGION \
  --format 'value(status.url)'
  1. 請代理程式根據可用的 Citibike 資料進行推論:
We have budget for 3 coffee trucks.
We want to find the best city bike stations to place our coffee trucks.

代理程式應使用 BigQuery MCP 伺服器探索 Citibike 資料集、執行幾項 SQL 查詢,並傳回 3 個 Citibike 車站的清單。

5. 恭喜!

恭喜您完成本程式碼研究室!

建議您參閱 Cloud Run 說明文件。

涵蓋內容

  • 如何使用 Agent Development Kit 和 Gemini 建立 AI 代理
  • 如何將代理程式連線至 BigQuery MCP 伺服器。
  • 如何將代理程式部署至 Cloud Run。

6. 清理

如要避免系統向您的 Google Cloud 帳戶收取本教學課程所用資源的費用,請刪除專案或個別資源。

方法 1:刪除服務

刪除 Cloud Run 服務

gcloud run services delete bq-data-agent \
      --project "${GOOGLE_CLOUD_PROJECT}" \
      --region "${GOOGLE_CLOUD_REGION}" \
      --quiet

方法 2:刪除專案

如要刪除整個專案,請前往「管理資源」,選取您在步驟 2 中建立的專案,然後選擇「刪除」。刪除專案後,您必須在 Cloud SDK 中變更專案。如要查看所有可用專案的清單,請執行 gcloud projects list。如要使用指令列,也可以執行下列指令:

gcloud projects delete ${GOOGLE_CLOUD_PROJECT}