使用 MCP 和 Cloud Run 部署 Enterprise Governance-Aware Agent

1. 簡介

本程式碼實驗室是兩堂系列課程的一部分,旨在探討如何建構具備管理意識的 AI 代理。

(您可以閱讀本系列的第一部分,瞭解如何註冊 Knowledge Catalog 構面類型、將構面套用至 BigQuery 資料表,以及透過 AGY CLI 在本機測試規則,藉此建立資料基礎。閱讀第 1 部分

不過,在本機 CLI 測試只是第一步。如要將這項功能推廣至全公司,您需要集中式安全防護機制、標準化 AI 工具連線,以及適當的應用程式架構,以便自動調度代理的邏輯,並提供熟悉的對話介面。

在第二部分,您將解決這些挑戰,並擴充至正式環境。您不必部署自訂 MCP 伺服器,而是直接將代理連至 Google 代管的 Knowledge Catalog MCP 伺服器。接著,您將使用 Google 的 Agent Development Kit (ADK) 建構實際的代理應用程式、從本機代理技能載入管理規則,並部署至 Cloud Run,完成專業的網頁 UI

.

使用者與 ADK UI 互動時,會依序執行下列操作:

8912d1983c34ee8e.png

課程內容

  • 如何使用 Model Context Protocol (MCP),將 AI 代理與 Google Cloud 資料的互動方式標準化。
  • ADK 代理如何連線至 Google 代管的 Knowledge Catalog MCP 伺服器。
  • 如何從共用代理技能動態載入治理規則。
  • 如何將代理部署至 Cloud Run,並執行 ADK 內建的網頁測試區。

軟硬體需求

  • 已啟用計費功能的 Google Cloud 專案。
  • Google Cloud Shell 的存取權。
  • 對 Cloud Run、IAM 服務帳戶和 Python 有基本瞭解。
  • 第 1 部分建立的 BigQuery 資料集和 Knowledge Catalog 方面。(如果已刪除,請別擔心,我們在下方提供快速指令碼,可重新建立這些資源!)

核心概念

  • Model Context Protocol (MCP):MCP 就像是 AI 代理的「通用 USB-C 傳輸線」。MCP 提供標準方法,讓 AI 安全連結至企業資料工具 (例如 Knowledge Catalog 和 BigQuery),不必為每個 AI 模型編寫自訂 API 整合程式碼。
  • Agent Development Kit (ADK):Google 的彈性開放原始碼框架,旨在簡化 AI 代理的端對端開發作業。這項工具將軟體工程原則套用至代理建立作業,可讓您自動調度管理複雜的工具、管理狀態,並輕鬆啟動內建的開發人員 UI,以便進行測試和部署。
  • Gemini Enterprise Agent Platform (GEAP):企業級託管和自動調度管理環境,用於在 Google Cloud 部署 AI 代理。

2. 設定和需求

啟動 Cloud Shell

雖然您可以透過筆電遠端操作 Google Cloud,但在本程式碼實驗室中,您將使用 Google Cloud Shell,這是在雲端執行的指令列環境。

在 Google Cloud 控制台右上方的工具列,點選「Cloud Shell」圖示:

啟用 Cloud Shell

佈建並連線至環境的作業需要一些時間才能完成。完成後,您應該會看到類似下方的內容:

Google Cloud Shell 終端機螢幕截圖,顯示環境已連線

這個虛擬機器已預先安裝所有必要的開發人員工具,並提供永久的 5 GB 主目錄,而且可在 Google Cloud 運作,大幅提升網路效能並強化驗證功能。本程式碼實驗室的所有工作都可以在瀏覽器中完成。您不需要安裝任何項目。

初始化環境

開啟 Cloud Shell 並設定專案變數,確保所有指令都指定正確的基礎架構。

export PROJECT_ID=$(gcloud config get-value project)
gcloud config set project $PROJECT_ID
export REGION="us-central1"

啟用必要的 API

啟用最少量的 Google Cloud API,以便管理資料基礎、執行 Vertex AI 模型,以及在 Cloud Run 託管 ADK 代理。

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

檢查點:繼續或重新建構?

由於這是第 2 部分,代理需要第 1 部分的受控資料才能運作。請選擇您的路徑:

路徑 A:我剛完成第 1 部分,資源仍在執行中

太好了!前往目前使用的目錄,即可繼續操作。

cd ~/devrel-demos/data-analytics/governance-context

路徑 B:我略過第 1 部分,或已刪除資源 (已清理)

沒問題!我們在下方提供「快速通關」指令區塊。這會自動重建 BigQuery 資料湖泊、註冊切面類型,並套用管理中繼資料,與第 1 部分的操作完全相同。

# 1. Clone the repo and navigate to the working directory
git clone --depth 1 --filter=blob:none --sparse https://github.com/GoogleCloudPlatform/devrel-demos.git
cd devrel-demos
git sparse-checkout set data-analytics/governance-context
cd data-analytics/governance-context

# 2. Rebuild the BigQuery datasets and tables
chmod +x ./setup_bq_tables.sh
./setup_bq_tables.sh

# 3. Register the Knowledge Catalog aspect type
gcloud dataplex aspect-types create official-data-product-spec \
    --location="${REGION}" \
    --project="${PROJECT_ID}" \
    --metadata-template-file-name="aspect_template.json"

# 4. Generate and apply aspects (governance rules)
chmod +x ./generate_payloads.sh ./apply_governance.sh
./generate_payloads.sh
./apply_governance.sh

3. 集中式資料控制層 (代管 MCP)

在實際的企業環境中,您需要安全、集中的資料控制層。我們不會建構自訂 MCP 伺服器容器並部署至 Cloud Run,而是直接將代理連結至 Google 代管的 Knowledge Catalog MCP 伺服器。

使用這個代管端點,可達到以下效果:

  1. 免維護:不需管理 MCP 伺服器的容器、資源調度或修補作業。
  2. 標準化:代理會使用 Model Context Protocol (SSE 傳輸),連線至標準、安全的 Google API 端點。
  3. 控管範圍:MCP 伺服器只會公開必要的中繼資料工具 (search_entries、lookup_context、lookup_entry),強制執行唯讀、管理優先的推論迴圈。

您可以透過下列安全網址,存取 Google 代管的 Knowledge Catalog MCP 伺服器:

https://dataplex.googleapis.com/mcp

由於這是第一方 Google API,代理必須使用標準 Google Cloud OAuth2 存取權杖進行驗證,而非 ID 權杖。我們會在應用程式程式碼中自動處理這項驗證。

4. 使用 ADK 建構代理後端

您擁有安全、受管理的資料控制層。現在,AI 代理需要一個架構來協調邏輯,例如處理使用者輸入內容、決定何時呼叫 MCP 伺服器,以及設定輸出內容格式。

我們將使用 Google 的 Agent Development Kit (ADK)。ADK 是以程式碼為優先的架構,會自動將代理邏輯包裝至 FastAPI 後端,並提供內建網頁介面,方便您立即測試。

在 Cloud Shell 編輯器中開啟代理程式碼

請在 Cloud Shell 編輯器中開啟檔案,方便您檢查、編輯及瞭解程式碼,而不是將整個檔案傾印到終端機。

在終端機中執行下列指令,並查看編輯器中的程式碼結構。這個應用程式是使用 Google 的 Agent Development Kit (ADK) 建構:

cd ~/devrel-demos/data-analytics/governance-context/mcp_server

# Copy the governance skill directory inside the application bundle so it packages during Cloud Run deployment
mkdir -p skills
cp -r ../.agents/skills/knowledge-catalog-governance skills/

cloudshell edit agent.py

(注意:agent.py 頂端包含樣板程式碼,用於處理 Google Cloud OAuth2 驗證和權杖重新整理,確保代理能安全地與 Google 代管的 Knowledge Catalog API 通訊)。

1. 載入原生技能

為了建構高度最佳化的代理,我們使用 ADK 的原生 load_skill_from_dir,從外部代理技能目錄載入管理指令。這種做法可實現漸進式揭露:

  • L1 中繼資料:代理在啟動時只會載入技能的名稱和說明。這項最少脈絡資訊可讓 LLM 判斷何時使用技能,而不會預先耗用大量詞元。
  • L2 指令:只有在模型判定相關時,才會在執行階段動態擷取 SKILL.md 內的完整指令集。
base_dir = Path(__file__).parent
governance_skill = load_skill_from_dir(
    base_dir / "skills" / "knowledge-catalog-governance"
)

# Bundle the skill and MCP tools together into a SkillToolset
governance_skill_toolset = skill_toolset.SkillToolset(
    skills=[governance_skill],
    additional_tools=[tools]
)

2. 代理自動化調度管理

ADK 可讓您鏈結多個代理,自動調度管理複雜的代理行為。我們定義了 SequentialAgent 工作流程,其中包含兩個專用代理:

  • governance_researcher:配備 governance_skill_toolset 和 Knowledge Catalog MCP tools。它會檢查查詢是否在 Data Catalog 和法規遵循範圍內,然後使用插入系統指令的環境變數查詢 Knowledge Catalog。
  • compliance_formatter: 負責將原始 JSON 中繼資料搜尋結果轉換為乾淨的回覆,或在要求超出範圍時,妥善說明範圍界限。
# 1. Researcher Agent (has access to the encapsulated SkillToolset)
governance_researcher = LlmAgent(
    name="governance_researcher",
    model=model_name,
    description="Dynamically interprets metadata schema (Booleans/Enums) and searches for assets using strict syntax.",
    instruction=f"""
    You are a governance researcher. Your job is to verify Knowledge Catalog metadata rules and find compliant assets for the user's query.
    
    YOUR ACTIVE ENVIRONMENT CONTEXT:
    - Google Cloud Project ID: {project_id}
    - Location (Region): {location}

    YOUR WORKFLOW:
    1. First, check if the user query is related to data analytics assets, database tables, or data compliance.
       - If YES: Call `load_skill` with `name="knowledge-catalog-governance"` to load the rules, then use search/lookup tools to locate a certified compliant table.
       - If NO (e.g., general chit-chat, unrelated tasks): Skip skill loading and output a JSON object indicating it is out of scope:
         {"error": "out_of_scope", "message": "The query does not pertain to data catalog search or governance compliance."}
    2. Populate the required projectId and location parameters in tool calls with the active environment parameters.
    3. Return the verified table's metadata in JSON format as your final research output.
    """,
    tools=[governance_skill_toolset, tools],
    output_key="research_data"
)

# 2. Formatter Agent (formats the output or explains out-of-scope errors)
compliance_formatter = LlmAgent(
    name="compliance_formatter",
    model=model_name,
    description="Formats the JSON research data into a helpful response for the user.",
    instruction="""
    You are the **Intelligent Data Governance Specialist**.
    Your job is to explain the findings of the governance research clearly to the user.

    **YOUR GOAL:**
    1. If the researcher found a matching table (valid JSON with table metadata):
       - Explain the logical connection between the User's Request, the Governance Schema (translated criteria), and the Recommended Table.
       - Use the following RESPONSE TEMPLATE:
         - **Analysis:** "I analyzed the metadata schema and translated your request into the following technical criteria:..."
         - **Recommendation:** "Based on this, I recommend the following table:"
           - **Table:** [Insert Table Name]
           - **Description:** [Insert Table Description]
         - **Verification:** "This asset is a verified match because: [Explain the verification details]."
    2. If the researcher returned an 'out_of_scope' error or no matching tables were found:
       - Apologize politely and explain that no data asset currently matches the strict governance criteria defined in `official-data-product-spec`.
       - Clearly state what domain of questions this agent is certified to answer (e.g., Data Catalog Search and Data Governance compliance).
    """
)

# 3. Orchestrated Workflow (Exported as root_agent)
root_agent = SequentialAgent(
    name="governance_workflow",
    description="Workflow to learn metadata rules, search with strict syntax, and recommend assets.",
    sub_agents=[
        governance_researcher,
        compliance_formatter,
    ]
)

設定執行階段變數

如要執行代理,必須指定代管 MCP 伺服器的位置,並設定專案和區域。我們會將這些變數儲存到 .env 檔案,ADK 會在執行階段讀取該檔案。

執行下列指令,產生 .env 檔案。請注意,MCP_SERVER_URL 會直接指向 Google 代管的 Knowledge Catalog API 端點:

export MCP_SERVER_URL="https://dataplex.googleapis.com/mcp"

echo MCP_SERVER_URL=$MCP_SERVER_URL > .env
echo GOOGLE_GENAI_USE_VERTEXAI=1 >> .env
echo GOOGLE_CLOUD_PROJECT=$PROJECT_ID >> .env
echo GOOGLE_CLOUD_LOCATION=$REGION >> .env

5. 在本機執行及測試代理

將代理部署至雲端前,請先在 Cloud Shell 本機執行,確認其行為。由於代理依賴多個 Python 套件 (包括 Google Cloud Logging 和 ADK 程式庫),因此我們會設定本機虛擬環境,以便安裝這些依附元件。

在 Cloud Shell 本機執行時,代理會自動使用有效的 Google Cloud 使用者憑證,因此已具備存取 Vertex AI 和 Knowledge Catalog 的必要權限。

  1. 前往 mcp_server 目錄,建立虛擬環境並安裝依附元件:
cd ~/devrel-demos/data-analytics/governance-context/mcp_server

# Create a virtual environment using uv
uv venv
source .venv/bin/activate

# Install the dependencies listed in requirements.txt
uv pip install -r requirements.txt
  1. 在終端機中啟動互動式即時通訊工作階段:
adk run .
  1. 課程開始後,您會看到提示。輸入查詢,測試代理的管理邏輯:
I need the Q1 revenue summary for our internal board meeting.

代理會處理您的要求,透過代管 MCP 伺服器查詢 Knowledge Catalog,並直接在終端機輸出建議和理由。

  1. 如要結束互動式工作階段,請輸入 exit 或 quit (或按下 Ctrl+C)。結束後,您可以停用虛擬環境:
deactivate

6. 將代理部署至正式環境

在本機驗證代理後,即可將代理部署至 Google Cloud,用於正式環境。

建立服務帳戶

基於安全考量,部署的代理不應以您的個人憑證執行。我們會遵循最小權限原則,為代理建立獨立身分 (knowledge-catalog-agent-sa)。

執行下列指令,建立服務帳戶:

export AGENT_SA=knowledge-catalog-agent-sa
export AGENT_SERVICE_ACCOUNT="${AGENT_SA}@${PROJECT_ID}.iam.gserviceaccount.com"

gcloud iam service-accounts create ${AGENT_SA} \
    --display-name="Service Account for Knowledge Catalog Agent"

授予權限

雖然代理會將管理檢查委派給 MCP 伺服器,但仍需要基本權限才能運作。

gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:$AGENT_SERVICE_ACCOUNT" \
  --role="roles/aiplatform.user"

gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:$AGENT_SERVICE_ACCOUNT" \
  --role="roles/dataplex.catalogAdmin"

gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:$AGENT_SERVICE_ACCOUNT" \
  --role="roles/bigquery.dataViewer"

gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:$AGENT_SERVICE_ACCOUNT" \
  --role="roles/mcp.toolUser"

gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:$AGENT_SERVICE_ACCOUNT" \
  --role="roles/viewer"

部署至 Cloud Run

最後,將代理部署至 Cloud Run。下列指令會使用目前目錄中的 Dockerfile 建構容器映像檔、上傳至 Artifact Registry,並部署至 Cloud Run。這項作業會在 1 至 3 分鐘內完成。

gcloud run deploy knowledge-catalog-agent \
  --source . \
  --project=$PROJECT_ID \
  --region=$REGION \
  --service-account=$AGENT_SERVICE_ACCOUNT \
  --allow-unauthenticated \
  --clear-base-image \
  --labels created-by=adk

指令執行完畢後,會輸出服務網址 (例如 https://knowledge-catalog-agent-xyz.run.app)。點選該連結,即可開啟完全受控的生成式 AI 對話介面。

12a5fa4c2aaf381f.png

7. 測試正式版代理

代理已上線,現在來測試管理情境。邏輯維持不變,但您現在是與已部署的 ADK Web Playground 互動,以視覺化方式呈現內部狀態和工具執行情形。

在瀏覽器中開啟上一步生成的服務網址 (例如 https://knowledge-catalog-agent-xyz.run.app)。貼上以下提示詞:

"My dashboard needs to show what's happening right now with our ad spend. I can't wait for the overnight load. What do you recommend?"

在開發人員 UI 中觀察代理的推論過程:

  1. 意圖辨識:代理剖析「現在」和「等不及隔夜」。
  2. 中繼資料查詢:使用查詢 [PROJECT_ID].us-central1.official-data-product-spec.update_frequency=REALTIME_STREAMING 呼叫 MCP 工具 search_entries。
  3. 選取:表示資料表 mkt_realtime_campaign_performance 符合這些條件。
  4. 回覆:代理建議使用即時資料表。

e0da615724199e.png

重要性:

如果沒有這項治理中繼資料,LLM 可能會直接推薦 fin_monthly_closing_internal 資料表,因為該資料表有名為「ad_spend」的資料欄,但忽略了資料已過時 24 小時。中繼資料背景資訊可避免業務錯誤。

您也可以測試「Board Meeting」提示,看看代理如何根據資料產品層級,切換至不同資料表:

"We are preparing the deck for an internal Board of Directors meeting next week. I need the numbers to be absolutely finalized, trustworthy, and kept strictly confidential. Which table is safe to use?"

8. 清除

為避免系統向您的 Google Cloud 帳戶收取費用,請按照下列步驟,刪除本程式碼實驗室建立的所有基礎架構。

刪除資料湖泊

使用清理指令碼,拆除 BigQuery 資料表、資料集和 Knowledge Catalog 剖面定義。

cd ~/devrel-demos/data-analytics/governance-context
chmod +x ./cleanup_data_lake.sh
./cleanup_data_lake.sh

刪除 Cloud Run 服務

移除運算資源,停止對執行中的容器計費。

gcloud run services delete knowledge-catalog-agent --region=$REGION --quiet

清理建構構件和測試環境儲存空間

部署 ADK 代理程式時,系統會自動建構容器映像檔,並將原始碼上傳至暫時的 Cloud Storage bucket。

移除 Artifact Registry 存放區和 Cloud Storage 暫存 bucket:

# Delete the repository used for the agent build
gcloud artifacts repositories delete cloud-run-source-deploy \
    --location=$REGION \
    --quiet

# Delete the staging bucket created by Cloud Run source deploy
gcloud storage rm --recursive gs://run-sources-${PROJECT_ID}-${REGION}

刪除身分和權限

請先移除 IAM 政策繫結,再刪除服務帳戶。

# Remove IAM roles granted to the Agent Service Account
gcloud projects remove-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:$AGENT_SERVICE_ACCOUNT" \
  --role="roles/aiplatform.user" --quiet

gcloud projects remove-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:$AGENT_SERVICE_ACCOUNT" \
  --role="roles/dataplex.catalogViewer" --quiet

gcloud projects remove-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:$AGENT_SERVICE_ACCOUNT" \
  --role="roles/mcp.toolUser" --quiet

gcloud projects remove-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:$AGENT_SERVICE_ACCOUNT" \
  --role="roles/bigquery.dataViewer" --quiet

# Delete the Service Account
gcloud iam service-accounts delete $AGENT_SERVICE_ACCOUNT --quiet

移除本機設定

最後,在 Cloud Shell 清理本機設定檔和環境變數。

# Uninstall the AGY CLI plugin
agy plugin uninstall dataplex

# Remove local repository files and unset variables
cd ~
rm -rf ~/devrel-demos
unset MCP_SERVER_URL
unset AGENT_SERVICE_ACCOUNT

9. 恭喜!

您已成功部署具備管理意識的端對端生成式 AI 代理。

在本程式碼實驗室的兩個部分中,您不只學會簡單的提示工程,還實作了可部署於正式環境的強大架構。將資料治理視為生成式 AI 的先決條件,建立系統化方法,防止模型擷取未經認證或幻覺資料。

重點整理

  • 透過中繼資料實現確定性 AI:您不依賴 LLM 根據資料欄名稱猜測正確的資料表,而是使用 Google 代管的 Knowledge Catalog MCP 伺服器強制執行嚴格的推論迴圈,要求模型先驗證資料認證,再推薦資料表。
  • 分離式架構:前端代理不需要包含資料庫邏輯,只要透過 MCP 標準通訊即可。這表示日後任何 AI 模型或用戶端,都能插入同一個受控管的後端。
  • 分散權責:您已隔離 IAM 身分,套用最小權限原則。面向使用者的 ADK 代理,其權限僅限於模型叫用和 API 轉送。
  • 程式碼優先的代理調度管理:您使用 Google Agent Development Kit (ADK),立即將 Python 代理邏輯包裝成可擴充的 FastAPI 後端,並利用內建的開發人員 UI,以視覺化方式呈現及偵錯代理的內部工具執行作業。

後續步驟