跳转到内容

Google Cloud Agent Registry

在 ADK 中得到支持。Python v1.26.0Go v2.1.0预览

Agent Development Kit(ADK)中的 Agent Registry 客户端库允许开发人员查找、查询并连接到系统中注册的 AI Agent(人工智能代理)和 MCP Server(管理控制服务器)。 Google Cloud Agent 注册表(Registry)这使得可以使用受控制的组件(即那些遵循特定规则或标准的组件),动态地构建基于代理的应用程序。

使用场景

  • 加速开发:可以轻松地从中央目录中找到并重用现有的代理程序和工具(适用于 MCP 服务器),而无需重新开发它们。
  • 动态集成(Dynamic Integration)在运行时发现代理(agent)和 MCP 服务器的端点(endpoints),从而使应用程序能够更好地应对环境中的变化。
  • 加强治理(Enhanced Governance)在您的 ADK(Application Development Kit)应用程序中,使用来自注册表的、经过审核和验证的组件。

先决条件

  • A Google Cloud 项目.
  • The Agent Registry API 已在您的 Google Cloud 项目中启用该功能。
  • 您的环境已配置了身份验证机制。您应该使用相应的凭据登录。 应用程序默认设置 凭据(Credentials) (gcloud auth application-default login).
  • 环境变量 GOOGLE_CLOUD_PROJECT 将其设置为你的项目 ID,然后…… GOOGLE_CLOUD_LOCATION 将其设置为相应的区域(例如: global, us-central1).
  • 已为您使用的语言安装了 ADK,具体安装方法如文档中所述。 安装.

有关如何从 ADK 代理连接到 Google Cloud 的更多信息,请参阅…… 连接到 Google Cloud 和 Agent Platform。.

安装

The 代理注册表(Agent Registry) 集成(integration)是 ADK 核心库(core ADK library)的重要组成部分。

pip install google-adk

必需的依赖项

The google.adk.integrations.agent_registry 该模块在模块范围内同时导入了 A2A SDK 和 Agent Identity 身份认证提供者(auth provider)。 AgentRegistry 引发(某种反应或问题);提高(水平、价格等) ImportError **仅进行核心组件的安装(core-only installation)**:请同时安装以下两个组件: a2a 和 agent-identity extras:

pip install "google-adk[a2a,agent-identity]"
go get google.golang.org/adk/v2

客户居住在……(具体地址未提供)。 google.golang.org/adk/v2/agentregistry 只需要安装核心模块的相关组件,因此无需额外安装任何其他内容。

与 Agent 一起使用

在 ADK (Application Development Kit)代理中使用 Agent Registry 集成的主要方法是:通过 Agent Registry 客户端动态地获取远程代理或工具集。

from google.adk.agents.llm_agent import LlmAgent
from google.adk.integrations.agent_registry import AgentRegistry
import os

# 1. Initialization
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,
)

# 2. Listing Resources
print("Listing Agents...")
agents_response = registry.list_agents()
for agent in agents_response.get("agents", []):
    print(f"  - {agent.get('name')} ({agent.get('displayName')})")

print("Listing MCP Servers...")
mcp_servers_response = registry.list_mcp_servers()
for server in mcp_servers_response.get("mcpServers", []):
    print(f"  - {server.get('name')} ({server.get('displayName')})")

# 3. Using a Remote A2A Agent
# Replace with the full resource name of your registered agent
agent_name = f"projects/{project_id}/locations/{location}/agents/YOUR_AGENT_ID"
my_remote_agent = registry.get_remote_a2a_agent(agent_name=agent_name)

# 4. Using an MCP Toolset
# Replace with the full resource name of your registered MCP server
mcp_server_name = f"projects/{project_id}/locations/{location}/mcpServers/YOUR_MCP_SERVER_ID"
my_mcp_toolset = registry.get_mcp_toolset(mcp_server_name=mcp_server_name)

# 5. Example Agent Composition
main_agent = LlmAgent(
    model="gemini-flash-latest", # Or your preferred model
    name="demo_agent",
    instruction="You can leverage registered tools and sub-agents.",
    tools=[my_mcp_toolset],
    sub_agents=[my_remote_agent],
)
package main

import (
    "cmp"
    "context"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"

    "google.golang.org/adk/v2/agent"
    "google.golang.org/adk/v2/agent/llmagent"
    "google.golang.org/adk/v2/agentregistry"
    "google.golang.org/adk/v2/cmd/launcher"
    "google.golang.org/adk/v2/cmd/launcher/full"
    "google.golang.org/adk/v2/model/gemini"
    "google.golang.org/adk/v2/tool"
)

func main() {
    ctx := context.Background()

    // 1. Initialization
    projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
    if projectID == "" {
        log.Fatal("GOOGLE_CLOUD_PROJECT environment variable not set.")
    }
    location := cmp.Or(os.Getenv("GOOGLE_CLOUD_LOCATION"), "global")

    registry, err := agentregistry.New(ctx, agentregistry.Config{
        ProjectID: projectID,
        Location:  location,
    })
    if err != nil {
        log.Fatalf("Failed to create the registry client: %v", err)
    }

    // 2. Listing Resources. The All* iterators fetch pages on demand and
    // report a failed page fetch as a single (nil, error).
    fmt.Println("Listing Agents...")
    for a, err := range registry.AllAgents(ctx) {
        if err != nil {
            log.Fatalf("Failed to list agents: %v", err)
        }
        fmt.Printf("  - %s (%s)\n", a.Name, a.DisplayName)
    }

    fmt.Println("Listing MCP Servers...")
    for s, err := range registry.AllMCPServers(ctx) {
        if err != nil {
            log.Fatalf("Failed to list MCP servers: %v", err)
        }
        fmt.Printf("  - %s (%s)\n", s.Name, s.DisplayName)
    }

    // 3. Using a Remote A2A Agent
    // Replace with the full resource name of your registered agent
    agentName := fmt.Sprintf("projects/%s/locations/%s/agents/YOUR_AGENT_ID", projectID, location)
    myRemoteAgent, err := registry.RemoteAgent(ctx, agentName)
    if err != nil {
        log.Fatalf("Failed to resolve the remote agent: %v", err)
    }

    // 4. Using an MCP Toolset
    // Replace with the full resource name of your registered MCP server
    mcpServerName := fmt.Sprintf("projects/%s/locations/%s/mcpServers/YOUR_MCP_SERVER_ID", projectID, location)
    myMCPToolset, err := registry.MCPToolset(ctx, mcpServerName)
    if err != nil {
        log.Fatalf("Failed to connect to the MCP server: %v", err)
    }

    // 5. Example Agent Composition
    model, err := gemini.NewModel(ctx, "gemini-flash-latest", &genai.ClientConfig{})
    if err != nil {
        log.Fatalf("Failed to create the model: %v", err)
    }

    rootAgent, err := llmagent.New(llmagent.Config{
        Name:        "demo_agent",
        Model:       model,
        Instruction: "You can leverage registered tools and sub-agents.",
        Toolsets:    []tool.Toolset{myMCPToolset},
        SubAgents:   []agent.Agent{myRemoteAgent},
    })
    if err != nil {
        log.Fatalf("Failed to create the agent: %v", err)
    }

    config := &launcher.Config{AgentLoader: agent.NewSingleLoader(rootAgent)}
    l := full.NewLauncher()
    if err := l.Execute(ctx, config, os.Args[1:]); err != nil {
        log.Fatalf("Run failed: %v\n\n%s", err, l.CommandLineSyntax())
    }
}

针对 Google MCP 服务器以及远程 A2A 代理的认证机制

远程 A2A 代理(Remote A2A Agents)

对远程 A2A 代理的调用不会为您进行身份验证。如果您正在连接到 Google A2A 代理,请在创建该远程代理时提供一个已通过身份验证的 HTTP 客户端。

传递一个…… httpx.AsyncClient 已配置 Google 认证头部(authentication headers),以便与……进行交互。 get_remote_a2a_agent method.

import httpx
import google.auth
from google.auth.transport.requests import Request

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

httpx_client = httpx.AsyncClient(auth=GoogleAuth(), timeout=httpx.Timeout(60.0))
remote_agent = registry.get_remote_a2a_agent(
    f"projects/{project_id}/locations/{location}/agents/YOUR_AGENT_ID",
    httpx_client=httpx_client,
)

传递一个已通过身份验证的用户信息。 *http.Client 使用(with) WithA2AHTTPClient或者使用静态(static)的头部信息(headers) WithA2AHeaders.

import (
    "golang.org/x/oauth2/google"

    "google.golang.org/adk/v2/agentregistry"
)

httpClient, err := google.DefaultClient(ctx, "https://www.googleapis.com/auth/cloud-platform")
if err != nil {
    log.Fatalf("Failed to load Application Default Credentials: %v", err)
}

remoteAgent, err := registry.RemoteAgent(ctx, agentName,
    agentregistry.WithA2AHTTPClient(httpClient),
)

为客户端设置任何超时时间(timeout)。 Transport 而不是与……一起使用 http.Client.Timeout该规则适用于整个请求过程,并会截断流式响应(即那些以连续数据流形式发送的响应)。

Google MCP 服务器

对于 Google MCP 服务器而言,身份验证相关的头部信息会自动被传递。

如果自动身份验证没有按预期工作,您可以手动提供相关头部信息(headers)。 header_provider “argument in the”中的“argument”指的是“论点”或“参数”;“in the”则表示这个论点或参数存在于某个特定的上下文或结构中。因此,整个短语可以理解为“某个特定上下文或结构中的论点/参数”。 AgentRegistry constructor.

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

def google_auth_header_provider(context):
    creds, _ = google.auth.default()
    if not creds.valid:
        creds.refresh(Request())
    return {"Authorization": f"Bearer {creds.token}"}

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

对……的请求 *.googleapis.com 该端点会使用注册表客户端(registry client)自身的凭据(credentials)进行身份验证。对于其他端点,或者想要覆盖这一默认设置,需要手动传递相应的凭据。 WithMCPHTTPClient 和 WithMCPHeaders.

toolset, err := registry.MCPToolset(ctx, mcpServerName,
    agentregistry.WithMCPHTTPClient(httpClient),
    agentregistry.WithMCPHeaders(map[string]string{"X-Tenant-Id": "acme"}),
)

以这种方式设置的头部信息会应用于工具集发送给 MCP 服务器的每一个请求;这些头部信息不会影响对 Agent Registry API 本身的调用。

API 参考手册

`AgentRegistry` 类提供了以下核心方法:

  • list_mcp_servers(self, filter_str, page_size, page_token):获取已注册的 MCP 服务器列表。
  • get_mcp_server(self, name):检索特定 MCP 服务器的详细元数据。
  • get_mcp_toolset(self, mcp_server_name):从已注册的 MCP 服务器中构建一个 ADK McpToolset 实例。
  • list_agents(self, filter_str, page_size, page_token):获取已注册的 A2A 代理列表。
  • get_agent_info(self, name):检索特定 A2A 代理的详细元数据。
  • get_remote_a2a_agent(self, agent_name)为已注册的 A2A Agent 创建一个 ADK RemoteA2aAgent 实例。

The agentregistry.Client 每个资源类型(type)都提供了三种用于发现(discovery)该资源的方法。 kind: List* 返回一个页面(即只显示一个页面的内容)。 Get* 根据资源的完整名称返回该资源; All* 返回一个 iter.Seq2 该功能可以根据用户的需求动态地获取页面内容(即“按需获取页面”)。

  • ListAgents(ctx, opts ...ListOption), GetAgent(ctx, name), AllAgents(ctx, opts ...ListOption)已注册的 A2A 代理(registered A2A agents)。
  • ListMCPServers(ctx, opts ...ListOption), GetMCPServer(ctx, name), AllMCPServers(ctx, opts ...ListOption)已注册的 MCP 服务器。
  • ListEndpoints(ctx, opts ...ListOption), GetEndpoint(ctx, name), AllEndpoints(ctx, opts ...ListOption)已注册的模型端点(registered model endpoints)。
  • RemoteAgent(ctx, name, opts ...RemoteAgentOption):将已注册的 A2A 代理转换为相应的实体(或资源)。 agent.Agent 可用作子代理(sub-agent)。
  • MCPToolset(ctx, name, opts ...MCPToolsetOption):将已注册的 MCP 服务器解析为 tool.Toolset.

列表选项包括: WithFilter, WithPageSize,以及 WithPageToken. The All* 迭代器会自行管理页面令牌(page token)。如果从代理注册表(Agent Registry)API 返回的响应状态码不是 2xx,系统会相应地处理该情况。 *agentregistry.APIError 携带…… StatusCode 以及响应结果 Body.

配置选项

`AgentRegistry` 的构造函数接受以下参数:

  • project_id (str,必填):Google Cloud 项目的 ID。
  • location (str,必填):Google Cloud 的位置/区域,例如 “global” 或 “us-central1”。
  • header_provider (可选参数):一个可调用对象(callable),该对象接收一个 `ReadOnlyContext` 对象作为参数,并返回一个字典,其中包含需要添加到请求中的自定义头部信息(custom headers)。 McpToolset 那个;那种 get_mcp_toolset 数据会被返回到目标 MCP 服务器。这些头部信息(headers)不会影响对 Agent Registry API 的调用本身,也不会影响其他请求的发送。 RemoteA2aAgent对于这些请求,请传递经过身份验证的数据(即已通过认证的用户信息)。 httpx.AsyncClient 给……;发送到…… get_remote_a2a_agent如所示, 远程 A2A 代理(Remote A2A Agents).

The agentregistry.New 构造函数接受一个参数。 Config ```c struct { // 成员变量 }; ```

  • ProjectID (字符串,必填):Google Cloud 项目的 ID。
  • Location (字符串,必填):Google Cloud 的位置/区域,例如 “global” 或 “us-central1”。
  • HTTPClient (*http.Client(可选):用于与 Agent Registry 进行 API 调用的客户端。当该参数值为 `nil` 时,ADK 会使用应用程序的默认配置来创建相应的客户端,并根据这些配置(包括 TLS 相关的认证信息)来解析 API 的端点地址。 GOOGLE_API_USE_MTLS_ENDPOINT 和 GOOGLE_API_USE_CLIENT_CERTIFICATE这个客户端也被重新用于其他用途。 McpToolset (网站的)流量流向 *.googleapis.com 这些端点(endpoints)……但从来都不是为了(but never for……) A2A traffic.

相反,每次调用时都会重新配置通往已解析端点的出站连接(即数据传输路径)。 WithA2AHTTPClient 和 WithA2AHeaders 在……的时候;当……发生时 RemoteAgent, WithMCPHTTPClient 和 WithMCPHeaders 在……的时候;当……发生时 MCPToolset.

其他资源