Python Agent에서 Gateway로
connection 생성기는 Python Agent를 AgentCore Gateway에 연결할 수 있습니다.
생성기는 에이전트가 배포 시 IAM SigV4(httpx 요청 서명 사용)로 Gateway에 인증하고, 로컬 실행 시 Gateway 프로젝트에서 시작한 로컬 게이트웨이에 연결하도록 연결합니다.
사전 요구 사항
섹션 제목: “사전 요구 사항”이 생성기를 사용하기 전에 다음을 확인하세요:
- Agent 컴포넌트가 있는 Python 프로젝트 (
infra: agentcore) agentcore-gateway프로젝트
사용법
섹션 제목: “사용법”생성기 실행
섹션 제목: “생성기 실행”- 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
- VSCode에서 Nx 콘솔 열기
- 클릭
Generate (UI)"Common Nx Commands" 섹션에서 - 검색
@aws/nx-plugin - connection - 필수 매개변수 입력
- 클릭
Generate
pnpm nx g @aws/nx-plugin:connectionyarn nx g @aws/nx-plugin:connectionnpx nx g @aws/nx-plugin:connectionbunx nx g @aws/nx-plugin:connection에이전트 프로젝트를 소스로, Gateway 프로젝트를 대상으로 선택하세요.
| 매개변수 | 타입 | 기본값 | 설명 |
|---|---|---|---|
| sourceProject 필수 | string | - | 소스 프로젝트 |
| targetProject 필수 | string | - | 연결할 대상 프로젝트 |
| sourceComponent | string | - | 연결을 시작할 소스 컴포넌트 (컴포넌트 이름, 소스 프로젝트 루트 기준 상대 경로, 또는 generator id). 프로젝트를 소스로 명시적으로 선택하려면 '.'을 사용하세요. |
| targetComponent | string | - | 연결할 대상 컴포넌트 (컴포넌트 이름, 대상 프로젝트 루트 기준 상대 경로, 또는 generator id). 프로젝트를 대상으로 명시적으로 선택하려면 '.'을 사용하세요. |
| preferInstallDependencies | boolean | true | 생성기 실행 후 의존성 설치를 선호할지 여부입니다. 여러 생성기를 일괄 처리할 때 설치를 연기하려면 false로 설정하세요 (후속 생성기가 Nx 프로젝트 그래프를 계산할 수 있도록 필요한 경우 설치는 여전히 실행됩니다); 마지막에 한 번만 설치합니다. |
생성기 출력
섹션 제목: “생성기 출력”생성기는 공유 core-gateway 모듈을 agent_connection Python 프로젝트에 생성하고, Gateway별 래퍼를 추가하며, 에이전트를 수정합니다:
디렉터리packages/common/agent_connection
디렉터리<scope>_agent_connection
디렉터리core/
- agentcore_endpoints.py 프레임워크 독립적인 ARN/URL 확인
- agentcore_gateway_mcp_transport.py 프레임워크 독립적인 Gateway MCP 전송
- agentcore_gateway_mcp_client_<framework>.py 에이전트 프레임워크용 Gateway MCP 클라이언트
디렉터리auth/ 프레임워크 독립적인 SigV4 / 세션 전달
httpx.Auth- …
디렉터리app/
- <gateway_snake>_client_<framework>.py Gateway별 클라이언트 래퍼
- __init__.py Gateway 클라이언트를 재내보내기
클라이언트 접미사는 에이전트의 프레임워크(_strands 또는 _langchain)와 일치합니다.
또한 생성기는:
- 에이전트의
agent.py를 수정하여 Gateway 클라이언트를 가져오고tools에 도구를 등록합니다 - 에이전트의 작업 공간 종속성으로
agent_connection을 추가합니다 - 에이전트의
<agent>-dev대상이 Gateway의dev대상에 의존하도록 연결합니다
연결된 Gateway 사용
섹션 제목: “연결된 Gateway 사용”생성기는 에이전트의 agent.py를 변환하여 Gateway 클라이언트를 사용합니다:
from contextlib import contextmanagerfrom strands import Agent
from my_scope_agent_connection import MyGatewayClientStrands
@contextmanagerdef get_agent(): my_gateway = MyGatewayClientStrands.create() with ( my_gateway, ): yield Agent( system_prompt="...", tools=[*my_gateway.list_tools_sync()], )MyGatewayClientStrands.create()는 컨텍스트 관리 가능한 단일 MCPClient를 반환하며, 이 클라이언트의 list_tools_sync()는 Gateway를 통해 사용 가능한 모든 도구를 제공합니다.
from langchain.agents import create_agentfrom langchain_aws import ChatBedrockConverse
from my_scope_agent_connection import MyGatewayClientLangChain
def get_agent(): my_gateway = MyGatewayClientLangChain.create() return create_agent( model=ChatBedrockConverse(model=MODEL_ID, region_name=REGION), system_prompt="...", tools=[*my_gateway], )MyGatewayClientLangChain.create()는 langchain-mcp-adapters를 통해 로드된 도구 목록을 반환합니다. 각 도구는 호출마다 새로운 세션을 열기 때문에 with 블록이 필요하지 않습니다.
두 경우 모두 클라이언트는 모드별로 동일하게 동작합니다:
- 배포 모드 (
LOCAL_DEV미설정): Gateway의 MCP 엔드포인트를 가리키는 도구, SigV4 서명됨. - 로컬 모드 (
LOCAL_DEV=true): Gateway 프로젝트의dev대상에서 시작한 로컬 게이트웨이를 가리키는 일반 HTTP 도구.
세션 ID는 X-Amzn-Bedrock-AgentCore-Runtime-Session-Id 헤더를 통해 다운스트림 MCP 서버로 자동으로 전파됩니다.
인프라
섹션 제목: “인프라”생성기를 실행한 후 에이전트에 Gateway를 호출할 수 있는 권한을 부여해야 합니다.
const gateway = new MyGateway(this, 'MyGateway');const myAgent = new MyAgent(this, 'MyAgent');
// Grant the agent permissions to invoke the Gatewaygateway.grantInvokeAccess(myAgent);Gateway URL은 생성된 CDK 구성에 의해 Runtime Configuration의 agentcore.gateways.<ClassName> 네임스페이스에 자동으로 등록되므로 에이전트가 런타임에 이를 검색할 수 있습니다.
module "my_gateway" { source = "../../common/terraform/src/app/gateways/my-gateway"}
module "my_agent" { source = "../../common/terraform/src/app/agents/my-agent"}
# Grant the agent permission to invoke the Gatewayresource "aws_iam_policy" "agent_invoke_gateway" { name = "AgentInvokeGatewayPolicy" policy = jsonencode({ Version = "2012-10-17" Statement = [{ Effect = "Allow" Action = "bedrock-agentcore:InvokeGateway" Resource = module.my_gateway.gateway_arn }] })}
resource "aws_iam_role_policy_attachment" "agent_invoke_gateway" { role = module.my_agent.agent_core_runtime_role_arn policy_arn = aws_iam_policy.agent_invoke_gateway.arn}Gateway URL은 생성된 Terraform 모듈에 의해 Runtime Configuration의 agentcore.gateways.<ClassName> 네임스페이스에 자동으로 등록되므로 에이전트가 런타임에 이를 검색할 수 있습니다.
로컬 개발
섹션 제목: “로컬 개발”생성기는 에이전트의 dev 대상을 다음과 같이 구성합니다:
- 연결된 Gateway의 로컬 게이트웨이와 연결된 모든 MCP 서버 시작
LOCAL_DEV=true를 설정하여 생성된 클라이언트가 배포된 Gateway 대신 로컬 게이트웨이를 가리키도록 함
다음 명령으로 에이전트를 로컬에서 실행하세요:
pnpm nx <agent-name>-dev <project-name>yarn nx <agent-name>-dev <project-name>npx nx <agent-name>-dev <project-name>bunx nx <agent-name>-dev <project-name>에이전트를 로컬에서 배포된 Gateway에 대해 실행하려면(예: Cedar 정책을 테스트하기 위해) 에이전트의 serve 대상을 사용하세요. LOCAL_DEV이 설정되지 않으면 클라이언트는 런타임 구성에서 배포된 Gateway URL을 확인하고 로컬 AWS 자격 증명으로 요청에 SigV4 서명합니다:
pnpm nx <agent-name>-serve <project-name>yarn nx <agent-name>-serve <project-name>npx nx <agent-name>-serve <project-name>bunx nx <agent-name>-serve <project-name>로컬 충실도
섹션 제목: “로컬 충실도”로컬 게이트웨이는 배포된 Gateway를 대신하므로:
- Cedar 정책 평가 없음. 정책에 관계없이 모든 도구가 에이전트에 표시됩니다. 배포된 Gateway에 대해 정책을 테스트하려면
serve대상을 사용하세요. - 도구 이름 접두사는 유지됨. 각 로컬 MCP 서버의 도구는
<target-name>___<tool-name>으로 노출되며, 이는 배포된 Gateway가 생성하는 것과 일치합니다. 이를 통해 에이전트의 시스템 프롬프트와 참조하는 Cedar 액션 이름이 로컬 및 배포 실행 간에 일관성을 유지합니다.