跳转到内容

AgentCore Gateway 到 MCP Server

connection 生成器可以将 MCP 服务器(TypeScriptPython)注册为 AgentCore Gateway 的目标。

连接后,Gateway 将 MCP 服务器的工具聚合到其单一的 MCP 端点中,根据其 Cedar 策略引擎评估调用,并使用 IAM SigV4 对发往 MCP 服务器的出站流量进行签名。

在使用此生成器之前,请确保您具备:

  1. 一个 agentcore-gateway 项目
  2. 一个使用 infra: agentcoreauth: iam 创建的 MCP 服务器组件(ts#mcp-serverpy#mcp-server

Gateway 必须具有 protocol: mcp,MCP 服务器必须具有 auth: iam — 生成器会验证这两者。无法附加非 IAM 的 MCP 服务器,因为 Gateway 使用 SigV4 对出站流量进行签名。

Terminal window
pnpm nx g @aws/nx-plugin:connection
您还可以执行试运行以查看哪些文件会被更改
Terminal window
pnpm nx g @aws/nx-plugin:connection --dry-run

选择 Gateway 项目作为源,MCP 服务器项目作为目标。如果 MCP 服务器项目包含多个组件,请指定 targetComponent 以消除歧义。

参数类型默认值描述
sourceProject 必需string-源项目
targetProject 必需string-要连接到的目标项目
sourceComponent string-要从其连接的源组件(组件名称、相对于源项目根目录的路径或生成器 ID)。使用 '.' 显式选择项目作为源。
targetComponent string-要连接到的目标组件(组件名称、相对于目标项目根目录的路径或生成器 ID)。使用 '.' 显式选择项目作为目标。
preferInstallDependencies booleantrue是否在生成器运行后优先安装依赖项。设置为 false 可在批量运行多个生成器时延迟安装(如果后续生成器需要计算 Nx 项目图,仍会运行安装);在最后统一安装一次。

生成器将现有项目连接在一起,而不是生成新的源文件。以下文件会被修改:

  • 文件夹packages/<gateway>
    • project.json Gateway 的 dev 目标获得对 MCP 服务器的 <mcp>-dev 的依赖
    • local-dev.ts ATTACHED_MCP_SERVERS 已更新,以便本地 gateway 聚合 MCP 服务器

Gateway 项目的 dev 目标获得对 MCP 服务器的 <mcp>-dev 目标的依赖,因此在本地运行 Gateway 时也会启动 MCP 服务器。MCP 服务器还会在 Gateway 项目的 local-dev.ts 中注册,以便本地 gateway 聚合其工具。

将 MCP 服务器目标添加到您的堆栈

Section titled “将 MCP 服务器目标添加到您的堆栈”

生成器无法自动将 MCP 服务器目标连接到您的基础设施中,因为它不知道哪个堆栈或模块实例化了 Gateway。您需要自己添加一个对 gateway.addMcpServer(server) 的调用。

在实例化 Gateway 的堆栈中,将 MCP 服务器注册为目标:

packages/infra/src/stacks/application-stack.ts
const myMcpServer = new MyMcpServer(this, 'MyMcpServer');
const myGateway = new MyGateway(this, 'MyGateway');
// Register the MCP server as a target of the Gateway. The target name
// defaults to the MCP server's `mcpServerName` (its class name in
// kebab-case, e.g. `MyMcpServer` -> `my-mcp-server`).
myGateway.addMcpServer(myMcpServer);

Gateway 目标名称(默认为 MCP 服务器的 mcpServerName)用作 Cedar 操作名称的前缀 — 操作格式为 AgentCore::Action::"<targetName>___<toolName>"。请参阅编写策略部分。保持目标名称简短且稳定;稍后更改它会使引用旧名称的任何 Cedar 策略失效。

要覆盖默认目标名称,请传递 gatewayTargetName

myGateway.addMcpServer(myMcpServer, { gatewayTargetName: 'my-mcp' });

该构造使用 iamCredentialProvider.service = 'bedrock-agentcore' 配置目标,以便 Gateway 使用其自己的执行角色对出站调用进行签名。

使用以下命令在本地运行 Gateway:

Terminal window
pnpm nx dev <gateway-name>

启动本地 gateway 以及每个附加的 MCP 服务器在其分配的本地端口上。本地 gateway 公开一个单一的 MCP 端点,该端点聚合附加服务器的工具。通过 TypeScriptPython gateway-connection 生成器连接到 Gateway 的 Agent 在使用 LOCAL_DEV=true 运行时会指向它。