在线AI教程 / AI上云
[Amazon Bedrock] Automating AWS Agent Registry updates with push-based archit…
人工智能 用基于推送的架构自动更新 AWS Agent Registry 每当发布在 AWS Agent Registry(Amazon Bedrock AgentCore 的一项
人工智能
用基于推送的架构自动更新 AWS Agent Registry
每当发布在 AWS Agent Registry(Amazon Bedrock AgentCore 的一项能力)里的一个 Model Context Protocol(MCP)server 新增工具或更新 schema,registry 记录也必须跟着更新。没有自动化的基于推送的同步,消费方查到的就是过时的元数据。对跨账户管理多个 MCP servers 的组织来说,这种同步能让 catalog 记录在一套既有治理流程内保持最新。
在多数企业部署里,catalog 的价值取决于它的新鲜度。若开发者周一上线了一个新工具,而 registry 记录里还是上周的 schema,消费方就会失去对 catalog 的信任。过时的元数据直接拉低 registry 的可靠性,让团队在不知不觉中把依赖建在不准确的信息上。
当工程师给一个 MCP server 加了工具、却忘了更新 catalog 时:
消费方会完全错过这项新能力。 应用可能拿过时的 schema 去调这个工具,造成意外的运行时行为或无声的工作流偏差。
把这种缺乏自动化的情形乘上团队数量,就会侵蚀人们对 registry 的信任。组织最终退回到各种临时的发现机制:硬编码的 endpoint、非正式的经验传递,以及过时的文档。
本文里,我们勾勒一套事件驱动架构,用 AWS CloudTrail、Amazon EventBridge 和 AWS Lambda 把这些更新自动化。
架构概览
下面这套方案把这些服务组合成一条事件驱动流水线,检测运行时变更并自动把它们同步到 registry。
该架构同时支持多账户和单账户环境:
单账户配置:对简单的部署,所有组件都在 Account A 内。不需要跨账户转发,因为事件直接在 Account A 内流转。 多账户配置:涉及两个账户,来自 Account B 的运行时事件被安全地转发到 Account A。Account A(registry 账户) 持有 AWS Agent Registry、Amazon EventBridge rule、push-sync Lambda function 和 CloudTrail 日志。Account B(MCP server 账户) 承载 MCP server runtime 以及用于认证的 Amazon Cognito OAuth provider。
这个示例用两个账户,但你可以把架构扩展到多账户:以 Account A 作为 registry 账户,再用多个类似 Account B 的 AWS 账户分别放不同的 MCP servers。
下图展示 Account B 里一次 MCP server 更新的端到端事件流。捕获到的事件被转发到 Account A,那里一个 Lambda function 会向 MCP server 查询它的工具,并更新匹配的 registry 记录。

图 1:跨账户 MCP server 更新的端到端事件流,从 Account B 里的 CloudTrail 事件到 Account A 里的 registry 记录更新。
这套架构用了五个 AWS 服务:
AWS CloudTrail 把 UpdateAgentRuntime API 调用作为 management events 捕获下来。 Amazon EventBridge 把匹配的事件路由给 Lambda function,并支持跨账户转发。 AWS Lambda 向 MCP server 查询它当前的工具,与 registry 做 diff,有变化就更新记录。 AWS Agent Registry 存放 MCP server 记录及其工具 schema,作为唯一的中央事实来源。 AgentCore Identity(Amazon Bedrock AgentCore 的一项能力) 安全地代理 OAuth token 交换,因此 Lambda 无需存 secret 就能完成认证。
它如何工作:业务逻辑流
部署之后,这条流水线按下面这个端到端工作流运行:
触发(Trigger): Account B 里一位开发者更新一个 MCP server,这会调用 Amazon Bedrock AgentCore 的 UpdateAgentRuntime API,AWS CloudTrail 捕获该事件。 路由(Route): Amazon EventBridge 接住这条 CloudTrail 事件,把它转发到 Account A 的中央 event bus。 解析(Parse): Account A 里的 sync Lambda 从事件 payload 里取出 runtime Amazon Resource Name(ARN),动态拼出该 MCP server 的 invocation URL。它正是靠这个知道该去查 Account B 里的哪台 server。 认证(Authenticate): Lambda 经 AgentCore Identity 生成一个安全的 OAuth bearer token。 抓取(Fetch): Lambda 调用 MCP server(先 initialize,再 tools/list),取回最新的工具信息。 同步(Sync): Lambda 按 ARN 找到匹配的 registry 记录,评估差异,schema 有变化就更新 registry。
这条流程假定 Account A 里的 Agent Registry 已经为该 MCP server 存有一条预注册记录(在初次接入时创建)。本示例里的 Lambda function 只更新既有记录,不生成新记录。
同样的流程也适用于单账户配置——所有资源(registry、Lambda、Amazon EventBridge rule 和 MCP server)都在一个账户里。那种情况下跳过跨账户转发这一步,事件直接在同一账户的 Amazon EventBridge bus 内流转。
技术实操
本节按架构图所示、以两个账户走一遍单个 MCP server 更新的工作流。
每个发出 UpdateAgentRuntime 事件的 server 都各自独立跑一遍同样的流程。Lambda 一次处理一条事件,随 Amazon EventBridge 的调用模型自然扩缩。
第 1 步:跨账户配置下的事件捕获与路由
当开发者部署或更新一个 MCP server 时,UpdateAgentRuntime API 会被调用,可能由 AgentCore CLI(agentcore deploy)发起,也可能直接调用。
AWS CloudTrail 把它记成 Account B 里的一条 management event,投递延迟约 5–15 分钟。随后事件被送到 Account A 的默认 Amazon EventBridge bus。
对跨账户配置,Account B 的 Amazon EventBridge 通过一条跨账户 rule 把匹配的事件转发到 Account A 的 event bus。
Account A 里那条 Amazon EventBridge rule 的 target 调用 sync Lambda,把完整的 CloudTrail event JSON 作为输入 payload 传进去。
Amazon EventBridge rule pattern:
{ "source": ["aws.bedrock-agentcore"], "detail-type": ["API Call via AWS CloudTrail"], "detail": { "eventName": ["UpdateAgentRuntime"] } }
第 2 步:提取 MCP server URL
Lambda 从事件里解析出 runtime ARN。它取出承载账户的 Account ID 和 AWS Region,动态拼出目标 MCP server 经过 URL 编码的 invocation endpoint。
Extract the runtime ARN from the AWS CloudTrail event payload
def _extract_mcp_url(event): detail = event.get("detail", {}) runtime_arn = detail.get("responseElements", {}).get("agentRuntimeArn", "") if not runtime_arn: return None, None
Parse the account ID from the ARN (5th colon-separated segment)
arn_parts = runtime_arn.split(":") account_id = arn_parts[4] if len(arn_parts) > 4 else None region = detail.get("awsRegion", "us-west-2")
URL-encode the ARN and build the MCP invocation endpoint
encoded_arn = runtime_arn.replace(":", "%3A").replace("/", "%2F") mcp_url = (f"https://bedrock-agentcore.{region}.amazonaws.com" f"/runtimes/{encoded_arn}/invocations?qualifier=DEFAULT") return mcp_url, account_id
第 3 步:用 AgentCore Identity 做安全认证
Lambda 用一套两步身份流程完成认证。它先把自己的执行身份换成一个临时 workload token,再拿这个 token 经目标账户的 credential provider 换一个限定作用域的 OAuth bearer token。
def get_bearer_token(account_id=None): """Get OAuth bearer token via AgentCore Identity credential provider.
Two-step process:
- Get a workload access token from AgentCore Identity (identifies this Lambda)
- Use it to fetch an OAuth token from the credential provider (M2M flow)
The credential provider stores the Cognito/OAuth config securely in AgentCore Identity, so no client secrets are needed in Lambda env vars. """ acct = account_id or "" provider_name = os.environ.get(f"CREDENTIAL_PROVIDER_{acct}") or os.environ.get("CREDENTIAL_PROVIDER", "") scope_str = os.environ.get(f"CREDENTIAL_SCOPE_{acct}") or os.environ.get("CREDENTIAL_SCOPE", "") scopes = [s.strip() for s in scope_str.split(",") if s.strip()] if scope_str else [] workload_name = os.environ.get("WORKLOAD_IDENTITY_NAME", "") if not provider_name: raise ValueError(f"No CREDENTIAL_PROVIDER configured for account {acct}") if not workload_name: raise ValueError("WORKLOAD_IDENTITY_NAME env var not set") region = os.environ.get("AWS_REGION", "us-west-2") client = boto3.client("bedrock-agentcore", region_name=region)
Step 1: Get workload access token (identifies this Lambda as a trusted workload)
wat_response = client.get_workload_access_token( workloadName=workload_name, ) print(f"Workload access token response keys: {list(wat_response.keys())}") workload_token = wat_response.get("workloadAccessToken") or wat_response.get("accessToken", "") if not workload_token: raise ValueError(f"No access token in workload response: {list(wat_response.keys())}")
Step 2: Use workload token to get OAuth token from the credential provider
response = client.get_resource_oauth2_token( workloadIdentityToken=workload_token, resourceCredentialProviderName=provider_name, oauth2Flow="M2M", scopes=scopes, ) return response["accessToken"]
credential providers 是按账户配的(CREDENTIAL_PROVIDER_{ACCT_ID}),因此一个 Lambda 就能给跨多个账户的 MCP servers 做认证。
第 4 步:查询 MCP server
借助标准的 MCP streamable-HTTP 机制,Lambda 先用一个 initialize 请求建立活跃会话。会话就绪后,它调 tools/list 取回当前暴露的工具与 schema 的完整数组。
def call_tools_list(mcp_url, token): """Call the MCP server's initialize + tools/list methods and return the result.
MCP streamable-http requires initialize before tools/list. The session_id from initialize is passed to tools/list if the server uses sessions. """
Validate URL scheme to prevent file:// or custom scheme access
if not mcp_url.startswith("https://"): raise ValueError(f"Only HTTPS URLs are allowed, got: {mcp_url[:50]}")
Step 1: Initialize MCP session
init_payload = { "jsonrpc": "2.0", "id": "init-1", "method": "initialize", "params": { "protocolVersion": "2025-03-26", "capabilities": {}, "clientInfo": {"name": "tool-sync-lambda", "version": "1.0.0"}, }, } init_resp = requests.post( mcp_url, json=init_payload, headers=_mcp_headers(token), timeout=30, ) init_resp.raise_for_status() session_id = init_resp.headers.get("Mcp-Session-Id") init_result = _parse_sse_json(init_resp.text) print(f"MCP session initialized, session_id={session_id}")
Step 2: Call tools/list
list_payload = { "jsonrpc": "2.0", "id": "list-1", "method": "tools/list", "params": {}, } list_resp = requests.post( mcp_url, json=list_payload, headers=_mcp_headers(token, session_id), timeout=30, ) list_resp.raise_for_status() return _parse_sse_json(list_resp.text)
第 5 步:找到匹配的 registry 记录
Lambda 查询中央 Agent Registry,定位对应记录。它在 APPROVED 记录里查找 mcpServer.data 含有创建记录时嵌入的 runtime ARN 的那一条(见 Deployment 一节)。
Decode the runtime ARN from the MCP URL for matching
def _find_record_by_mcp_url(client, registry_id, mcp_url): """Search registry records to find one whose server schema contains the runtime ARN.
Tries three matching strategies:
- Decoded ARN (e.g. arn:aws:bedrock-agentcore:...:runtime/TrimMCP-xxx)
- URL-encoded ARN (e.g. arn%3Aaws%3Abedrock-agentcore%3A...%2FTrimMCP-xxx)
- Full MCP URL match
Returns: (record_id, full_record) tuple. Both None if no match found. """
Extract the runtime ARN from the MCP URL for matching
URL format: .../runtimes/arn%3A...%2Fruntime%2F/invocations...
Decode to get: arn:aws:bedrock-agentcore:region:account:runtime/id
try: decoded_url = urllib.parse.unquote(mcp_url)
Extract just the runtime path: arn:aws:bedrock-agentcore:...:runtime/xxx
runtime_marker = "/runtimes/" idx = decoded_url.find(runtime_marker) if idx >= 0: runtime_arn = decoded_url[idx + len(runtime_marker) :].split("/invocations")[0] else: runtime_arn = None except Exception: # noqa: BLE001 runtime_arn = None records = client.list_registry_records(registryId=registry_id) record_list = records.get("registryRecords", []) print(f"Found {len(record_list)} registry records") for rec in record_list: record_id = rec.get("registryRecordId") or rec.get("recordId") or rec.get("id", "") record_name = rec.get("name", "?") record_status = rec.get("status", "?") print(f" Record: {record_id} | {record_name} | status={record_status} | keys={list(rec.keys())}") if not record_id: print(f" Warning: could not get record ID from: {list(rec.keys())}") continue if record_status == "DRAFT": print(f" Skipping DRAFT record {record_id} ({record_name}) — must be APPROVED first") continue try: full = client.get_registry_record( registryId=registry_id, recordId=record_id, ) descriptors = full.get("descriptors", {}) mcp_desc = descriptors.get("mcpServer", {}) inline = mcp_desc.get("data", "")
Match on runtime ARN (decoded or encoded) in the server schema
if runtime_arn and runtime_arn in inline: print(f"Found matching record (by ARN): {record_id} ({rec.get('name', '?')})") return record_id, full
Also check URL-encoded ARN
encoded_arn = runtime_arn.replace(":", "%3A").replace("/", "%2F") if runtime_arn else None if encoded_arn and encoded_arn in inline: print(f"Found matching record (by encoded ARN): {record_id} ({rec.get('name', '?')})") return record_id, full if mcp_url in inline or urllib.parse.unquote(mcp_url).replace("?qualifier=DEFAULT", "") in inline: print(f"Found matching record (by URL): {record_id} ({rec.get('name', '?')})") return record_id, full except Exception as e: # noqa: BLE001 print(f"Error checking record {record_id}: {e}") continue print(f"No matching record found among {len(record_list)} records.") print(f" Looking for runtime ARN: {runtime_arn}") print(f" Looking for MCP URL: {mcp_url}") return None, None
第 6 步:做 diff 并更新
为尽量减少无谓写入,工具列表会先归一化(按名称排序,用 name + description + inputSchema 比较)。只有检测到变化时才触发 registry 更新。若 schema 有差异,Lambda 会记下具体新增或移除了哪些,再把新定义推到 registry 记录里。
Normalize tool definitions for comparison (sort by name, extract key fields)
def _normalize_tools(tools): """Normalize tool list for comparison — extract name, description, inputSchema.""" normalized = [] for t in sorted(tools, key=lambda x: x.get("name", "")): normalized.append( { "name": t.get("name", ""), "description": t.get("description", ""), "inputSchema": t.get("inputSchema", {}), } ) return normalized
def _normalize_tools(tools): """Normalize tool list for comparison — extract name, description, inputSchema.""" normalized = [] for t in sorted(tools, key=lambda x: x.get("name", "")): normalized.append( { "name": t.get("name", ""), "description": t.get("description", ""), "inputSchema": t.get("inputSchema", {}), } ) return normalized
def sync_registry_if_changed(mcp_tools, mcp_url): """Compare MCP server tools with AWS Agent Registry record tools. Update only if different.
Steps:
- Find the AWS Agent Registry record matching this MCP server's URL
- Extract existing tools from the record's tools.inlineContent
- Normalize both tool lists (sort by name, compare name/description/inputSchema)
- If identical → skip update
- If different → log the diff and update the registry record
Returns: dict with 'action' key: 'no_change', 'updated', or 'skipped' """ registry_id = os.environ["REGISTRY_ID"] client = _get_registry_client()
Find the matching record
record_id, full_record = _find_record_by_mcp_url(client, registry_id, mcp_url) if not record_id: print(f"No matching registry record found for {mcp_url}") return {"action": "skipped", "reason": "no matching record"}
Get current tools from registry
registry_tools = _get_registry_tools_from_record(full_record)
Compare normalized tool lists
mcp_normalized = _normalize_tools(mcp_tools) registry_normalized = _normalize_tools(registry_tools) if mcp_normalized == registry_normalized: print(f"No change detected. Registry record {record_id} is up to date ({len(registry_tools)} tools).") return { "action": "no_change", "record_id": record_id, "tool_count": len(registry_tools), }
Tools differ — update the registry
print(f"Change detected! Registry has {len(registry_tools)} tools, MCP server has {len(mcp_tools)} tools.")
Log the diff
mcp_names = {t["name"] for t in mcp_normalized} reg_names = {t["name"] for t in registry_normalized} added = mcp_names - reg_names removed = reg_names - mcp_names if added: print(f" Added: {added}") if removed: print(f" Removed: {removed}") if not added and not removed: print(" Tool definitions changed (same names, different schemas/descriptions)") tool_schema_content = json.dumps({"tools": mcp_tools}) client.update_registry_record( registryId=registry_id, recordId=record_id, descriptors={ "optionalValue": { "mcpServer": { "optionalValue": { "additionalData": { "optionalValue": { "tools": { "optionalValue": { "data": { "optionalValue": tool_schema_content, }, } } } } } } } }, ) print(f"Updated registry record {record_id} in registry {registry_id}") return { "action": "updated", "record_id": record_id, "old_count": len(registry_tools), "new_count": len(mcp_tools), }
治理与审批工作流
AWS Agent Registry 在每条记录上强制一套治理生命周期:Draft -> Pending Approval -> Approved(或 Rejected/Deprecated)。管理员在 registry 级别配置审批设置,由这些设置决定什么能被发布、由谁评审,以及记录被发现之前是否必须人工批准。只有处于 Approved 状态的记录,消费方才能通过搜索、catalog 浏览或 registry 的 MCP endpoint 看到。
当 Lambda 用新工具定义更新一条记录时,该记录会自动退回 Draft 状态。消费方继续看到此前已批准的版本。随后必须由 curator 或管理员批准这次更新,新元数据才能被发现。这样自动化更新就无法绕过组织评审,管理员对「向消费方暴露什么」保有一切控制权。
部署
下表列出这条自动化流水线里的各步骤:
步骤说明 定义配置Region、Lambda 名称、registry ID 和 MCP server ARN 创建并批准 registry 记录注册 MCP server 条目并把它置为 APPROVED 配置 AgentCore Identity创建 workload identity 与 OAuth2 credential providers 部署 Lambda function创建 IAM execution role、打包 handler、部署函数 创建 Amazon EventBridge rule把 UpdateAgentRuntime 事件路由给 Lambda 跨账户转发(可选)转发来自远端账户的运行时事件
前置条件
部署本方案之前,确认下面几项都已就位:
一个 AWS 账户,具备创建 Lambda functions、Amazon EventBridge rules、AWS Identity and Access Management(IAM)roles 和 Agent Registry 资源的权限。 AWS Command Line Interface(AWS CLI)已配好凭证,能访问本示例用到的所有服务。更多信息见 Getting started with the AWS CLI。 Python 3.12 runtime。 一个既有的 AWS Agent Registry,其中至少有一条 MCP server 记录(在初次接入时创建;创建记录的说明见 Deployment 一节)。 一个部署在 Amazon Bedrock AgentCore runtime 上的 MCP server。 为每个 MCP server 账户配好 AgentCore Identity workload identity 和 OAuth2 credential providers(配置见 sample repository)。 对多账户配置,Account B 与 Account A 之间有跨账户 Amazon EventBridge 权限。
组织常用多个账户:registry 在一个账户,MCP servers 在别的账户。本示例勾勒的是多账户场景,按文中说明你可以把它改造成单账户场景。
创建 registry 记录
在本示例里,sync 流水线能工作之前,必须已存在一条 registry 记录,且其 server schema 里显式嵌入了 runtime ARN。你可以用下面这段代码创建 registry 记录,并把 runtime ARN 写进记录的 mcpServer.data 字段。Lambda 正是拿它来把 AWS CloudTrail 事件与记录对应起来:
The websiteUrl contains the MCP server invocation URL with the encoded
runtime ARN: this is what the Lambda matches against later.
encoded_arn = MCP_RUNTIME_ARN.replace(":", "%3A").replace("/", "%2F") mcp_server_url = ( f"https://bedrock-agentcore.{AWS_REGION}.amazonaws.com" f"/runtimes/{encoded_arn}/invocations?qualifier=DEFAULT" ) server_schema = json.dumps({ "name": MCP_SERVER_NAME, "description": MCP_SERVER_DESCRIPTION, "websiteUrl": mcp_server_url, }) registry_cp.create_registry_record( registryId=REGISTRY_ID, name=MCP_SERVER_NAME, description=MCP_SERVER_DESCRIPTION, recordType="MCP", recordVersion="1.0", descriptors={"mcpServer": {"data": server_schema}} )
批准记录
Lambda 只同步到 APPROVED 记录。
做完更新后,registry 记录处于 DRAFT 阶段。它必须走完治理工作流,变更才能被发现。
Submit for approval (DRAFT → PENDING_APPROVAL)
registry_cp.submit_registry_record_for_approval( registryId=REGISTRY_ID, recordId=RECORD_ID, )
Approve (PENDING_APPROVAL → APPROVED)
registry_cp.update_registry_record_status( registryId=REGISTRY_ID, recordId=RECORD_ID, status="APPROVED", )
Lambda 环境变量
为保持强安全姿态,Lambda 环境变量里不存任何 client secret。函数完全靠环境变量映射来引用运行时 workload identities、provider 名称和权限作用域。
No client secrets here. Only provider names and scopes.
The Lambda uses WORKLOAD_IDENTITY_NAME to get a workload token,
then CREDENTIAL_PROVIDER_{ACCT} to fetch the OAuth token.
env_vars = { "REGISTRY_ID": REGISTRY_ID, "WORKLOAD_IDENTITY_NAME": WORKLOAD_IDENTITY_NAME, } for acct_id, config in ACCOUNT_CONFIGS.items(): env_vars[f"CREDENTIAL_PROVIDER_{acct_id}"] = config["provider_name"] env_vars[f"CREDENTIAL_SCOPE_{acct_id}"] = config.get("scope", "")
Amazon EventBridge rule
这条 rule 充当流水线的触发器,监听本地账户内、或由跨账户 Amazon EventBridge bus 转发器送来的 UpdateAgentRuntime management events:
Match UpdateAgentRuntime events from AgentCore.
Fires when any runtime is created or updated in this account
(or forwarded from a cross-account EventBridge bus).
event_pattern = { "source": ["aws.bedrock-agentcore"], "detail-type": ["API Call via AWS CloudTrail"], "detail": {"eventName": ["UpdateAgentRuntime"]} } events_client.put_rule( Name=f"{LAMBDA_NAME}-trigger", EventPattern=json.dumps(event_pattern), State="ENABLED", )
清理
为避免持续产生费用,用完后删掉下面这些资源:
Lambda function – 删除 push-sync Lambda 及其 IAM execution role。 Amazon EventBridge rule – 删除该 rule 及其 Lambda target。 AgentCore Identity – 删除 workload identity 与 OAuth2 credential providers。 Registry 记录 – 删除或废弃那条测试用 MCP server 记录。 Registry – 若这个 registry 纯粹为测试而建,把它删掉。 (多账户) 移除 Account B 里的跨账户 Amazon EventBridge rule 与 resource policy。
清理代码见 sample repository。
已知局限与后续改进
本文勾勒的示例代码(以及完整示例里的代码)可以从几个方向扩展:
自动注册新的 MCP servers – 目前必须已存在一条匹配的 registry 记录。后续 enhancements 可以在首次检测到一个此前未知的 MCP server 时自动创建记录。 手动「强制同步」触发器 – 对时效敏感的部署,可以经 Amazon API Gateway 或一条 CLI 命令做一条按需调用路径,在常规 CloudTrail 投递流程之外送达变更。 冷启动韧性 – 若 MCP server 处于冷状态、返回零个工具,当前 Lambda 不会重试。加上指数退避,并在工具数为零时跳过更新,会提升可靠性。
结语
AWS Agent Registry 给组织提供了一个受治理、可被发现的 catalog,用来管他们的 AI agents 和 MCP servers。
push-sync Lambda 模式补上了新鲜度这道缺口:检测到 server 变更时,registry 记录会在 Known limitations 一节所述的约束内自动、安全地更新。更新会把记录退回 DRAFT 状态,必须走完审批工作流才能重新被发现。
当你的 agent 规模从几个增长到几百个 MCP servers,这个模式让 registry 始终是那个唯一的事实来源,既持续保持新鲜,又都经过评审。
开始使用
完整实现(Lambda 代码、部署脚本和架构图)以 ready-to-deploy sample 提供。要在你的环境里部署这套方案,克隆这个 repository,按 README 里的部署步骤操作。
关于作者