跳转到内容

Python Agent 到 MCP

connection 生成器可以将您的 Python Agent 连接到 MCP 服务器(TypeScriptPython)。

该生成器会设置所有必要的连接,使您的代理能够发现并调用 MCP 服务器的工具,无论是部署到 AWS(通过 Bedrock AgentCore)还是在本地运行。

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

  1. 一个包含 Python Agent 组件(Strands 或 LangChain)的 Python 项目
  2. 一个包含 MCP 服务器组件的项目(ts#mcp-serverpy#mcp-server
  3. 两个组件都使用 infra: agentcore 创建
Terminal window
pnpm nx g @aws/nx-plugin:connection
您还可以执行试运行以查看哪些文件会被更改
Terminal window
pnpm nx g @aws/nx-plugin:connection --dry-run

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

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

生成器会在 packages/common/agent_connection/ 创建一个共享的 agent_connection Python 项目(如果尚不存在)。每个连接的客户端模块都会生成到这个共享项目中:

  • 文件夹packages/common/agent_connection
    • 文件夹<scope>_agent_connection
      • __init__.py 重新导出每个连接的客户端
      • 文件夹core
        • agentcore_endpoints.py 框架无关的 ARN/URL 解析
        • agentcore_mcp_transport.py 框架无关的 MCP 传输
        • agentcore_mcp_client_<framework>.py 为您的代理框架包装传输的 MCP 客户端
        • 文件夹auth/ 框架无关的 SigV4 / 会话转发 httpx.Auth
      • 文件夹app
        • <mcp_server_name>_client_<framework>.py 每个 MCP 服务器的连接客户端

客户端后缀与您的代理框架匹配(_strands_langchain)。

此外,生成器还会:

  • 转换您的代理的 agent.py,通过基于类的客户端导入并使用 MCP 服务器的工具
  • agent_connection 项目添加为您的代理项目的工作区依赖项
  • 更新代理的 dev 目标以依赖于 MCP 服务器的 serve 目标

生成器会转换您的代理的 agent.py 以使用 MCP 服务器的工具:

packages/my-project/my_module/agent/agent.py
from contextlib import contextmanager
from strands import Agent
from my_scope_agent_connection import MyMcpServerClientStrands
@contextmanager
def get_agent():
my_mcp_server = MyMcpServerClientStrands.create()
with (
my_mcp_server,
):
yield Agent(
system_prompt="...",
tools=[*my_mcp_server.list_tools_sync()],
)

Strands 客户端是一个上下文管理器,在代理周围的 with 块中进入。

AgentCore 会话 ID 会通过 X-Amzn-Bedrock-AgentCore-Runtime-Session-Id 标头自动传播到 MCP 服务器,适用于两种框架,确保 Bedrock AgentCore 可观测性的一致性。

运行连接生成器后,您需要授予代理调用 MCP 服务器的权限:

packages/infra/src/stacks/application-stack.ts
const mcpServer = new MyMcpServer(this, 'MyMcpServer');
const myAgent = new MyAgent(this, 'MyAgent');
// Grant the agent permissions to invoke the MCP server
mcpServer.grantInvokeAccess(myAgent);

MCP 服务器的 AgentCore 运行时 ARN 会由生成的 CDK 构造自动注册到 运行时配置agentcore 命名空间中,以便代理可以在运行时发现它。

生成器会配置代理的 dev 目标以:

  1. 自动启动已连接的 MCP 服务器
  2. 设置 LOCAL_DEV=true,使生成的客户端使用直接 HTTP 传输而不是 AgentCore

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

Terminal window
pnpm nx <agent-name>-dev <project-name>

这将启动代理和所有已连接的 MCP 服务器,代理通过 HTTP 在其分配的本地端口上直接连接到 MCP 服务器。