跳转到内容

Python Strands Agent 到 MCP

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

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

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

  1. 一个包含 Strands Agent 组件的 Python 项目
  2. 一个包含 MCP 服务器组件的项目(可以是 ts#mcp-serverpy#mcp-server)
  3. 两个组件都使用 computeType: BedrockAgentCoreRuntime 创建
  1. 安装 Nx Console VSCode Plugin 如果您尚未安装
  2. 在VSCode中打开Nx控制台
  3. 点击 Generate (UI) 在"Common Nx Commands"部分
  4. 搜索 @aws/nx-plugin - connection
  5. 填写必需参数
    • 点击 Generate

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

    参数 类型 默认值 描述
    sourceProject 必需 string - 源项目
    targetProject 必需 string - 要连接到的目标项目
    sourceComponent string - 要从其连接的源组件(组件名称、相对于源项目根目录的路径或生成器 ID)。使用 '.' 显式选择项目作为源。
    targetComponent string - 要连接到的目标组件(组件名称、相对于目标项目根目录的路径或生成器 ID)。使用 '.' 显式选择项目作为目标。

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

    • 文件夹packages/common/agent_connection
      • 文件夹<scope>_agent_connection
        • __init__.py 重新导出每个连接的客户端
        • 文件夹core
          • agentcore_mcp_client.py 核心 AgentCore MCP 客户端
        • 文件夹app
          • <mcp_server_name>_client.py 每个 MCP 服务器的专用连接客户端

    此外,生成器还会:

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

    生成器会转换您的代理的 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 MyMcpServerClient
    @contextmanager
    def get_agent(session_id: str):
    my_mcp_server = MyMcpServerClient.create(session_id=session_id)
    with (
    my_mcp_server,
    ):
    yield Agent(
    system_prompt="...",
    tools=[*my_mcp_server.list_tools_sync()],
    )

    session_id 参数从调用方传递,确保 Bedrock AgentCore Observability 的一致性。

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

    packages/infra/src/stacks/application-stack.ts
    const mcpServer = new MyMcpServer(this, 'MyMcpServer');
    const myAgent = new MyAgent(this, 'MyAgent');
    // Grant the agent access to bedrock models
    myAgent.agentCoreRuntime.addToRolePolicy(
    new PolicyStatement({
    actions: ['bedrock:InvokeModel', 'bedrock:InvokeModelWithResponseStream'],
    resources: ['arn:aws:bedrock:*:*:foundation-model/*', 'arn:aws:bedrock:*:*:inference-profile/*'],
    }),
    );
    // Grant the agent permissions to invoke the MCP server
    mcpServer.grantInvokeAccess(myAgent.agentCoreRuntime);

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

    生成器会配置代理的 serve-local 目标以:

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

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

    Terminal window
    pnpm nx <agent-name>-serve-local <project-name>

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