כשסוכן תזמור מפעיל סוכן מרוחק או ערכת כלים של Model Context Protocol (MCP) שהתגלו דרך Agent Registry, הוא צריך לבצע אימות מול שירות הבסיס Google Cloud שמספק את היכולות האלה.
במאמר הזה מוסבר איך לטפל באימות של משאבים ב-Agent Registry.
לפני שמתחילים
לפני שמאמתים את הגישה לכלים ולמשאבים, צריך לבצע את הפעולות הבאות:
- מגדירים את Agent Registry בפרויקט.
מתקינים את הגרסה האחרונה של הערכה לפיתוח סוכנים (ADK) או משדרגים אליה, עם התלויות הנדרשות של A2A:
צִפצוּף
pip install --upgrade "google-adk[a2a]"uv
uv add "google-adk[a2a]"צריך לשדרג לפחות ל-
google-adk>=1.29.0.כדי להשתמש ב-Application Default Credentials (ADC) לאימות, צריך להגדיר אותם:
gcloud auth application-default loginלפרטי הכניסה של ADC צריכות להיות ההרשאות הנדרשות לניהול זהויות והרשאות גישה (IAM) בשירותים הבסיסיים שאיתם הסוכנים או הכלים יוצרים אינטראקציה. Google Cloud
כדי לפעול לפי הדוגמאות במדריך הזה, צריך להגדיר משתני סביבה, למשל:
export GOOGLE_CLOUD_PROJECT=PROJECT_ID export GOOGLE_CLOUD_LOCATION=LOCATION export API_KEY=EXTERNAL_API_KEYמחליפים את מה שכתוב בשדות הבאים:
PROJECT_ID: מזהה הפרויקט.-
LOCATION: האזור או המיקום של המאגר, למשלus-central1. -
EXTERNAL_API_KEY: אם משתמשים בכותרות בהתאמה אישית, מזינים את מפתח ה-API החיצוני.
מידע על מודלים של אימות
כדי לנהל את פרטי הכניסה, Agent Registry מסתמך על Agent Identity לאימות מובנה של Google Cloud ועל Agent Identity auth manager לספקי אימות וקישורים.
הסוכנים יכולים להשתמש בזהות שלהם או במנהל ההרשאות כדי לגשת לכלים באמצעות מפתחות API או OAuth. הזהות של הסוכן מסופקת באמצעות Application Default Credentials (ADC), בין אם אתם משתמשים בזהות הסוכן או בחשבונות שירות.
לחלופין, כדי לשלוח הקשר מתקדם לסוכן יעד, או אם ערכות כלים חיצוניות לא תומכות במנהל האימות של זהות הסוכן, אפשר לספק כותרות HTTP מותאמות אישית ישירות בבקשות ADK.
כדי לקבוע את הגישה הכי טובה לתרחיש שלכם לדוגמה, אפשר לעיין במאמר בנושא מודלים של אימות.
שימוש בזהות הסוכן עבור Google Cloud כלים
בשירותים כמו Agent Runtime בפלטפורמת הסוכנים של Gemini Enterprise או Cloud Storage, הסוכן משתמש בזהות שלו כדי לגשת לכלים. Google Cloud הגישה הזו מנוהלת באמצעות Application Default Credentials (ADC), בין אם אתם משתמשים ב-Agent Identity API או ב-חשבונות שירות.
לזהות שמשויכת לסוכן צריכות להיות הרשאות IAM שנדרשות לשירותי Google Cloud הבסיסיים. לדוגמה, אם כלי MCP מנהל מכונות וירטואליות של Compute Engine, לזהות של הסוכן צריכים להיות תפקידים כמו Compute Instance Admin (v1) או תפקיד ברמה גבוהה יותר, בנוסף לתפקיד 'צפייה ב-API של רישום סוכנים'.
אימות סוכני A2A מרוחקים
אם סוכן האורקסטרציה מתחבר לסוכן Google Agent2Agent (A2A) מרוחק באמצעות הזהות שלו, צריך לכלול באופן מפורש את httpx.AsyncClient
שמוגדר עם כותרות האימות של Google בשיטה get_remote_a2a_agent().
מומלץ להגדיר פסק זמן מותאם אישית כדי לא לחרוג ממגבלות ברירת המחדל של פסק הזמן של לקוח HTTP.
בדוגמה הבאה אפשר לראות איך מגדירים את httpx.AsyncClient באמצעות ADC וזמן קצוב לתפוגה בהתאמה אישית:
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,
)
אימות של כלי MCP
אם סוכן התזמור משתמש בזהות משלו כדי לגשת לערכת כלים של MCP, אפשר לאתחל את לקוח הרישום באמצעות ADC והשיטה get_mcp_toolset():
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,
)
# 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)
שימוש במנהל ההרשאות לכלים בהתאמה אישית ולהענקת גישה
כשהסוכן צריך להתחבר לממשקי API חיצוניים, לכלים מותאמים אישית או לשרתי MCP חיצוניים, אפשר להשתמש במנהל ההרשאות של זהות הסוכן כדי לנהל את פרטי הכניסה בלי לקודד אותם באפליקציה.
בהתאם לתרחיש השימוש, אפשר להגדיר את מנהל ההרשאות לתרחישים הבאים:
- גישה לכלים בהתאמה אישית: כדי שהסוכן יוכל לגשת לכלי באמצעות הזהות וההרשאות שלו, צריך לאמת את הסוכן באמצעות מפתחות API או הרשאה באמצעות OAuth 2.0 משרת-אל-שרת.
- גישה לכלים בשם משתמש: אימות הסוכן שפועל כמשתמש פרטי באמצעות OAuth תלת-רגלי (3LO). המודל הזה מומלץ אם הסוכן צריך לגשת לכלים בשם האדם שמקיים איתו אינטראקציה, ולכן נדרשת הסכמה מהמשתמש והרשאה מוקצית.
כדי להשתמש במודלים האלה, צריך ליצור ספק אימות. לאחר מכן, יוצרים קישור במרשם הסוכנים כדי לקשר את ספק האימות למשאבי המרשם.
אחרי שמגדירים את ספק האימות, ה-ADK מנהל את תהליך האימות של כלי התזמור. דוגמה מופיעה במאמר פתרון בעיות של קישורים בקוד ADK.
גישה לכלים בהתאמה אישית
אם רוצים שהסוכן יתחבר לכלים חיצוניים או מותאמים אישית באמצעות פרטי הכניסה שלו, אפשר להגדיר את מנהל האימות של זהות הסוכן כך שיטפל במפתחות API או ב-OAuth דו-רגלי (2LO):
- יוצרים את ספק האימות: יוצרים ספק אימות במנהל האימות של זהויות הסוכנים כדי לאחסן את מפתח ה-API או את פרטי הכניסה של OAuth. מידע נוסף זמין במאמרים בנושא אימות באמצעות OAuth דו-רגלי עם מנהל ההרשאות או אימות באמצעות מפתח API עם מנהל ההרשאות.
קישור ספק האימות: כדי שהסוכן שלכם לניהול תהליכים יוכל לזהות את ספק האימות הנכון עבור יעד, אתם צריכים ליצור קישור במאגר הסוכנים בין הסוכן שלכם לבין ספק האימות. כשמשתמשים בקישורים, לא צריך להגדיר ספקי אימות באופן ידני בקוד.
יוצרים קישור כדי לקשר באופן מפורש את הסוכן לספק האימות. כשמציינים את שם המשאב
--auth-provider, צריך להשתמש במזהה הפרויקט:gcloud agent-registry bindings create BINDING_NAME \ --project=PROJECT_ID \ --location=LOCATION \ --display-name="DISPLAY_NAME" \ --source-identifier="SOURCE_ID" \ --auth-provider="projects/PROJECT_ID/locations/LOCATION/connectors/AUTH_PROVIDER_ID" \מידע נוסף על ניהול החיבורים האלה זמין במאמר בנושא ניהול קישורים.
גישה לכלים מטעם משתמש
אם רוצים שהסוכן יבצע אימות לשרתים או לכלים מרוחקים של MCP בשם משתמש ספציפי, צריך להשתמש ב-OAuth תלת-רגלי (3LO) דרך מנהל האימות של זהות הסוכן.
מנהל ההרשאות מספק שירות שמנוהל באופן מלא על ידי Google לטיפול בטוקנים של OAuth, בהסכמת המשתמשים ובהפניות אוטומטיות. כשאתם יוצרים אינטראקציה עם הסוכן ומפעילים כלי שדורש הרשאות מוקצות, הפלטפורמה מציגה למשתמש באופן אוטומטי בקשת הסכמה, שומרת את פרטי הכניסה וממשיכה את תהליך העבודה:
- יוצרים את ספק האימות: יוצרים ספק אימות במנהל האימות של זהויות הסוכן ומגדירים את כתובות ה-URI להפניה אוטומטית של OAuth. מידע נוסף זמין במאמר בנושא אימות באמצעות OAuth תלת-רגלי עם מנהל הרשאות.
- עדכון אפליקציית הלקוח: צריך לעדכן את אפליקציית הלקוח כדי לטפל בקריאה לפונקציה
adk_request_credentialולנהל את הסכמת המשתמש. הוראות מפורטות זמינות במאמר בנושא עדכון האפליקציה בצד הלקוח. קישור ספק האימות: כדי שהסוכן שלכם לניהול תהליכים יוכל לזהות את ספק האימות הנכון עבור יעד, אתם צריכים ליצור קישור במאגר הסוכנים בין הסוכן שלכם לבין ספק האימות. כשמשתמשים בקישורים, לא צריך להגדיר ספקי אימות באופן ידני בקוד.
יוצרים קישור כדי לקשר באופן מפורש את הסוכן לספק האימות. כשמציינים את שם המשאב
--auth-provider, צריך להשתמש במזהה הפרויקט:gcloud agent-registry bindings create BINDING_NAME \ --project=PROJECT_ID \ --location=LOCATION \ --display-name="DISPLAY_NAME" \ --source-identifier="SOURCE_ID" \ --auth-provider="projects/PROJECT_ID/locations/LOCATION/connectors/AUTH_PROVIDER_ID" \מידע נוסף על ניהול החיבורים האלה זמין במאמר בנושא ניהול קישורים.
פתרון בעיות בהגדרות של קישורים בקוד ADK
אחרי שיוצרים את הקישור של ספק האימות במאגר סוכני ה-ADK, ה-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],
)
אם הגדרתם 3LO לגישה לכלים בשם משתמש, אתם צריכים גם לספק continue_uri לשיטה get_mcp_toolset. ה-URI הזה מציין לאן המשתמש מופנה אחרי שהוא מעניק הסכמה:
[...]
# 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],
)
שימוש בכותרות מותאמות אישית לכלים חיצוניים
כדי לשלוח הקשר מתקדם לסוכן יעד, או אם ערכות כלים חיצוניות לא תומכות במנהל אימות זהות הסוכן, אפשר לספק כותרות HTTP מותאמות אישית ישירות בבקשות ADK.
כדי להגדיר כותרות בהתאמה אישית, צריך לספק קריאה חוזרת (callback) header_provider כשמפעילים את לקוח AgentRegistry.
פונקציית הקריאה החוזרת header_provider מקבלת את הקשר הנוכחי של ההפעלה ומחזירה מילון של כותרות HTTP. רכיב RemoteA2aAgent או McpToolset
מצרף באופן אוטומטי את הכותרות האלה לבקשות במורד הזרם.
כותרות בהתאמה אישית שמועברות על ידי הקריאה החוזרת header_provider נשלחות רק לשירותי היעד Google Cloud , שהם הסוכנים או הכלים. אי אפשר להשתמש בכותרות בהתאמה אישית כדי לבצע אימות מול Agent Registry API עצמו. ה-API תמיד מסתמך על ADC.
בדוגמה הזו מוסבר איך מספקים מפתח API או טוקן bearer בהתאמה אישית לערכת כלים חיצונית:
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 the tool or agent requests."""
return {
"Authorization": f"Bearer {external_api_key}",
"X-Custom-Context": "orchestrator-request"
}
# Initialize the registry client.
# The header_provider is sent to the MCP server or agent 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)
המאמרים הבאים
- כך משתמשים ב-Agent Gateway כדי לאכוף בקרת גישה וגבולות רשת בבקשות שלכם לכלים מאומתים.