認証マネージャーで API キーを使用して認証する

エージェントが Google マップや天気予報 API などの外部ツールに対して認証できるようにするには、エージェント ID 認証マネージャーで API キー認証プロバイダを使用してアウトバウンド認証を構成します。

API キー認証プロバイダは、暗号鍵を管理します。この機能により、エージェントのコードに鍵をハードコードしたり、手動で鍵を管理したりする必要がなくなります。

API キーのワークフロー

API キー認証プロバイダはエージェントの ID を使用し、ユーザーの同意を必要としません。Google は、保存中の API キーを保護するための対策を講じています。Agent Development Kit(ADK)を使用すると、API キーが自動的に取得され、ツール呼び出しヘッダーに挿入されます。

始める前に

  1. 正しい認証方法を選択していることを確認します
  2. Agent Identity API を有効にします。

    API を有効にするために必要なロール

    API を有効にするには、serviceusage.services.enable 権限を含む Service Usage 管理者 IAM ロール(roles/serviceusage.serviceUsageAdmin)が必要です。詳しくは、ロールを付与する方法をご覧ください。

    API の有効化

  3. エージェントを作成してデプロイする

  4. 接続するサードパーティ サービスから API キーを取得します

  5. このタスクの完了に必要なロールが付与されていることを確認します

必要なロール

API キー認証プロバイダの作成と使用に必要な権限を取得するには、プロジェクトに対する次の IAM ロールを付与するよう管理者に依頼してください。

ロールの付与については、プロジェクト、フォルダ、組織へのアクセス権の管理をご覧ください。

これらの事前定義ロールには、API キー認証プロバイダの作成と使用に必要な権限が含まれています。必要とされる正確な権限については、「必要な権限」セクションを開いてご確認ください。

必要な権限

API キー認証プロバイダを作成して使用するには、次の権限が必要です。

  • 認証プロバイダを作成するには: agentidentity.authProviders.create
  • 認証プロバイダを使用するには:
    • agentidentity.authProviders.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 コンソールで、[API とサービス>ライブラリ] ページに移動します。

      [API とサービス] > [ライブラリ] に移動

    2. エージェントが使用する API(Cloud Translation API や Google Maps Weather API など)を検索して有効にします。
    3. 生成された API キー文字列をコピーします。
  2. API キーを構成します。

    1. Google Cloud コンソールで、[API とサービス>認証情報] ページに移動します。

      [API とサービス] > [認証情報] に移動

    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 Maps 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 キー認証プロバイダを作成する

認証プロバイダを作成して、サードパーティ アプリケーションの構成と認証情報を定義します。

エージェント コードで認証する

エージェントを認証するには、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 Google Cloud auth provider
CredentialManager.register_auth_provider(GcpAuthProvider())

# Create Google Cloud auth provider scheme
# Note: If using the legacy V1 API, the resource name uses 'connectors'
# instead of 'authProviders': projects/.../connectors/...
auth_scheme = GcpAuthProviderScheme(
    name="projects/PROJECT_ID/locations/LOCATION/authProviders/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 Maps MCP に接続する

次の例は、エージェントを Google マップ MCP サーバーに接続する agent.py 構成を示しています。

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 Google Cloud auth provider for Agent Identity Credentials service
CredentialManager.register_auth_provider(GcpAuthProvider())

maps_auth_scheme = GcpAuthProviderScheme(
    name="projects/PROJECT_ID/locations/LOCATION/authProviders/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
# Note: If using the legacy V1 API, the resource name uses 'connectors'
# instead of 'authProviders': projects/.../connectors/...
spotify_auth_config = AuthConfig(
    auth_scheme=GcpAuthProviderScheme(
        name="projects/PROJECT_ID/locations/LOCATION/authProviders/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 Maps Weather API に接続する

次の例は、認証済み関数ツールを使用してエージェントを Google Maps Weather API に接続する agent.py 構成を示しています。

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 Google Cloud 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/authProviders/AUTH_PROVIDER_NAME"
    )
)

async def get_weather(credential: AuthCredential, latitude: float, longitude: float) -> str | dict:
    """Gets current weather conditions for a location."""
    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 のエージェント レジストリ 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
# Note: If using the legacy V1 API, the resource name uses 'connectors'
# instead of 'authProviders': projects/.../connectors/...
auth_scheme = GcpAuthProviderScheme(
    name="projects/PROJECT_ID/locations/LOCATION/authProviders/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にデプロイするときは、エージェント ID が有効になっていることを確認してください。

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]"],
    },
)

次のステップ