Autenticar usando a chave de API com o gerenciador de autenticação

Para permitir que seus agentes façam a autenticação em ferramentas externas, como as APIs Google Maps ou Weather, configure a autenticação de saída usando provedores de autenticação de chave de API no gerenciador de autenticação de identidade do agente.

Os provedores de autenticação de chave de API gerenciam suas chaves criptográficas. Esse recurso elimina a necessidade de codificar chaves no código do agente ou gerenciá-las manualmente.

Fluxo de trabalho da chave de API

Os provedores de autenticação de chave de API usam a identidade do agente e não exigem o consentimento do usuário. O Google toma medidas para ajudar a proteger a chave de API durante o armazenamento. Quando você usa o Kit de desenvolvimento de agentes (ADK), ele recupera e injeta automaticamente a chave de API nos cabeçalhos de invocação da ferramenta.

Antes de começar

  1. Verifique se você escolheu o método de autenticação correto.
  2. Ative a API Agent Identity.

    Funções necessárias para ativar APIs

    Para ativar as APIs, é necessário ter o papel do IAM de administrador de uso do serviço (roles/serviceusage.serviceUsageAdmin), que contém a permissão serviceusage.services.enable. Saiba como conceder papéis.

    Ativar a API

  3. Crie e implante um agente.

  4. Receba uma chave de API do serviço de terceiros ao qual você quer se conectar.

  5. Verifique se você tem os papéis necessários para concluir essa tarefa.

Funções exigidas

Para receber as permissões necessárias para criar e usar um provedor de autenticação de chave de API, peça ao administrador para conceder a você os seguintes papéis do IAM no projeto:

Para mais informações sobre a concessão de papéis, consulte Gerenciar o acesso a projetos, pastas e organizações.

Esses papéis predefinidos contêm as permissões necessárias para criar e usar um provedor de autenticação de chave de API. Para acessar as permissões exatas que são necessárias, expanda a seção Permissões necessárias:

Permissões necessárias

As seguintes permissões são necessárias para criar e usar um provedor de autenticação de chave de API:

  • Para criar provedores de autenticação: agentidentity.authProviders.create
  • Para usar provedores de autenticação:
    • agentidentity.authProviders.retrieveCredentials
    • aiplatform.endpoints.predict
    • aiplatform.sessions.create

Essas permissões também podem ser concedidas com papéis personalizados ou outros papéis predefinidos.

Receber uma chave de API do serviço de terceiros

Antes de criar um provedor de autenticação, receba uma chave de API do serviço de terceiros ao qual você quer que seu agente se conecte.

Se você estiver se conectando a um serviço de terceiros fora do Google Cloud, receba a chave de API do portal do desenvolvedor desse serviço e pule as etapas desta seção.

Se você estiver se conectando aos Google Cloud serviços (como o Cloud Translation ou o Google Maps), poderá gerar e configurar uma chave de API seguindo estas etapas:

  1. No Google Cloud console, ative os serviços de API necessários para seu projeto:

    1. No Google Cloud console, acesse a página APIs e serviços >Biblioteca.

      Acessar APIs e serviços >Biblioteca

    2. Pesquise e ative as APIs que seu agente usa, como a API Cloud Translation ou a API Google Maps Weather.
    3. Copie a string de chave de API gerada.
  2. Configure sua chave de API:

    1. No Google Cloud console, acesse a página APIs e serviços >Credenciais.

      Acessar APIs e serviços >Credenciais

    2. Clique em Criar credenciais >Chave de API.
    3. Na caixa de diálogo Criar chave de API, faça o seguinte:
      1. Insira um nome exclusivo para sua chave de API.
      2. Para restringir a chave às APIs específicas que você ativou, selecione essas APIs na lista Selecionar restrições de API.
      3. Opcional: na seção Restrinja sua chave para reduzir os riscos de segurança , selecione um tipo de aplicativo para restringir o acesso.
      4. Clique em Criar.
  3. Valide sua chave de API enviando uma solicitação de teste ao endpoint do serviço.

    • Para verificar uma chave de API Cloud Translation, execute o seguinte comando:

      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"

      Substitua YOUR_API_KEY pela chave de API gerada.

    • Para verificar uma chave de API Google Maps Weather, execute o seguinte comando:

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

      Substitua YOUR_API_KEY pela chave de API gerada.

    Se a chave de API for válida e estiver configurada corretamente, o serviço vai retornar os dados solicitados.

Criar um provedor de autenticação de chave de API

Crie um provedor de autenticação para definir a configuração e as credenciais de aplicativos de terceiros.

Autenticar no código do agente

Para autenticar seu agente, você pode usar o ADK.

ADK

Faça referência ao provedor de autenticação no código do agente usando o conjunto de ferramentas MCP no ADK.

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

Exemplo: como se conectar ao MCP do Google Maps

O exemplo a seguir demonstra uma configuração agent.py que conecta um agente a um servidor MCP do Google Maps:

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

Faça referência ao provedor de autenticação no código do agente usando uma ferramenta de função autenticada no 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)

Exemplo: como se conectar à API Google Maps Weather

O exemplo a seguir demonstra uma configuração agent.py que conecta um agente à API Google Maps Weather usando uma ferramenta de função autenticada:

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

Faça referência ao provedor de autenticação no código do agente usando o conjunto de ferramentas MCP do registro de agentes no ADK.

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

  

Implantar o agente

Ao implantar seu agente no Google Cloud, verifique se a identidade do agente está ativada.

Se você estiver implantando no ambiente de execução de agentes da Gemini Enterprise Agent Platform , use a identity_type=AGENT_IDENTITY flag:

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

A seguir