如何在 AWS 上透過 A2A 構建可組合、互通的多智能體系統
Build composable, interoperable multi-agent systems with A2A on AWS
AWS 文章示範如何透過 A2A 連接兩個 AWS 帳戶中的 LangChain 企業協調器與 Strands Agents SaaS 智能體,實現跨框架、跨組織的雙向協作。方案採用雙向 OAuth 驗證,兩邊不必使用對方的框架或 SDK,亦不共享密鑰。文章提供三個 Jupyter notebooks 的部署流程,並執行端到端測試及七項信任邊界檢查;合規掃描示範使用合成資料。
文章把 Agent Card 發現、跨組織雙向 OAuth 和回呼協作放進同一部署範例,並提供可按步驟執行的三個 Jupyter notebooks。
跨越組織界線的多代理系統,當中的代理往往需要以可組合、互通的方式,與其他組織建立及運行的代理協作。它們需要一種方法互相發現、溝通及交換任務,同時不暴露內部細節,也不要求雙方使用相同框架。
Agent-to-Agent (A2A) 協定正是為了解決這項限制。沒有 A2A 的話,要跨越組織界線建立可組合的多代理系統,就需要為每位客戶及每種框架編寫自訂整合程式碼。獨立軟件供應商(ISV)則可建立可組合、互通的代理,讓它們與客戶現正使用的 A2A 相容框架協作。
本文以 ISV 用例為主,但這種模式同樣適用於需要跨越界線提供代理服務的組織,無論對象是合作夥伴、客戶,還是使用不同框架的內部團隊。隨着系統擴展,只需向編排器註冊 Agent Cards,便可新增技能,無須更改已在運行的代理。
本文會介紹一個已部署在 AWS 上的參考架構。以 LangChain 為基礎的企業編排器,透過 A2A 與以 Strands Agents 為基礎的軟件即服務(SaaS)代理跨組織界線通訊;企業與 SaaS 供應商分別使用獨立的 AWS 帳戶。雙方都不依賴對方的框架或 SDK,也不會共用任何密鑰。我們會介紹架構及實作模式,然後透過三個 Jupyter notebooks 部署系統並執行端到端測試。
A2A 協定現已成為 Linux Foundation 專案,AWS 也是支持它的組織之一。透過 A2A,代理可以互相發現、協商任務,並透過標準化協定跨越組織界線協作。協定採用 OAuth 2.0 和 OpenID Connect (OIDC) 等現有身份驗證標準來保障跨界安全,並旨在支援各種 A2A 相容框架。
在 Open Protocols for Agent Interoperability Part 4: Inter-Agent Communication on A2A 一文中,我們介紹了 A2A 概念,並示範兩個 Strands 代理如何在 AWS 上使用該協定通訊。該文奠定了基礎,介紹 Agent Card 探索、結構化任務執行,以及 A2A 伺服器模式。本文會在此基礎上,進一步探討跨框架互通、跨組織信任界線,以及雙向 OAuth。
方案概覽
三個代理在兩個 AWS 帳戶中運行,一個屬於企業,另一個屬於 SaaS 供應商。A2A 協定連接這些代理,並在兩個方向都使用 OAuth 身份驗證。每個帳戶都有自己的 Amazon Cognito 用戶集區,因此雙方各自透過自己的身份提供者進行身份驗證。
圖 1:企業帳戶與 SaaS 供應商帳戶中的 A2A 代理
在註冊期間,企業與 SaaS 供應商只會交換公開資料,例如身份提供者 URL、client ID、scope 及端點 URL。之後,雙方各自信任來自對方用戶集區的 token,而且不會共用任何密鑰。
完成註冊後,每個請求都會按以下步驟進行:
- 企業應用程式從企業的 Amazon Cognito 用戶集區取得 access token。
- 應用程式透過 HTTPS 將問題傳送至 Amazon API Gateway 中的 user API,然後輪詢以取得答案。
- Amazon API Gateway 會透過 VPC link 及內部 Network Load Balancer,以私有方式將請求轉送至 Enterprise Orchestrator(一個 LangChain 代理)。
- 當模型判定問題需要進行合規掃描時,編排器會使用儲存在 AWS Secrets Manager 的 client secret,從企業用戶集區取得自己的 token。
- 編排器會向運行於 Amazon Bedrock AgentCore 執行環境上的 Compliance SaaS Agent 傳送 A2A 請求,並使用啟動時從該代理的 Agent Card 讀取的技能。
- Compliance SaaS Agent 會透過註冊時登記的 callback URL 檢查 Enterprise Context Agent 的 Agent Card,然後從 SaaS 供應商自己的用戶集區取得 token。
- Compliance SaaS Agent 會回呼 Enterprise Context Agent 以取得帳戶中繼資料,完成掃描,再將答案傳回編排器,最後送到應用程式。
在企業一方,兩個代理使用 Amazon Elastic Container Service(Amazon ECS)和 AWS Fargate 運行。Enterprise Orchestrator 是用戶使用系統的入口。LangChain 提供代理框架及工具呼叫抽象,而 Amazon Bedrock 則提供支援各代理推理的基礎模型(FMs)。編排器使用 LangChain 和 Amazon Bedrock(Anthropic Claude Sonnet 4.6)。啟動時,編排器會從 well-known URL 取得 SaaS 代理的 Agent Card,並為卡上描述的每項技能建立一個 LangChain 工具。模型會根據用戶問題決定要呼叫哪個工具,因此編排器無須硬編碼路由邏輯。它會透過 A2A 和 OAuth bearer tokens 傳送合規掃描請求,並為管理層摘要結果。用戶透過 Amazon API Gateway 的 HTTPS 端點連接編排器;該端點只接受來自企業自身用戶集區的 token。
第二個企業代理負責提供內部情境資料。Enterprise Context Agent 使用 LangChain 和 Amazon Bedrock(Amazon Nova Lite)建構,提供內部帳戶中繼資料,例如內部政策規則、資料分類、業務重要程度,以及升級聯絡人(團隊當值輪值表)。已部署的代理使用官方 a2a-sdk(AgentCard、AgentExecutor 及符合規格的 JSON-RPC routes),並固定使用 a2a-sdk[http-server]==1.2.2。SaaS 代理透過 API Gateway partner API 連接情境代理;該 API 只接受 SaaS 供應商的 callback token。
兩個企業代理都在 Amazon Virtual Private Cloud(Amazon VPC)的私有子網中運行,沒有公開 IP 地址。
在 SaaS 供應商一方,Compliance SaaS Agent 在供應商自己的 AWS 帳戶內,於 Amazon Bedrock AgentCore 上運行。代理以 Strands Agents SDK 建構,會按照企業自己的內部政策檢查 AWS 帳戶,例如生產環境不得使用公開儲存空間,以及機密資料必須進行靜態加密。在正式環境中,掃描工具會連接 AWS Config、AWS Security Hub 或 Amazon GuardDuty 等服務。這個示範中的代理則使用合成資料,模擬多個帳戶的合規檢查結果。
掃描前,SaaS 代理會回呼 Enterprise Context Agent,以取得企業情境資料,例如哪些帳戶屬於生產環境、適用哪些內部政策,以及應向誰升級處理。這種雙向模式令代理成為真正的對等方,而非單純的客戶端與伺服器。回呼只會連接客戶在註冊時登記的地址。
關鍵的設計決定是,所有跨界通訊都使用 A2A。企業無法存取 SaaS 代理的內部工具、系統提示詞或模型選擇。只要 Agent Card 和 A2A 介面保持相容,ISV 就可以更改內部架構,而無須改動客戶整合。SaaS Agent Card 只公布一項精選技能,不會公布內部工具名稱。
Amazon Bedrock 提供多個基礎模型的 API 存取,因此每個代理程式都可使用最適合其工作負載的模型。在此方案中,協調器和 SaaS 代理程式使用 Anthropic Claude Sonnet 4.6 處理複雜推理,而上下文代理程式使用 Amazon Nova Lite 查詢中繼資料。你可按自己的需求選擇不同模型。
A2A 和 Model Context Protocol (MCP) 在此架構中解決不同問題。MCP 以用戶端-伺服器模型連接代理程式與其自身的工具和資料來源。A2A 將代理程式以對等方式連接至其他代理程式,雙方都不會公開其內部實作。在正式環境中,SaaS 代理程式可在內部使用 MCP 連接其合規掃描工具,同時透過 A2A 對外提供服務。無論代理程式如何連接其內部工具,對外介面都保持不變。
先決條件
筆記本包含完整的部署程序。執行前,你需要準備以下項目:
- 兩個 AWS 帳戶,一個供企業使用,一個供 SaaS 供應商使用,並且位於同一個 AWS 區域:us-east-1、us-east-2 或 us-west-2。在兩個帳戶中均須能存取 Amazon Bedrock 上的 Anthropic Claude Sonnet 4.6;企業帳戶則須能存取 Amazon Nova Lite。首次執行前,請在每個帳戶提交 Anthropic 首次使用表格,並為你用來執行筆記本的身分授予 Amazon Bedrock 模型存取文件中列出的 AWS Marketplace 權限。模型的可用性因區域而異。請查看 Amazon Bedrock 模型可用性文件,以取得目前清單。
- 具備 Python 3.10 或更新版本的 Jupyter 環境,可選擇以下其中一種方式:
- 在你的電腦上:JupyterLab、AWS Command Line Interface (AWS CLI) version 2,以及每個帳戶各一個 AWS IAM Identity Center 設定檔,並使用 aws configure sso 完成設定。你不需要 Docker:AWS CodeBuild 會建置容器映像。
- 或者在每個帳戶中使用一個 Amazon SageMaker AI 筆記本執行個體(ml.t3.medium 已足夠)。請參閱 Amazon SageMaker AI 入門指南。
- 每個帳戶都須有一個具備權限的 AWS Identity and Access Management (IAM) 角色,可用來建立 AWS CloudFormation 堆疊及其中的資源。每個筆記本的 Reference 部分都列出確切權限。請參閱 IAM User Guide。
筆記本 3 亦會執行本文稍後所述的端對端測試,讓你驗證部署。
執行此方案會產生其所建立資源的費用。在企業帳戶中,主要的常駐資源包括 NAT gateway、兩個 AWS Fargate 任務、內部 Network Load Balancer,以及兩個介面 VPC 端點。Amazon Bedrock 和 Amazon Bedrock AgentCore 按用量收費。價格因 AWS 區域而異。請參閱 Amazon VPC、AWS Fargate、Amazon Bedrock、Amazon Bedrock AgentCore 和 Elastic Load Balancing 的定價頁面。完成後請執行 Clean up 部分。
實作方案
使用三個筆記本部署系統,依序以 Jupyter 執行,每次執行一個儲存格。筆記本 1(企業帳戶,約 3 分鐘)會建立企業身分並寫入一項註冊請求。筆記本 2(SaaS 供應商帳戶,約 5 分鐘)會部署合規代理程式並寫入一項註冊回應。筆記本 3(企業帳戶,約 20 分鐘)會部署企業代理程式並執行測試。註冊檔案只包含公開值。
- 複製 GitHub 存放庫,並為本機執行設定兩個 AWS 設定檔;或者在每個帳戶各使用一個已複製該存放庫的筆記本執行個體。
- 在企業帳戶中執行筆記本 1。
- 將
onboarding-request.json提供給 SaaS 供應商。 - 在 SaaS 供應商帳戶中執行筆記本 2。
- 將
onboarding-response.json交回企業。 - 在企業帳戶中執行筆記本 3。
- 測試後,先執行筆記本 3 的 Clean up,再執行筆記本 2 的 Clean up。
以下各節會說明部署背後的主要實作模式。它們合起來展示三項能力:
- 跨框架互通性 – LangChain 協調器透過 A2A 呼叫 Strands 代理程式,雙方均不依賴對方的 SDK。
- 跨組織邊界的組合能力 – ISV 的合規代理程式與企業的上下文代理程式組成一個雙方團隊都未曾獨自建置的工作流程。
- 透過 OAuth 的雙向協作 – 代理程式以對等身分運作,透過權杖式驗證跨越信任邊界互相呼叫。
在此情境中,ISV 透過 A2A 以單一基於協定的介面取代多條自訂整合路徑。
建立 SaaS 合規代理
使用 Strands Agents SDK 建立 ISV 的合規代理,並部署至 Amazon Bedrock AgentCore。此示範中的掃描工具會回傳模擬的合規調查結果。
代理使用 Strands @tool 裝飾器提供三種合規工具(列出可用帳戶、執行合規掃描,以及取得修正步驟),另有第四種工具會回呼企業,詳情見下一節。Agent Card 不會列出這些工具,而是發布一項精選 skill,讓調用方的模型看到產品能做甚麼,而非產品如何建構。以下簡化範例展示掃描工具:
from strands import Agent, ToolContext, tool
from strands.models.bedrock import BedrockModel
from strands.multiagent.a2a import A2AServer
@tool
def run_compliance_scan(account_id: str) -> dict:
"""Run a compliance scan on a specific AWS account.
Args:
account_id: The AWS account ID to scan (e.g., acc-12345)
"""
if account_id not in ACCOUNTS:
return {"error": f"Account {account_id} not found."}
findings = COMPLIANCE_FINDINGS.get(account_id, [])
non_compliant = [f for f in findings if f["status"] == "NON_COMPLIANT"]
return {
"account_id": account_id,
"account_name": ACCOUNTS[account_id]["name"],
"scan_summary": {
"total_rules_checked": len(findings),
"compliant": len(findings) - len(non_compliant),
"non_compliant": len(non_compliant),
"critical_findings": len([f for f in non_compliant if f["severity"] == "CRITICAL"]),
"high_findings": len([f for f in non_compliant if f["severity"] == "HIGH"]),
},
"findings": findings,
}啟用雙向回呼
這正是此方案超越一般代理整合之處。大部分代理對代理示範都只展示單向請求和回應:客戶端代理呼叫伺服器代理,然後等待結果。如果被呼叫的代理需要只有呼叫方才掌握的資料,這種模式便行不通。在正式環境中,代理需要成為能互相呼叫的對等方。
SaaS 合規代理需要企業環境資訊,例如哪些帳戶屬於正式環境、適用哪些內部政策,以及應向誰升級處理。這些資料只有企業掌握。
SaaS 代理會透過 A2A 回呼,但只會呼叫客戶在接入期間登記的 callback URL。它會先在該處驗證客戶的公開 context card,然後從 SaaS 供應商自己的 Cognito pool 取得 token,再向企業合作夥伴 API 傳送 message/send:
def _call_enterprise_context(message_text: str, inbound_task_id: str = "-") -> str:
if not CALLBACK_URL_VALID: # checked once at import
raise CallbackUnavailable("CALLBACK_URL is not a registered callback URL")
cfg = _load_callback_config() # this SaaS provider's own client, from Secrets Manager
_verify_context_card(cfg) # anonymous GET of the card at CALLBACK_URL, no redirects
rpc_id = f"req-{uuid4().hex}"
payload = {
"jsonrpc": "2.0",
"id": rpc_id,
"method": "message/send",
"params": {
"message": {
"role": "user",
"parts": [{"kind": "text", "text": message_text}],
"messageId": uuid4().hex,
}
},
}
for attempt in (1, 2):
token = _fetch_token(cfg, force=attempt > 1) # from the SaaS provider's own Cognito pool
try:
resp = _post_callback(CALLBACK_URL, payload, token)
...任何失敗,從未能驗證的 card 到遭拒的 token,都只會向模型傳回一則訊息:「Enterprise context unavailable」,詳細資料則保留在 SaaS 供應商的日誌中。
在 AgentCore 上透過 A2A 對外提供代理
Strands SDK 的 A2AServer class 負責處理 A2A 協定、產生 Agent Card,以及處理 JSON-RPC 訊息。伺服器會發布一項精選 skill,並在卡片中說明呼叫方如何取得 token:
a2a_server = SecuredA2AServer( # A2AServer plus the card's securitySchemes
agent_factory=create_compliance_agent,
http_url=AGENT_URL,
serve_at_root=True,
skills=[COMPLIANCE_SCAN_SKILL], # one curated skill, not the internal tools
enable_a2a_compliant_streaming=True,
)部署至 AgentCore 後,系統會自動在 /.well-known/agent-card.json 產生 Agent Card。Agent Card 是一份 JSON 文件,描述代理的名稱、功能和 skills。A2A 相容客戶端可以取得此卡片,無須文件或 SDK 整合便能了解代理的功能。
使用 LangChain 建立企業協調器
這是互通性的實證。企業協調器使用 LangChain,刻意與以 Strands 為基礎的 SaaS 代理採用不同技術。它透過原始 httpx HTTP 呼叫使用 A2A JSON-RPC,並不依賴 Strands SDK。即使 ISV 從 Strands 改用另一個 A2A 相容框架,只要 SaaS 代理仍使用 A2A 通訊並發布相容的 Agent Card,企業協調器便無須修改也能繼續運作。這就是協定層互通性的實際意義。
協調器會從企業自己的 Cognito pool 取得 token,並只透過 HTTPS,將 JSON-RPC payload 傳送至已固定為取得 Agent Card 時所用位址的代理 URL。以下精簡程式碼展示 A2A 客戶端的核心部分:
from langchain_aws import ChatBedrock
from langchain_core.tools import tool as langchain_tool
from langchain.agents import create_agent
llm = ChatBedrock(
model_id="us.anthropic.claude-sonnet-4-6",
region_name=AWS_REGION,
max_tokens=4096,
config=BEDROCK_CLIENT_CONFIG, # timeouts and standard retries
guardrails=GUARDRAIL_CONFIG, # this account's guardrail on every model call
)
def send_a2a_message(agent_url: str, message_text: str) -> str:
# agent_url is the pinned agent URL from discovery: the address the Agent Card
# was fetched from, never a value from a caller or a message.
rpc_id = f"lc-{uuid4().hex}"
payload = {
"jsonrpc": "2.0",
"id": rpc_id,
"method": "message/send",
"params": {
"message": {
"role": "user",
"parts": [{"kind": "text", "text": message_text}],
"messageId": uuid4().hex,
}
},
}
def _post(token: str, attempt: int) -> httpx.Response:
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {token}"}
with httpx.Client(timeout=_A2A_TIMEOUT) as client: # Timeout(300.0, connect=5.0); httpx doesn't follow redirects by default
resp = client.post(agent_url, json=payload, headers=headers)
resp.raise_for_status()
return resp
# get_bearer_token() raises when there is no valid client config and never returns
# an empty token, so no request goes out without one (fail closed).
token = get_bearer_token()
try:
resp = _post(token, 1)
except httpx.HTTPStatusError as e:
# On a 401, force one token refresh and retry once.
if e.response.status_code == 401:
resp = _post(_fetch_token(force=True), 2)
else:
raise
...探索代理並以 LLM 路由請求
協調器啟動時,會從已設定的 ISV URL 取得 Agent Cards。它會讀取每張卡片上的 skill 描述,並為每項 skill 建立一個 LangChain 工具。接着,協調器的大型語言模型 (LLM) Anthropic Claude Sonnet 4.6 會根據使用者的問題,決定要呼叫哪項工具。以下簡化程式碼展示此模式:
def _tool_name_part(text: str) -> str:
"""Reduce card text to the characters Bedrock allows in a tool name (letters, digits, _)."""
return re.sub(r"[^A-Za-z0-9_]+", "_", str(text)).strip("_") or "agent"
def build_langchain_tools(agents: list[dict]) -> list:
"""Create a LangChain tool for each skill in each discovered agent."""
tools = []
for agent in agents:
agent_url = agent["url"]
agent_name = _tool_name_part(agent["name"])
for skill in agent["skills"]:
skill_name = _tool_name_part(skill["name"])
skill_description = skill.get("description", "")
examples = skill.get("examples", [])
# Build a descriptive tool name and description
tool_name = f"{agent_name}__{skill_name}"[:64]
tool_description = (
f"{skill_description} "
f"(External agent: {agent['name']})"
)
if examples:
tool_description += f" Examples: {'; '.join(examples[:3])}"
# Create a closure to capture agent_url for this specific tool
def make_tool(name: str, desc: str, url: str):
def call_external_agent(question: str) -> str:
"""Send a natural language question to an external agent via A2A protocol."""
return send_a2a_message(url, question)
call_external_agent.__name__ = name
call_external_agent.__doc__ = desc
return langchain_tool(call_external_agent)
tools.append(make_tool(tool_name, tool_description, agent_url))
# (A catch-all tool for an agent whose card lists no skills is omitted here.)
return tools
agent_tools = build_langchain_tools(discovered_agents) # from the Agent Cards fetched at startup
agent_executor = create_agent(llm, agent_tools, system_prompt=SYSTEM_PROMPT)因此,ISV 新增或更改功能時,其 Agent Card 也會隨之更新;協調器下次重新啟動時便會取得新 skills。兩個團隊毋須為這項變更協調合作。
建立企業環境資訊代理
企業環境資訊代理使用 LangChain 和 Amazon Nova Lite 查詢企業 metadata,並透過官方 a2a-sdk 使用 A2A 提供其功能。SDK 負責提供 Agent Card、路由 JSON-RPC,以及確保符合協定要求。由於 A2A 是透過 HTTP 傳輸的 JSON-RPC,標準網絡框架便可用來提供服務。協調器展示了客戶端一側:它使用純 httpx 傳送 A2A 請求,並不使用 A2A SDK。
代理也會在 /.well-known/agent-card.json 發布自己的 Agent Card,SaaS 代理會在回呼前先檢查此卡片。這與另一方向使用的是同一種探索機制。A2A 規格定義了 Agent Cards,因此它們不依賴建立代理所用的框架。
設定跨組織邊界的 OAuth
大部分企業都不接受跨組織邊界、未經驗證的代理對代理通訊。此方案中的每項 A2A 任務請求 (message/send) 都會附帶 JSON Web Token (JWT)。雙方各自使用來自其身分提供者的 token 進行驗證;接收方只接受指定的提供者、單一客戶端及單一 scope。唯一無須驗證的端點是企業環境資訊代理的 Agent Card;該卡片會發布描述性 metadata,供呼叫方探索代理。
此方案使用 Amazon Cognito 作為 OAuth 提供者。更新範例中專屬於 Cognito 的檢查後,同一模式亦可使用另一個會簽發已簽署 JWT 存取 token 的 OpenID Connect (OIDC) 身分提供者。
驗證流程涉及四個組成部分:
Amazon Cognito:每個帳戶各設一個 user pool。企業 pool 會向協調器及企業應用程式簽發 token;SaaS pool 則會向 SaaS 代理簽發回呼所需的 token。你可以在 Amazon Cognito 主控台查看這些 pool。
Amazon Bedrock AgentCore 設定了企業集區的 discovery URL、協調器的 client ID,以及一個 scope。它會驗證每個傳入的 A2A 請求所帶的 JWT:
{"customJWTAuthorizer": {
"discoveryUrl": "https://cognito-idp.us-east-1.amazonaws.com/<enterprise pool ID>/.well-known/openid-configuration",
"allowedClients": ["<a2a-enterprise-orchestrator-saas client ID>"],
"allowedScopes": ["a2a-enterprise-compliance-saas/invoke"]
}}Amazon API Gateway 使用 JWT 授權器。合作夥伴 API 只接受 SaaS 供應商的回呼 token,而用戶 API 只接受企業應用程式的 token。請在 Amazon API Gateway console 查看設定。
每個帳戶中的 AWS Secrets Manager 都會儲存該帳戶的 client secret,而 IAM 授權及一項拒絕所有其他主體的資源政策,會限制每個密鑰只供一個工作負載使用。密鑰不會硬編碼,也不會與另一個帳戶共用。你可以在 AWS Secrets Manager console 管理密鑰。
以下 AWS CloudFormation 片段展示合作夥伴 API 的 JWT 授權器:
# Trusts only the SaaS provider's pool, its callback client, and its callback scope.
ContextApiAuthorizer:
Type: AWS::ApiGatewayV2::Authorizer
Properties:
ApiId: !ImportValue
Fn::Sub: '${IdentityStackName}-PartnerApiId'
AuthorizerType: JWT
Name: saas-jwt
IdentitySource:
- '$request.header.Authorization'
JwtConfiguration:
Audience: [!Ref SaasCallbackClientId]
Issuer: !Ref SaasIssuer
ContextApiRoute:
Type: AWS::ApiGatewayV2::Route
Properties:
RouteKey: 'POST /'
AuthorizationType: JWT
AuthorizerId: !Ref ContextApiAuthorizer
AuthorizationScopes: [!Ref SaasCallbackScope]
# ApiId and Target omitted在 API Gateway 與 AgentCore 之間設定 OAuth 時,機器對機器驗證有一個細節經常引發錯誤。Amazon Cognito 的 client-credentials access token 會帶有 client_id 和 scope,但不會帶有 aud claim。若缺少 aud,API Gateway JWT 授權器會用 client_id 比對 audience 清單。在 AgentCore 一側,請設定 allowedClients,並讓 allowedAudience 保持未設定。
使用 notebook 部署系統
這些 notebook 會透過 Jupyter 執行整個部署流程。它們會部署五個 AWS CloudFormation stacks:企業帳戶中有三個,SaaS 供應商帳戶中有兩個。企業基礎設施與服務 stacks 分開部署,是因為有先有雞還是先有蛋的問題:ECS 服務需要 Docker 映像,但 CloudFormation 會建立存放這些映像的 Amazon Elastic Container Registry (Amazon ECR) repositories。你可以在 AWS CloudFormation console 監察各個 stack。
這些 notebook 會及早顯示故障。在部署任何內容之前,每個 notebook 都會先透過簡短的測試呼叫檢查 Amazon Bedrock 模型存取權,而每個步驟遇到第一個錯誤時都會停止,並清楚顯示輸出。notebook 2 和 3 底部的「清理」部分位於停止用的 cell 之後,因此 Run All 不會執行到這些部分。
了解 Agent Cards 與探索機制
Agent Cards 讓系統無須預先就工具定義達成共識,也能進行探索。若沒有 Agent Cards,企業便需要文件、SDK,或與 ISV 的工程團隊開會,才能了解合規代理能做甚麼。有了 Agent Cards,企業協調器只需擷取一份 JSON 文件,便能在執行時以程式方式即時得知代理的名稱、能力和技能。以下是合規代理為一位客戶發布的卡片節錄:
{
"name": "Compliance SaaS Agent",
"description": "Scans AWS accounts for compliance with your organization's policies and returns findings by severity with remediation steps.",
"url": "https://bedrock-agentcore.us-east-1.amazonaws.com/runtimes/.../invocations/",
"protocolVersion": "0.3.0",
"capabilities": { "streaming": true },
"skills": [
{
"id": "compliance-scan",
"name": "Compliance scan",
"description": "Scans your AWS accounts against your organization's policies and returns findings by severity, remediation steps with estimated effort, and your escalation contacts when available."
}
],
"securitySchemes": {
"cognito": {
"type": "oauth2",
"description": "OAuth 2.0 client credentials from the customer's identity provider, registered at onboarding.",
"flows": { "clientCredentials": {
"tokenUrl": "https://a2a-enterprise-<account-id>.auth.us-east-1.amazoncognito.com/oauth2/token",
"scopes": { "a2a-enterprise-compliance-saas/invoke": "Invoke the compliance agent" }
} }
}
},
"security": [ { "cognito": ["a2a-enterprise-compliance-saas/invoke"] } ]
}每項技能的描述都會成為工具的 docstring,讓協調器的模型將每個請求路由至合適的代理。兩個團隊從未需要就工具定義達成共識,也無須共用 SDK。卡片亦會聲明呼叫方如何進行驗證。協調器會檢查該聲明,而不會盲目跟從:只有卡片列出入職時登記的 token endpoint 和 scope,才會保留該卡片。
端對端測試
Notebook 3 會透過兩個帳戶執行一項端對端測試。它會取得企業應用程式的 token、提交問題,並輪詢結果:
# A token for the enterprise's own user client. The secret is read from this account's
# Cognito pool in memory and discarded; it is never printed or typed.
secret = cognito.describe_user_pool_client(
UserPoolId=ENT_POOL_ID, ClientId=ORCH_USER_CLIENT_ID)["UserPoolClient"]["ClientSecret"]
r = requests.post(TOKEN_ENDPOINT, auth=(ORCH_USER_CLIENT_ID, secret), allow_redirects=False, timeout=15,
data={"grant_type": "client_credentials", "scope": "a2a-enterprise-orchestrator/ask"})
del secret
auth = {"Authorization": f"Bearer {r.json()['access_token']}"}
# Submit (HTTP 202 and a job ID), then poll every 5 seconds
r = requests.post(f"{ORCH_API_URL}/jobs", headers=auth, allow_redirects=False, timeout=30,
json={"question": "Scan our production accounts for compliance with our internal "
"policies, and include escalation contacts "
"for critical findings."})
job_id = r.json()["job_id"]
while (job := requests.get(f"{ORCH_API_URL}/jobs/{job_id}", headers=auth,
allow_redirects=False, timeout=30).json())["status"] not in ("succeeded", "failed"):
time.sleep(5)
del auth
print(job["response"])協調器會透過 Agent Card 探索 SaaS 代理,並透過 A2A 將請求路由過去。SaaS 代理會回呼企業情境代理以取得帳戶中繼資料(雙向 A2A),使用內部工具執行合規掃描,整合所有資料成為一份內容更豐富的報告,再將報告傳回。回應包含來自兩個代理的資料。這展示了兩個各自獨立建構、採用不同框架和不同基礎設施的代理,可以組合成一個工作流程,而這個流程並非任何一方單獨就能產生。
只有在回覆包含合規調查結果、列出只有企業情境代理才知道的值班輪值代碼,而且合作夥伴 API 的存取日誌顯示來自 SaaS 回呼用戶端的 200,測試才算通過。這些條件合起來證明回呼運作正常。接著,Notebook 3 會執行七項信任邊界檢查,向每個閘口傳送錯誤、缺失或偽造的 token,而每次呼叫都必須被拒絕。以下是一次測試執行的輸出節錄(ID 為佔位符):
[22:53:27] INFO Step E11 End-to-end test: submit a job and poll it (usually about 1 to 3 min; waits up to 10) ...
[22:53:27] INFO POST /jobs: HTTP 202 (apigw-requestid=<request-id>)
[22:53:27] INFO job_id=<job-id>
[22:53:27] INFO job status: running
[22:54:08] INFO job status: succeeded
------------------------------------------------------------------
[22:54:19] INFO partner API access log: 28/Oct/2026:22:53:31 +0000 POST / status=200 clientId=<callback-client-id> requestId=<request-id>
[22:54:19] INFO [ok ] Compliance findings (SaaS agent)
[22:54:19] INFO [ok ] Context-only marker (context agent, through the callback)
[22:54:19] INFO [ok ] Partner API access log: 200 for POST / from the SaaS callback client
[22:54:19] INFO PASS E11: job <job-id> has compliance findings and a context-only marker, and the partner API logged the callback
[22:54:19] INFO done in 52.5s
[22:54:51] INFO Step E12 Trust boundary checks: each token works only where it's trusted ...
[22:54:52] INFO 1 orchestrator-saas token on the partner API POST /: 401 as expected (www-authenticate='Bearer scope="a2a-saas-customer-callback/invoke" error="invalid_token" error_description="unable to find an appropriate key in the JWKS. ..."', apigw-requestid=<request-id>, x-amzn-requestid=-)
[22:54:52] INFO 2 orchestrator-user token on the partner API POST /: 401 as expected (www-authenticate='Bearer scope="a2a-saas-customer-callback/invoke" error="invalid_token" error_description="unable to find an appropriate key in the JWKS. ..."', apigw-requestid=<request-id>, x-amzn-requestid=-)
[22:54:52] INFO 3a orchestrator-user token on the SaaS runtime Agent Card: 401 as expected (www-authenticate='Bearer resource_metadata="...", scope="a2a-enterprise-compliance-saas/invoke"', apigw-requestid=-, x-amzn-requestid=<request-id>)
[22:54:53] INFO 3b orchestrator-user token on the SaaS runtime message/send: 401 as expected (www-authenticate='Bearer resource_metadata="...", scope="a2a-enterprise-compliance-saas/invoke"', apigw-requestid=-, x-amzn-requestid=<request-id>)
[22:54:53] INFO 4 no token on POST /jobs: 401 as expected (www-authenticate='Bearer', apigw-requestid=<request-id>, x-amzn-requestid=-)
[22:54:53] INFO 5 orchestrator-saas token on the user API POST /jobs: 401 as expected (www-authenticate='Bearer scope="a2a-enterprise-orchestrator/ask" error="invalid_token" error_description="the token does not have a valid audience"', apigw-requestid=<request-id>, x-amzn-requestid=-)
[22:54:53] INFO 6 forged SaaS-issuer token (invalid signature) on the partner API POST /: 401 as expected (www-authenticate='Bearer scope="a2a-saas-customer-callback/invoke" error="invalid_token" error_description="unable to find an appropriate key in the JWKS. ..."', apigw-requestid=<request-id>, x-amzn-requestid=-)
[22:54:53] INFO PASS E12: all seven trust boundary checks passed; each token works only where it's trusted
[22:54:53] INFO done in 1.4s在該次執行中,報告涵蓋兩個正式環境帳戶和六項調查結果,並列出每個帳戶的升級聯絡人。你可以使用任何 HTTP 用戶端傳送相同的請求,無須使用 A2A SDK。
正式環境注意事項
為了清楚說明,這個示範簡化了幾個範疇。用於正式環境時,請考慮以下改動:
- 每位客戶使用一個 runtime;或採用可接受多個客戶身分提供者的入口,並為每位客戶配置回呼用戶端。
- 使用以金鑰為基礎的用戶端驗證(private_key_jwt 或 mutual TLS),取代 client secret。
- 使用 AWS PrivateLink 進行私有連線,並在 VPC 內使用 TLS 進行端對端加密。
- 為 Amazon Simple Storage Service (Amazon S3)、Amazon ECR、AWS Secrets Manager、Amazon CloudWatch Logs 和 Amazon Bedrock Guardrails 使用客戶管理的 AWS Key Management Service (AWS KMS) 金鑰。
- 使用 VPC Flow Logs 和 Network Load Balancer 存取日誌。兩個 API Gateway 階段目前都已寫入存取日誌。
- 為 Cognito 用戶端憑證設定 Secrets Manager 輪換函式。
- 使用經驗證的入職入口網站或 API,取代檔案。
如果經 API Gateway 發出的呼叫間歇性回傳 HTTP 503,請檢查內部 Network Load Balancer 是否已啟用跨區域負載平衡。每個 ECS 服務只會執行一個任務,而該任務可能在任何一個 Availability Zone 啟動。
儲存庫的 README 在「Security controls」及「Considerations for production」部分列出完整清單。
安全考量
此方案只應部署在不含客戶或業務資料的沙盒帳戶中,並在測試後刪除堆疊。此範例只使用合成資料,不含個人資料。其合規代理程式會檢查範例內部政策,但不會評估或認證是否符合任何法律、法規或標準。此範例包括以下控制措施。使用此模式投入生產環境前,請自行檢視並調整這些措施:
- 傳輸加密。所有跨帳戶呼叫均透過 HTTPS 連接 Amazon API Gateway 或 Amazon Bedrock AgentCore,而除了情境代理程式的公開 Agent Card 外,所有路由都要求 Cognito JWT。
- Guardrails。此範例中的每次模型呼叫都會使用 Amazon Bedrock guardrail,並啟用提示攻擊和有害內容篩選器;模型使用來自另一個組織的文字前,也會先以相同的 guardrail 檢查。
- IAM 最小權限。每個工作負載都有自己的角色,並列明確切的 ARNs。只有協調器和合規代理程式可以讀取密鑰,而且兩者各自只能讀取自己的密鑰。
- 容器強化。ECS 容器以唯讀根檔案系統執行,並移除所有 Linux capabilities。基礎映像會以 digest 固定。
- 帳戶隔離。兩個帳戶不會共用任何密鑰、金鑰或 IAM 權限,只會交換公開值。
清理資源
為避免持續產生費用,測試完成後請刪除所有資源。逐格執行 notebook 3 底部的「Clean up」部分,然後執行 notebook 2 中的相應部分。每個部分的最後一個 cell 都會確認沒有遺留任何資源。清理後,請檢查兩個帳戶中的 AWS CloudFormation、Amazon ECR 和 Amazon Cognito 主控台,以及 SaaS 供應商帳戶中的 Amazon Bedrock AgentCore 主控台,確認沒有剩餘資源。
總結
本文展示如何在 AWS 上建立一個多代理程式系統,讓不同組織以不同框架建置的代理程式透過 A2A 協作。
在 Amazon ECS 上執行的 LangChain 協調器會與 Amazon Bedrock AgentCore 上的 Strands 代理程式通訊。雙方都不需要使用對方的框架或 SDK。SaaS 代理程式會回呼企業情境代理程式,以取得帳戶中繼資料;雙方各自使用自己的身分提供者進行驗證。同一 ISV 提供的新技能無需修改程式碼。由於協調器目前只持有一個 OAuth client,要加入第二個 ISV,只需作一項擴充:按 README 的「Considerations for production」所述,為每個 ISV 提供一個 client 和 scope。接着進行相同的接入交換、加入其 Agent Card URL,然後重新啟動協調器。
要開始使用,請複製 GitHub 儲存庫,並在兩個帳戶中執行全部三個 notebook,可使用電腦上的 Jupyter,或 Amazon SageMaker AI 筆記本執行個體。這些 notebook 會處理基礎設施佈建、代理程式部署及端對端測試。
如欲進一步了解本文提及的服務和協定,請參閱以下資源:
- Amazon Bedrock AgentCore 開發者指南
- Amazon Bedrock 使用者指南
- Strands Agents SDK 文件
- 代理程式互通性的開放協定第 4 部分:透過 A2A 進行代理程式間通訊
如有問題或意見,歡迎在留言區提出。
關於作者
Amit Chaudhary
Amit 是 Amazon Web Services 的資深解決方案架構師,負責與 ISV 及企業客戶合作,設計和建置可在生產環境運行的生成式 AI 解決方案。他專注於 AWS 上的多代理程式架構、大型語言模型及 AI 應用程式開發。
來源:AWS Machine Learning Blog · aws.amazon.com
