使用驗證管理工具,透過 API 金鑰進行驗證

如要讓代理程式向 Google 地圖或天氣 API 等外部工具進行驗證,請在代理程式身分驗證管理工具中,使用 API 金鑰驗證供應商設定外送驗證。

API 金鑰驗證供應商會為您管理加密金鑰。這項功能可讓您不必在代理程式碼中硬式編碼金鑰,也不必手動管理金鑰。

API 金鑰工作流程

API 金鑰驗證提供者會使用代理程式的身分,不需要使用者同意。Google 會採取措施,確保 API 金鑰在儲存期間的安全。使用 Agent Development Kit (ADK) 時,系統會自動擷取 API 金鑰,並將其插入工具呼叫標頭。

事前準備

  1. 確認您選擇的驗證方法正確無誤
  2. 啟用 Agent Identity Connector API。

    啟用 API 時所需的角色

    如要啟用 API,您需要具備服務使用情形管理員 IAM 角色 (roles/serviceusage.serviceUsageAdmin),其中包含 serviceusage.services.enable 權限。瞭解如何授予角色

    啟用 API

  3. 建立及部署代理程式

  4. 從要連結的第三方服務取得 API 金鑰

  5. 確認您具備完成這項工作所需的角色

必要的角色

如要取得建立及使用 API 金鑰驗證供應商所需的權限,請要求管理員授予您專案的下列 IAM 角色:

如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。

這些預先定義的角色具備建立及使用 API 金鑰驗證供應商所需的權限。如要查看確切的必要權限,請展開「Required permissions」(必要權限) 部分:

所需權限

如要建立及使用 API 金鑰驗證供應商,必須具備下列權限:

  • 如要建立驗證提供者: iamconnectors.connectors.create
  • 如何使用驗證提供者:
    • iamconnectors.connectors.retrieveCredentials
    • aiplatform.endpoints.predict
    • aiplatform.sessions.create

您或許還可透過自訂角色或其他預先定義的角色取得這些權限。

向第三方服務取得 API 金鑰

建立驗證供應商之前,請先從要讓代理程式連線的第三方服務取得 API 金鑰。

如要連線至 Google Cloud以外的第三方服務,請從該服務的開發人員入口網站取得 API 金鑰,並略過本節中的步驟。

如要連線至 Google Cloud 服務 (例如 Cloud Translation 或 Google 地圖),請按照下列步驟產生及設定 API 金鑰:

  1. 在 Google Cloud 控制台為專案啟用必要的 API 服務:

    1. 在 Google Cloud 控制台中,前往「APIs & Services」(API 與服務) >「Library」(程式庫) 頁面。

      依序前往「API 和服務」>「程式庫」

    2. 搜尋並啟用代理程式使用的 API,例如 Cloud Translation API 或 Google 地圖 Weather API。
    3. 複製產生的 API 金鑰字串。
  2. 設定 API 金鑰:

    1. 在 Google Cloud 控制台中,前往「API 和服務」>「憑證」頁面。

      依序前往「APIs & Services」(API 和服務)>「Credentials」(憑證)

    2. 依序按一下「建立憑證」>「API 金鑰」
    3. 在「建立 API 金鑰」對話方塊中,執行下列操作:
      1. 輸入不重複的 API 金鑰名稱。
      2. 如要限制金鑰只能使用您啟用的特定 API,請從「選取 API 限制」清單中選取這些 API。
      3. 選用步驟:在「限制金鑰以降低安全性風險」部分,選取要限制存取權的應用程式類型。
      4. 點選「建立」
  3. 向服務端點傳送測試要求,驗證 API 金鑰。

    • 如要驗證 Cloud Translation API 金鑰,請執行下列指令:

      curl -X POST \
        -H "Content-Type: application/json" \
        -H "X-goog-api-key: YOUR_API_KEY" \
        -d '{"q": "Hello world", "target": "es"}' \
        "https://translation.googleapis.com/language/translate/v2"

      YOUR_API_KEY 替換為您產生的 API 金鑰。

    • 如要驗證 Google 地圖 Weather API 金鑰,請執行下列指令:

      curl -X GET \
        "https://weather.googleapis.com/v1/currentConditions:lookup?key=YOUR_API_KEY&location.latitude=37.4220&location.longitude=-122.0841"

      YOUR_API_KEY 替換為您產生的 API 金鑰。

    如果 API 金鑰有效且設定正確,服務就會傳回要求的資料。

建立 API 金鑰驗證供應商

建立驗證提供者,定義第三方應用程式的設定和憑證。

如要建立 API 金鑰驗證供應商,請使用 Google Cloud 控制台或 Google Cloud CLI。

控制台

  1. 前往 Google Cloud 控制台的「Agent Registry」頁面。

    前往 Agent Registry

  2. 按一下要建立驗證提供者的代理程式名稱。
  3. 按一下「身分」
  4. 在「Auth Providers」(驗證提供者) 專區中,按一下「新增驗證提供者」
  5. 在「新增驗證供應商」窗格中,輸入名稱和說明。

    名稱只能使用小寫英文字母、數字或連字號,開頭須為小寫英文字母,結尾不得為連字號。

  6. 在「OAuth 類型」清單中選取「API 金鑰」
  7. 點按「Create and continue」(建立並繼續)
  8. 如要授予代理程式身分使用驗證提供者的權限,請按一下「Grant access」(授予存取權)。

    這會自動將「連結器使用者」(roles/iamconnectors.user) 角色指派給授權提供者資源上的代理程式身分。

  9. 在「Auth provider credentials」(驗證供應商憑證) 部分中,輸入 API 金鑰
  10. 按一下「新增供應商設定」

新建立的驗證供應商會顯示在「驗證供應商」清單中。

Google Cloud CLI

  1. 建立驗證提供者:

    gcloud alpha agent-identity connectors create AUTH_PROVIDER_NAME \
        --project="PROJECT_ID" \
        --location="LOCATION" \
        --api-key="API_KEY"
  2. 確認驗證供應商顯示在清單中,且狀態為 ENABLED
    gcloud alpha agent-identity connectors list \
       --project="PROJECT_ID" \
       --location="LOCATION"
  3. 授予存取權,允許代理程式和本機開發環境從驗證提供者擷取憑證。如要允許已部署的代理程式和個人使用者帳戶存取驗證供應商,請在驗證供應商資源上授予「連結器使用者」(roles/iamconnectors.user) 角色:

    1. 授予已部署代理的 SPIFFE ID (代理身分) 存取權:

      gcloud alpha agent-identity connectors add-iam-policy-binding AUTH_PROVIDER_NAME \
          --project="PROJECT_ID" \
          --location="LOCATION" \
          --role="roles/iamconnectors.user" \
          --member="principal://agents.global.org-ORGANIZATION_ID.system.id.goog/resources/aiplatform/projects/PROJECT_NUMBER/locations/LOCATION/reasoningEngines/ENGINE_ID"
    2. 授予個人使用者帳戶存取權,以進行本機開發和測試 (adk web):

      gcloud alpha agent-identity connectors add-iam-policy-binding AUTH_PROVIDER_NAME \
          --project="PROJECT_ID" \
          --location="LOCATION" \
          --role="roles/iamconnectors.user" \
          --member="user:USER_EMAIL"

更改下列內容:

  • PROJECT_ID: Google Cloud 專案 ID。
  • LOCATION:部署驗證供應商和代理程式的位置 (例如 us-west1)。
  • AUTH_PROVIDER_NAME:驗證供應商的名稱 (例如 bigquery-mcp-3lo-authprovider)。
  • AUTHORIZATION_URL:授權伺服器網址 (例如 https://accounts.google.com/o/oauth2/v2/auth)。
  • TOKEN_URL:權杖伺服器網址 (例如 https://oauth2.googleapis.com/token)。
  • CLIENT_ID:您從第三方服務產生的 OAuth 用戶端 ID。
  • CLIENT_SECRET:您從第三方服務產生的 OAuth 用戶端密鑰。
  • ORGANIZATION_ID:您的 Google Cloud 機構 ID。
  • PROJECT_NUMBER:您的 Google Cloud 專案編號。
  • ENGINE_ID:已部署的推論引擎代理程式 ID。
  • USER_EMAIL:您的個人使用者帳戶電子郵件地址。

在代理程式碼中進行驗證

如要驗證代理程式,可以使用 ADK。

ADK

在 ADK 中使用 MCP 工具集,在代理的程式碼中參照驗證供應商。

from google.adk.agents.llm_agent import LlmAgent
from google.adk.auth.credential_manager import CredentialManager
from google.adk.integrations.agent_identity import GcpAuthProvider, GcpAuthProviderScheme
from google.adk.tools.mcp_tool.mcp_session_manager import StreamableHTTPConnectionParams
from google.adk.tools.mcp_tool.mcp_toolset import McpToolset
from google.adk.auth.auth_tool import AuthConfig

# Register the Google Cloud auth provider so the CredentialManager can use it.
CredentialManager.register_auth_provider(GcpAuthProvider())

# Create the Google Cloud auth provider scheme using the auth provider's full resource name.
auth_scheme = GcpAuthProviderScheme(
    name="projects/PROJECT_ID/locations/LOCATION/connectors/AUTH_PROVIDER_NAME"
)

# Configure an MCP tool with the authentication scheme.
toolset = McpToolset(
    connection_params=StreamableHTTPConnectionParams(url="https://YOUR_MCP_SERVER_URL"),
    auth_scheme=auth_scheme,
)

# Initialize the agent with the authenticated tools.
agent = LlmAgent(
    name="AGENT_NAME",
    model="gemini-2.5-flash",
    instruction="AGENT_INSTRUCTIONS",
    tools=[toolset],
)

範例:連線至 Google 地圖 MCP

以下範例說明如何設定 agent.py,將代理連至 Google 地圖 MCP 伺服器:

import os
from google.adk.agents import Agent
from google.adk.apps import App
from google.adk.auth.credential_manager import CredentialManager
from google.adk.integrations.agent_identity import GcpAuthProvider, GcpAuthProviderScheme
from google.adk.models import Gemini
from google.adk.tools.mcp_tool.mcp_session_manager import StreamableHTTPConnectionParams
from google.adk.tools.mcp_tool.mcp_toolset import McpToolset

os.environ["GOOGLE_CLOUD_PROJECT"] = "PROJECT_ID"
os.environ["GOOGLE_GENAI_USE_VERTEXAI"] = "True"

# Register GCP auth provider for Agent Identity Credentials service
CredentialManager.register_auth_provider(GcpAuthProvider())

maps_auth_scheme = GcpAuthProviderScheme(
    name="projects/PROJECT_ID/locations/LOCATION/connectors/AUTH_PROVIDER_NAME"
)

maps_tools = McpToolset(
    connection_params=StreamableHTTPConnectionParams(url="https://mapstools.googleapis.com/mcp"),
    auth_scheme=maps_auth_scheme,
    errlog=None,
)

root_agent = Agent(
    name="root_agent",
    model=Gemini(model="gemini-2.5-flash"),
    instruction="You are a helpful AI assistant designed to provide accurate and useful information. You can also use your Google Maps tools to look up locations and directions.",
    tools=[maps_tools],
)

app = App(
    root_agent=root_agent,
    name="AGENT_NAME",
)

ADK

在代理的程式碼中,使用 ADK 的已驗證函式工具參照驗證提供者。

import httpx
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_identity import GcpAuthProviderScheme
from google.adk.apps import App
from google.adk.auth.auth_credential import AuthCredential
from google.adk.auth.auth_tool import AuthConfig
from google.adk.tools.authenticated_function_tool import AuthenticatedFunctionTool
from vertexai import agent_engines

# First, register Google Cloud auth provider
CredentialManager.register_auth_provider(GcpAuthProvider())

# Create Auth Config
spotify_auth_config = AuthConfig(
    auth_scheme=GcpAuthProviderScheme(
        name="projects/PROJECT_ID/locations/LOCATION/connectors/AUTH_PROVIDER_NAME"
    )
)

# Use the Auth Config in Authenticated Function Tool
spotify_search_track_tool = AuthenticatedFunctionTool(
    func=spotify_search_track, auth_config=spotify_auth_config
)

# Sample function tool
async def spotify_search_track(credential: AuthCredential, query: str) -> str | list:
    token = None
    if credential.http and credential.http.credentials:
        token = credential.http.credentials.token

    if not token:
        return "Error: No authentication token available."

    async with httpx.AsyncClient() as client:
        response = await client.get(
            "https://api.spotify.com/v1/search",
            headers={"Authorization": f"Bearer {token}"},
            params={"q": query, "type": "track", "limit": 1},
        )
        # Add your own logic here

agent = LlmAgent(
    name="AGENT_NAME",
    model="gemini-2.5-flash",
    instruction="AGENT_INSTRUCTIONS",
    tools=[spotify_search_track_tool],
)

app = App(
    name="APP_NAME",
    root_agent=agent,
)

vertex_app = agent_engines.AdkApp(app_name=app)

範例:連線至 Google 地圖 Weather API

以下範例展示 agent.py 設定,可使用經過驗證的函式工具,將代理程式連線至 Google 地圖 Weather API:

import os
import httpx
from google.adk.agents import Agent
from google.adk.apps import App
from google.adk.auth.auth_credential import AuthCredential
from google.adk.auth.auth_tool import AuthConfig
from google.adk.auth.credential_manager import CredentialManager
from google.adk.integrations.agent_identity import GcpAuthProvider, GcpAuthProviderScheme
from google.adk.models import Gemini
from google.adk.tools.authenticated_function_tool import AuthenticatedFunctionTool

os.environ["GOOGLE_CLOUD_PROJECT"] = "PROJECT_ID"
os.environ["GOOGLE_GENAI_USE_VERTEXAI"] = "True"

# Register GCP auth provider for Agent Identity Credentials service
CredentialManager.register_auth_provider(GcpAuthProvider())

weather_auth_config = AuthConfig(
    auth_scheme=GcpAuthProviderScheme(
        name="projects/PROJECT_ID/locations/LOCATION/connectors/AUTH_PROVIDER_NAME"
    )
)

async def get_weather(credential: AuthCredential, latitude: float, longitude: float) -> str | dict:
    """Gets the current weather conditions for a location using latitude and longitude."""
    api_key = None
    if http := credential.http:
        if http.additional_headers and "X-GOOG-API-KEY" in http.additional_headers:
            api_key = http.additional_headers["X-GOOG-API-KEY"]
        elif http.credentials and http.credentials.token:
            api_key = http.credentials.token

    if not api_key:
        return "Error: No API key available from the auth provider."

    params = {"location.latitude": latitude, "location.longitude": longitude, "key": api_key}
    async with httpx.AsyncClient() as client:
        response = await client.get(
            "https://weather.googleapis.com/v1/currentConditions:lookup",
            params=params,
        )
        if response.status_code != 200:
            return f"Error from Weather API: {response.status_code} - {response.text}"
        return response.json()

get_weather_tool = AuthenticatedFunctionTool(
    func=get_weather, auth_config=weather_auth_config
)

root_agent = Agent(
    name="root_agent",
    model=Gemini(model="gemini-2.5-flash"),
    instruction="You are a helpful AI assistant. You will use your weather tool to look up current conditions.",
    tools=[get_weather_tool],
)

app = App(
    root_agent=root_agent,
    name="AGENT_NAME",
)

ADK

在代理的程式碼中,使用 ADK 的 Agent Registry MCP 工具集參照驗證提供者。

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_identity import GcpAuthProviderScheme
from google.adk.tools.mcp_tool.mcp_session_manager import StreamableHTTPConnectionParams
from google.adk.tools.mcp_tool.mcp_toolset import McpToolset
from google.adk.auth.auth_tool import AuthConfig
from google.adk.integrations.agent_registry import AgentRegistry

# First, register Google Cloud auth provider
CredentialManager.register_auth_provider(GcpAuthProvider())

# Create Google Cloud auth provider scheme by providing Auth Provider full resource name
auth_scheme = GcpAuthProviderScheme(
    name="projects/PROJECT_ID/locations/LOCATION/connectors/AUTH_PROVIDER_NAME"
)

# Set Agent Registry
registry = AgentRegistry(project_id="PROJECT_ID", location="global")

toolset = registry.get_mcp_toolset(mcp_server_name="projects/PROJECT_ID/locations/global/mcpServers/agentregistry-00000000-0000-0000-0000-000000000000", auth_scheme=auth_scheme)

# Example MCP tool
toolset = McpToolset(
    connection_params=StreamableHTTPConnectionParams(url="MCP_URL"),
    auth_scheme=auth_scheme,
)

agent = LlmAgent(
    name="AGENT_NAME",
    model="MODEL_NAME",
    instruction="AGENT_INSTRUCTIONS",
    tools=[toolset],
)

  

部署代理

將代理部署至 Google Cloud時,請務必啟用代理身分。

如要部署至 Gemini Enterprise Agent Platform 的 Agent Runtime ,請使用 identity_type=AGENT_IDENTITY 標記:

import vertexai
from vertexai import types
from vertexai.agent_engines import AdkApp

# Initialize the Vertex AI client with v1beta1 API for Agent Identity support
client = vertexai.Client(
    project="PROJECT_ID",
    location="LOCATION",
    http_options=dict(api_version="v1beta1")
)

# Use the proper wrapper class for your Agent Framework (e.g., AdkApp)
app = AdkApp(agent=agent)

# Deploy the agent with Agent Identity enabled
remote_app = client.agent_engines.create(
    agent=app,
    config={
        "identity_type": types.IdentityType.AGENT_IDENTITY,
        "requirements": ["google-cloud-aiplatform[agent_engines,adk]", "google-adk[agent-identity]"],
    },
)

後續步驟