驗證工具和資源

Agent Registry 可讓自動化調度管理代理安全地驗證探索到的遠端代理、Model Context Protocol (MCP) 工具集和Google Cloud 服務。使用 Agent Identity 和 Agent Identity 驗證管理工具,您可以在叫用透過 Agent Registry 探索到的功能時,設定憑證、繫結和自訂 HTTP 標頭。

事前準備

向工具和資源進行驗證前,請先完成下列操作:

  1. 設定 Agent Registry。
  2. 取得已啟用 Agent Registry 的管理專案專案 ID。

  3. 安裝或升級至最新版本 Agent Development Kit (ADK),並加入 A2A、Agent Identity 和 MCP 依附元件:

    pip

    pip install --upgrade "google-adk[a2a,agent-identity,mcp]"
    

    uv

    uv add "google-adk[a2a,agent-identity,mcp]"
    

    請務必升級至 google-adk>=1.29.0 以上版本。

  4. 如要使用應用程式預設憑證 (ADC) 進行驗證,請設定憑證:

    gcloud auth application-default login
    

    ADC 憑證必須具備必要的 Identity and Access Management (IAM) 權限,才能存取代理或工具互動的基礎 Google Cloud 服務。

  5. 設定下列環境變數:

    export GOOGLE_CLOUD_PROJECT=PROJECT_ID
    export GOOGLE_CLOUD_LOCATION=LOCATION
    export API_KEY=EXTERNAL_API_KEY
    

    更改下列內容:

    • PROJECT_ID:管理專案的專案 ID。
    • LOCATION:登錄檔區域或位置,例如 us-central1。
    • EXTERNAL_API_KEY:如果使用自訂標頭,請提供外部 API 金鑰。

瞭解驗證模式

為管理憑證,Agent Registry 仰賴 Agent Identity 進行內建Google Cloud 驗證,並使用驗證管理員管理驗證提供者和繫結。

代理可以使用自己的身分,或透過驗證管理工具,使用 API 金鑰或 OAuth 2.0 存取工具。無論您使用的是代理身分還是服務帳戶,代理的身分都是透過應用程式預設憑證 (ADC) 提供。

如需在不使用驗證管理工具的情況下進行驗證,請直接在 ADK 要求中提供自訂 HTTP 標頭。

如要判斷最適合您用途的方法,請參閱「驗證模型」。

使用代理身分執行 Google Cloud 工具

對於 Google Cloud 服務 (例如 Gemini Enterprise Agent Platform 的 Agent Runtime 或 Cloud Storage),代理會使用自己的身分存取工具。無論您使用代理身分還是服務帳戶,這項存取權都是透過應用程式預設憑證 (ADC) 管理。

與代理相關聯的身分必須具備基礎 Google Cloud 服務所需的 IAM 權限。舉例來說,如果 MCP 工具管理 Compute Engine VM 執行個體,則代理身分除了代理登錄 API 檢視者角色外,還必須具備 Compute 執行個體管理員 (v1) 或更高權限等角色。

驗證遠端 A2A 代理

如果自動化調度管理代理使用自己的身分,連線至遠端 Google Agent2Agent (A2A) 代理,您必須明確將 httpx.AsyncClient 設為 Google 驗證標頭,並加入 get_remote_a2a_agent() 方法。

為避免超過預設的 HTTP 用戶端逾時限制,請定義自訂逾時。

以下範例說明如何使用 ADC 和自訂逾時設定 httpx.AsyncClient:

import os
import httpx
import google.auth
from google.auth.transport.requests import Request
from google.adk.integrations.agent_registry import AgentRegistry

class GoogleAuth(httpx.Auth):
    def __init__(self):
        self.creds, _ = google.auth.default()
    def auth_flow(self, request):
        if not self.creds.valid:
            self.creds.refresh(Request())
        request.headers["Authorization"] = f"Bearer {self.creds.token}"
        yield request

# Initialize the registry client
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT")
location = os.environ.get("GOOGLE_CLOUD_LOCATION", "global")

if not project_id:
    raise ValueError("GOOGLE_CLOUD_PROJECT environment variable not set.")

registry = AgentRegistry(
    project_id=project_id,
    location=location,
)

# Configure the HTTP client with GoogleAuth and a 60-second timeout
httpx_client = httpx.AsyncClient(auth=GoogleAuth(), timeout=httpx.Timeout(60.0))

# Connect to a remote A2A agent using its resource name in short or full format
# Short formats automatically imply the client's configured project and location
# Short format: "agents/AGENT_ID"
# Full format: f"projects/{project_id}/locations/{location}/agents/AGENT_ID"
agent_name = "agents/AGENT_ID"
my_remote_agent = registry.get_remote_a2a_agent(
    agent_name=agent_name,
    httpx_client=httpx_client,
)

將 AGENT_ID 替換為註冊代理人的 ID。

驗證 MCP 工具

如果自動化調度管理代理使用自己的身分存取 MCP 工具集,您可以使用 ADC 和 get_mcp_toolset() 方法初始化註冊資料庫用戶端:

import os
from google.adk.integrations.agent_registry import AgentRegistry

# Initialize the registry client
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT")
location = os.environ.get("GOOGLE_CLOUD_LOCATION", "global")

if not project_id:
    raise ValueError("GOOGLE_CLOUD_PROJECT environment variable not set.")

registry = AgentRegistry(
    project_id=project_id,
    location=location,
)

# Retrieve an MCP toolset using its resource name in short or full format
# Short formats automatically imply the client's configured project and location
# Short format: "mcpServers/SERVER_ID"
# Full format: f"projects/{project_id}/locations/{location}/mcpServers/SERVER_ID"
mcp_server_name = "mcpServers/SERVER_ID"
my_mcp_toolset = registry.get_mcp_toolset(mcp_server_name=mcp_server_name)

將 SERVER_ID 替換為已註冊 MCP 伺服器的 ID。

使用授權管理工具,管理自訂工具和委派存取權

當代理需要連線至外部 API、自訂工具或外部 MCP 伺服器時,您可以使用驗證管理工具管理憑證,不必在應用程式中硬式編碼。

您可以根據用途,為下列情境設定驗證管理工具:

這些模型需要您建立驗證提供者。接著,在代理程式登錄檔中建立繫結,將驗證提供者連結至登錄檔資源。

設定驗證提供者後,ADK 會管理自動化調度管理工具的驗證流程。如需範例,請參閱「解析 ADK 程式碼中的繫結」。

存取自訂工具

如要讓代理使用自己的憑證連結至外部或自訂工具,可以設定驗證管理員來處理 API 金鑰或雙腳 OAuth (2LO):

  1. 建立驗證提供者:在驗證管理工具中建立驗證提供者,用於儲存 API 金鑰或 OAuth 憑證。詳情請參閱「使用驗證管理員透過雙足式 OAuth 進行驗證」或「使用驗證管理員透過 API 金鑰進行驗證」。
  2. 繫結驗證提供者:如要讓自動化調度管理代理偵測目標的正確驗證提供者,您必須在代理註冊資料庫中,建立代理、目標資源和驗證提供者之間的繫結。有了繫結,您就不必在程式碼中手動定義驗證供應商:

    gcloud

    執行 gcloud agent-registry bindings create 指令,建立繫結,將代理明確連結至目標資源和驗證提供者。指定 --auth-provider-binding 資源名稱時,必須使用管理專案的專案 ID:

    gcloud agent-registry bindings create BINDING_NAME \
        --project=PROJECT_ID \
        --location=LOCATION \
        --display-name="DISPLAY_NAME" \
        --source-identifier="SOURCE_ID" \
        --target-identifier="TARGET_ID" \
        --auth-provider-binding="projects/PROJECT_ID/locations/LOCATION/authProviders/AUTH_PROVIDER_ID"
    

    Terraform

    設定 google_agent_registry_binding 資源,將代理和目標資源連結至驗證提供者:

    resource "google_agent_registry_binding" "custom_tool_binding" {
      project      = "PROJECT_ID"
      location     = "LOCATION"
      binding_id   = "BINDING_NAME"
      display_name = "DISPLAY_NAME"
    
      source {
        identifier = "SOURCE_ID"
      }
    
      target {
        identifier = "TARGET_ID"
      }
    
      auth_provider_binding {
        auth_provider = "projects/PROJECT_ID/locations/LOCATION/authProviders/AUTH_PROVIDER_ID"
      }
    }
    

    更改下列內容:

    • BINDING_NAME:繫結的專屬 ID。
    • PROJECT_ID:管理專案的專案 ID。
    • LOCATION:登錄檔區域或位置,例如 us-central1 或 global。
    • DISPLAY_NAME:繫結的人類可讀顯示名稱。
    • SOURCE_ID:來源代理的代理 ID,格式為 URN。
    • TARGET_ID:目標 MCP 伺服器或端點的註冊資料庫 ID,格式為 URN。
    • AUTH_PROVIDER_ID:驗證供應商的 ID。

    如要進一步瞭解如何管理這些連線,請參閱「管理繫結」。

代表使用者存取工具

如要讓代理代表個別使用者向遠端 MCP 伺服器或工具進行驗證,請透過驗證管理工具使用三足式 OAuth (3LO)。

驗證管理工具提供完全由 Google 代管的服務,用於處理 OAuth 權杖、使用者同意聲明和重新導向。使用者與代理互動,並觸發需要委派權限的工具時,平台會自動提示使用者同意、儲存憑證,並繼續工作流程:

  1. 建立驗證提供者:在驗證管理工具中建立驗證提供者,並設定 OAuth 重新導向 URI。詳情請參閱「使用驗證管理員透過三足式 OAuth 進行驗證」。
  2. 更新用戶端應用程式:更新應用程式用戶端,以處理 adk_request_credential 函式呼叫並管理使用者同意聲明。如需詳細操作說明,請參閱「更新用戶端應用程式」。
  3. 繫結驗證提供者:如要讓自動化調度管理代理偵測目標的正確驗證提供者,您必須在代理註冊資料庫中,建立代理、目標資源和驗證提供者之間的繫結。有了繫結,您就不必在程式碼中手動定義驗證供應商:

    gcloud

    執行 gcloud agent-registry bindings create 指令,建立繫結,將代理明確連結至目標資源和驗證提供者。指定 --auth-provider-binding 資源名稱時,必須使用管理專案的專案 ID:

    gcloud agent-registry bindings create BINDING_NAME \
        --project=PROJECT_ID \
        --location=LOCATION \
        --display-name="DISPLAY_NAME" \
        --source-identifier="SOURCE_ID" \
        --target-identifier="TARGET_ID" \
        --auth-provider-binding="projects/PROJECT_ID/locations/LOCATION/authProviders/AUTH_PROVIDER_ID" \
        --auth-provider-binding-scopes=SCOPES \
        --auth-provider-binding-continue-uri="https://REDIRECT_URI"
    

    Terraform

    使用 OAuth 2.0 範圍和繼續 URI 設定 google_agent_registry_binding 資源:

    resource "google_agent_registry_binding" "user_delegated_binding" {
      project      = "PROJECT_ID"
      location     = "LOCATION"
      binding_id   = "BINDING_NAME"
      display_name = "DISPLAY_NAME"
    
      source {
        identifier = "SOURCE_ID"
      }
    
      target {
        identifier = "TARGET_ID"
      }
    
      auth_provider_binding {
        auth_provider = "projects/PROJECT_ID/locations/LOCATION/authProviders/AUTH_PROVIDER_ID"
        scopes        = [SCOPES]
        continue_uri  = "https://REDIRECT_URI"
      }
    }
    

    更改下列內容:

    • BINDING_NAME:繫結的專屬 ID。
    • PROJECT_ID:管理專案的專案 ID。
    • LOCATION:登錄檔區域或位置,例如 us-central1 或 global。
    • DISPLAY_NAME:繫結的人類可讀顯示名稱。
    • SOURCE_ID:來源代理的代理 ID,格式為 URN。
    • TARGET_ID:目標 MCP 伺服器或工具資源的註冊資料庫 ID,格式為 URN。
    • AUTH_PROVIDER_ID:驗證供應商的 ID。
    • SCOPES:以半形逗號分隔的 OAuth 2.0 範圍清單,例如 https://www.googleapis.com/auth/cloud-platform。在 Terraform 中,請將每個範圍括在雙引號中。
    • REDIRECT_URI:使用者同意後,為驗證提供者設定的重新導向 URI。

    如要進一步瞭解如何管理這些連線,請參閱「管理繫結」。

解析 ADK 程式碼中的繫結

在 Agent Registry 建立驗證服務供應商繫結後,ADK 會處理驗證流程。

使用 AgentRegistry 用戶端擷取 MCP 工具組時,ADK 會自動解析與該伺服器相關聯的所有繫結,並套用正確的配置。您不需要在程式碼中手動設定憑證。

以下範例說明如何擷取已驗證的 MCP 工具集,並附加至代理:

import os
from google.adk.agents.llm_agent import LlmAgent
from google.adk.auth.credential_manager import CredentialManager
from google.adk.integrations.agent_identity import GcpAuthProvider
from google.adk.integrations.agent_registry import AgentRegistry

project_id = os.environ.get("GOOGLE_CLOUD_PROJECT")
location = os.environ.get("GOOGLE_CLOUD_LOCATION", "global")

if not project_id:
    raise ValueError("GOOGLE_CLOUD_PROJECT environment variable not set.")

# Register the auth provider
CredentialManager.register_auth_provider(GcpAuthProvider())

# Initialize the registry client
registry = AgentRegistry(
    project_id=project_id,
    location=location,
)

# Fetch the registered MCP toolset.
# The ADK applies the bindings configured in Agent Registry.
mcp_server_name = "mcpServers/SERVER_ID"
my_mcp_toolset = registry.get_mcp_toolset(mcp_server_name=mcp_server_name)

# Compose the agent
maps_agent = LlmAgent(
    name="maps_agent",
    model="gemini-1.5-flash",
    instruction=(
        "You are a local guide and navigation expert. Your goal is to provide "
        "accurate location information and directions.\n\n"
        "Rules:\n"
        "1. **Planning**: Before answering, plan how to use the tools to get "
        "the best information (e.g., search for a place first, then get details "
        "or directions).\n"
        "2. **Tool Usage**: Use the Maps MCP tools to find locations, addresses, "
        "and navigation details. Do not guess locations or distances.\n"
        "3. **Output Format**: Provide clear summaries of locations, including "
        "full addresses and key details. Use formatting to make recommendations "
        "easy to read.\n"
        "4. **Tone**: Be helpful, enthusiastic, and descriptive, with "
        "appropriate emojis to enhance the experience."
    ),
    tools=[my_mcp_toolset],
)

將 SERVER_ID 替換為已註冊 MCP 伺服器的 ID。

如果您設定 3LO 是為了代表使用者存取工具,則也必須將 continue_uri 提供給 get_mcp_toolset 方法。這個 URI 會指出使用者授予同意聲明後,系統會將其重新導向至何處:

import os
from google.adk.agents.llm_agent import LlmAgent
from google.adk.auth.credential_manager import CredentialManager
from google.adk.integrations.agent_identity import GcpAuthProvider
from google.adk.integrations.agent_registry import AgentRegistry

project_id = os.environ.get("GOOGLE_CLOUD_PROJECT")
location = os.environ.get("GOOGLE_CLOUD_LOCATION", "global")

if not project_id:
    raise ValueError("GOOGLE_CLOUD_PROJECT environment variable not set.")

# Register the auth provider
CredentialManager.register_auth_provider(GcpAuthProvider())

# Initialize the registry client
registry = AgentRegistry(
    project_id=project_id,
    location=location,
)

# Fetch the registered MCP toolset.
# The ADK applies the bindings configured in Agent Registry.
# For 3-legged OAuth (3LO), provide continue_uri.
mcp_server_name = "mcpServers/SERVER_ID"
my_mcp_toolset = registry.get_mcp_toolset(
    mcp_server_name=mcp_server_name,
    # Replace with your app's redirect URI:
    continue_uri="https://REDIRECT_URI"
)

# Compose the agent
maps_agent = LlmAgent(
    name="maps_agent",
    model="gemini-1.5-flash",
    instruction=(
        "You are a local guide and navigation expert. Your goal is to provide "
        "accurate location information and directions.\n\n"
        "Rules:\n"
        "1. **Planning**: Before answering, plan how to use the tools to get "
        "the best information (e.g., search for a place first, then get details "
        "or directions).\n"
        "2. **Tool Usage**: Use the Maps MCP tools to find locations, addresses, "
        "and navigation details. Do not guess locations or distances.\n"
        "3. **Output Format**: Provide clear summaries of locations, including "
        "full addresses and key details. Use formatting to make recommendations "
        "easy to read.\n"
        "4. **Tone**: Be helpful, enthusiastic, and descriptive, with "
        "appropriate emojis to enhance the experience."
    ),
    tools=[my_mcp_toolset],
)

更改下列內容:

  • SERVER_ID:已註冊 MCP 伺服器的 ID。
  • REDIRECT_URI:應用程式的重新導向 URI,使用者授予同意聲明後會導向至該處。

為外部工具使用自訂標頭

如需在不使用驗證管理工具的情況下驗證或傳遞要求標頭,請直接在 ADK 要求中提供自訂 HTTP 標頭。

初始化 AgentRegistry 用戶端時,提供 header_provider 回呼,即可設定自訂標頭。

header_provider 回呼會接收目前的執行內容,並傳回 HTTP 標頭字典。McpToolset 元件會自動將這些標頭附加至傳送至 MCP 伺服器的下游要求。

header_provider 回呼提供的自訂標頭只會傳送至目標 MCP 伺服器。自訂標頭不會用於向 Agent Registry API 本身進行驗證。API 一律仰賴 ADC。

以下範例說明如何為外部工具組提供 API 金鑰或自訂不記名權杖:

import os
from typing import Any
from google.adk.integrations.agent_registry import AgentRegistry

project_id = os.environ.get("GOOGLE_CLOUD_PROJECT")
location = os.environ.get("GOOGLE_CLOUD_LOCATION", "global")
external_api_key = os.environ.get("API_KEY")

# Define the custom header provider.
def my_auth_headers(context: Any) -> dict[str, str]:
    """Returns custom headers injected into MCP toolset requests."""
    return {
        "Authorization": f"Bearer {external_api_key}",
        "X-Custom-Context": "orchestrator-request"
    }

# Initialize the registry client.
# The header_provider is sent to the target MCP server during invocation.
# The header_provider is not used to authenticate against the Agent Registry API.
# The Agent Registry API always uses your Google ADC.
registry = AgentRegistry(
    project_id=project_id,
    location=location,
    header_provider=my_auth_headers
)

# Fetching the toolset automatically attaches the header_provider to the MCP server.
# Replace with the full resource name of your registered MCP server.
mcp_server_name = f"projects/PROJECT_ID/locations/LOCATION/mcpServers/EXTERNAL_SERVER_ID"
external_mcp_toolset = registry.get_mcp_toolset(mcp_server_name=mcp_server_name)

更改下列內容:

  • PROJECT_ID:管理專案的專案 ID。
  • LOCATION:登錄檔區域或位置,例如 us-central1。
  • EXTERNAL_SERVER_ID:已註冊外部 MCP 伺服器的 ID。

後續步驟

  • 瞭解如何使用 Agent Gateway,對已驗證的工具要求強制執行存取控管和網路邊界。