TypeScript Agent
도구를 사용하여 AI 에이전트를 구축하기 위한 TypeScript Strands Agent를 생성하고, 선택적으로 Amazon Bedrock AgentCore Runtime에 배포합니다. 기본적으로 생성기는 WebSocket을 통한 tRPC를 사용하여 실시간 타입 안전 통신을 위한 AgentCore의 양방향 스트리밍 지원을 활용합니다. 또는 다른 A2A 호환 에이전트와의 상호 운용성을 위해 Agent-to-Agent (A2A) 프로토콜을 선택하거나, CopilotKit을 통한 직접 프론트엔드 통합을 위해 AG-UI 프로토콜을 선택할 수 있습니다.
Strands란 무엇인가요?
섹션 제목: “Strands란 무엇인가요?”Strands는 AI 에이전트를 구축하기 위한 경량 프레임워크입니다. 주요 기능은 다음과 같습니다:
- 경량 및 커스터마이징 가능: 방해하지 않는 간단한 에이전트 루프
- 프로덕션 준비: 확장을 위한 완전한 관찰성, 추적 및 배포 옵션
- 모델 및 제공자 독립적: 다양한 제공자의 여러 모델 지원
- 커뮤니티 기반 도구: 커뮤니티가 기여한 강력한 도구 세트
- 멀티 에이전트 지원: 에이전트 팀 및 자율 에이전트와 같은 고급 기술
- 유연한 상호작용 모드: 대화형, 스트리밍 및 비스트리밍 지원
사용법
섹션 제목: “사용법”Agent 생성
섹션 제목: “Agent 생성”두 가지 방법으로 TypeScript Agent를 생성할 수 있습니다:
pnpm nx g @aws/nx-plugin:ts#agentyarn nx g @aws/nx-plugin:ts#agentnpx nx g @aws/nx-plugin:ts#agentbunx nx g @aws/nx-plugin:ts#agent- 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
- VSCode에서 Nx 콘솔 열기
- 클릭
Generate (UI)"Common Nx Commands" 섹션에서 - 검색
@aws/nx-plugin - ts#agent - 필수 매개변수 입력
- 클릭
Generate
| 매개변수 | 타입 | 기본값 | 설명 |
|---|---|---|---|
| project 필수 | string | - | Agent를 추가할 프로젝트 |
| framework | strands | strands | 사용할 에이전트 SDK입니다. |
| name | string | - | Agent의 이름 (기본값: agent) |
| auth | iam | cognito | iam | 에이전트 인증에 사용되는 방법입니다. infra가 설정된 경우에만 적용됩니다 (infra가 none일 때는 무시됨). |
| protocol | http | a2a | ag-ui | http | Agent의 서버 프로토콜입니다. HTTP는 tRPC/WebSocket 서버를 노출합니다. A2A는 Agent-to-Agent 프로토콜 서버를 노출합니다. AG-UI는 CopilotKit과의 직접적인 프론트엔드 통합을 위한 AG-UI 프로토콜 서버를 노출합니다. |
| iac | inherit | cdk | terraform | inherit | 선호하는 IaC 공급자입니다. 기본적으로 초기 선택에서 상속됩니다. |
| infra | agentcore | none | agentcore | 에이전트를 호스팅할 인프라 유형입니다. |
| session | s3 | in-memory | s3 | Agent의 세션을 유지하기 위해 사용되는 스토리지입니다. |
| preferInstallDependencies | boolean | true | 생성기 실행 후 의존성 설치를 선호할지 여부입니다. 여러 생성기를 일괄 처리할 때 설치를 연기하려면 false로 설정하세요(후속 생성기가 Nx 프로젝트 그래프를 계산할 수 있도록 필요한 경우 설치는 여전히 실행됩니다). 마지막에 한 번만 설치하세요. |
생성기 출력
섹션 제목: “생성기 출력”생성기는 기존 TypeScript 프로젝트에 다음 파일을 추가합니다. 생성되는 파일은 선택한 protocol에 따라 다릅니다:
HTTP 프로토콜 (기본값)
섹션 제목: “HTTP 프로토콜 (기본값)”디렉터리your-project/
디렉터리src/
디렉터리agent/ (or custom name if specified)
- index.ts Entry point for Bedrock AgentCore Runtime (tRPC/WebSocket server)
- init.ts tRPC initialization
- router.ts tRPC router with agent procedures
- agent.ts Main agent definition with sample tools
- session.ts Resolves the SessionManager used to persist conversation state
- client.ts Vended client for invoking your agent
- agent-core-trpc-client.ts Client factory for connecting to agents on AgentCore Runtime
- Dockerfile Entry point for hosting your agent (excluded when
infrais set toNone)
- package.json Updated with Strands dependencies
- project.json Updated with agent serve targets
A2A 프로토콜
섹션 제목: “A2A 프로토콜”진입점은 tRPC 대신 Strands A2A Express Server를 사용합니다:
디렉터리your-project/
디렉터리src/
디렉터리agent/ (or custom name if specified)
- index.ts A2A Express server entry point
- agent.ts Main agent definition with sample tools
- session.ts Resolves the SessionManager used to persist conversation state
- Dockerfile Entry point for hosting your agent (excluded when
infrais set toNone)
- package.json Updated with Strands and Express dependencies
- project.json Updated with agent serve targets
AG-UI 프로토콜
섹션 제목: “AG-UI 프로토콜”진입점은 @ag-ui/aws-strands를 사용하여 AG-UI 프로토콜 (SSE over POST)을 통해 에이전트를 노출하며, CopilotKit과 호환됩니다:
디렉터리your-project/
디렉터리src/
디렉터리agent/ (or custom name if specified)
- index.ts AG-UI server entry point (Express + SSE)
- agent.ts Main agent definition with sample tools
- session.ts Resolves the SessionManager used to persist conversation state
- Dockerfile Entry point for hosting your agent (excluded when
infrais set toNone)
- package.json Updated with Strands and AG-UI dependencies
- project.json Updated with agent serve targets
인프라
섹션 제목: “인프라”이 생성기는 선택한 iac를 기반으로 코드형 인프라를 제공하므로, 관련 CDK constructs 또는 Terraform 모듈을 포함하는 packages/common에 프로젝트를 생성합니다.
공통 코드형 인프라 프로젝트는 다음과 같이 구성됩니다:
디렉터리packages/common/constructs
디렉터리src
디렉터리app/ 프로젝트/생성기에 특정한 인프라를 위한 Constructs
- …
디렉터리core/
app의 constructs에서 재사용되는 일반 constructs- …
- index.ts
app에서 constructs를 내보내는 진입점
- project.json 프로젝트 빌드 타겟 및 구성
디렉터리packages/common/terraform
디렉터리src
디렉터리app/ 프로젝트/생성기에 특정한 인프라를 위한 Terraform 모듈
- …
디렉터리core/
app의 모듈에서 재사용되는 일반 모듈- …
- project.json 프로젝트 빌드 타겟 및 구성
Agent를 배포하기 위해 다음 파일이 생성됩니다:
디렉터리packages/common/constructs/src
디렉터리app
디렉터리agents
디렉터리<project-name>
- <project-name>.ts CDK construct for deploying your agent
디렉터리packages/common/terraform/src
디렉터리app
디렉터리agents
디렉터리<project-name>
- <project-name>.tf Module for deploying your agent
디렉터리core
디렉터리agent-core
- runtime.tf Generic module for deploying to Bedrock AgentCore Runtime
infra에 대해 none을 선택한 경우 CDK 구성 또는 Terraform 모듈이 생성되지 않으며, Agent는 로컬에서만 실행할 수 있습니다. 인증할 호스팅 엔드포인트가 없으므로 이 모드에서는 auth 옵션이 무시됩니다.
아키텍처
섹션 제목: “아키텍처”Bedrock AgentCore Runtime에 배포되면, 에이전트는 컨테이너 이미지로 빌드되어 Amazon ECR에 푸시되고 AgentCore Runtime에서 실행됩니다. 클라이언트는 AgentCore Runtime 데이터 플레인 엔드포인트를 호출하며, 이는 요청을 에이전트로 전달합니다. 에이전트는 모델 추론을 위해 Amazon Bedrock을 호출하고 도구, MCP 서버 또는 다운스트림 API를 호출할 수 있습니다.
infra: none을 사용하면 AWS 인프라가 생성되지 않습니다. 에이전트는 로컬 프로세스로 실행되며 모델 추론을 위해 Amazon Bedrock을 호출합니다.
Agent 작업하기
섹션 제목: “Agent 작업하기”프로토콜
섹션 제목: “프로토콜”에이전트의 서버 프로토콜은 통신 방식을 결정합니다. 다음 중에서 선택할 수 있습니다:
- HTTP (기본값): 실시간 타입 안전 통신을 위해 WebSocket을 통한 tRPC를 사용합니다. 커스텀 클라이언트 통합 및 에이전트 API에 대한 세밀한 제어에 가장 적합합니다.
- A2A: 표준화된 에이전트 간 통신을 위해 Agent-to-Agent (A2A) 프로토콜을 사용합니다. 에이전트가 다른 A2A 호환 에이전트에 의해 검색 및 호출 가능해야 할 때 가장 적합합니다.
- AG-UI:
@ag-ui/aws-strands를 통해 AG-UI 프로토콜 (SSE over POST)을 사용하여 CopilotKit과의 직접 프론트엔드 통합을 제공합니다. 스트리밍, 도구 호출 시각화 및 상태 관리를 갖춘 풍부한 채팅 UI를 원할 때 가장 적합합니다.
프로토콜은 CDK/Terraform 인프라에서 설정되며, 애플리케이션 코드는 그에 따라 생성됩니다.
WebSocket을 통한 tRPC (HTTP 프로토콜)
섹션 제목: “WebSocket을 통한 tRPC (HTTP 프로토콜)”TypeScript Agent는 WebSocket을 통한 tRPC를 사용하여 AgentCore의 양방향 스트리밍 지원을 활용하여 클라이언트와 에이전트 간의 실시간 타입 안전 통신을 가능하게 합니다.
tRPC는 WebSocket을 통한 Query, Mutation 및 Subscription 프로시저를 지원하므로 원하는 수의 프로시저를 정의할 수 있습니다. 기본적으로 router.ts에 invoke라는 단일 subscription 프로시저가 정의되어 있습니다.
도구 추가
섹션 제목: “도구 추가”도구는 AI 에이전트가 작업을 수행하기 위해 호출할 수 있는 함수입니다. agent.ts 파일에서 새 도구를 추가할 수 있습니다:
import { Agent, tool } from '@strands-agents/sdk';import { z } from 'zod';
const letterCounter = tool({ name: 'letter_counter', description: 'Count occurrences of a specific letter in a word', inputSchema: z.object({ word: z.string().describe('The input word to search in'), letter: z.string().length(1).describe('The specific letter to count'), }), callback: (input) => { const { word, letter } = input; const count = word.toLowerCase().split(letter.toLowerCase()).length - 1; return `The letter '${letter}' appears ${count} time(s) in '${word}'`; },});
// Add tools to your agentexport const getAgent = async () => { return new Agent({ systemPrompt: 'You are a helpful assistant with access to various tools.', tools: [letterCounter], });};Strands 프레임워크는 다음을 자동으로 처리합니다:
- Zod 스키마를 사용한 입력 검증
- 도구 호출을 위한 JSON 스키마 생성
- 오류 처리 및 응답 포맷팅
모델 구성
섹션 제목: “모델 구성”기본적으로 Strands 에이전트는 Claude 4 Sonnet을 사용하지만, 모델 제공자 간에 쉽게 전환할 수 있습니다:
import { Agent } from '@strands-agents/sdk';import { BedrockModel } from '@strands-agents/sdk/models/bedrock';import { OpenAIModel } from '@strands-agents/sdk/models/openai';
// Use Bedrockconst bedrockModel = new BedrockModel({ modelId: 'anthropic.claude-sonnet-4-20250514-v1:0',});let agent = new Agent({ model: bedrockModel });let response = await agent.invoke('What can you help me with?');
// Alternatively, use OpenAI by just switching model providerconst openaiModel = new OpenAIModel({ apiKey: process.env.OPENAI_API_KEY, modelId: 'gpt-4o',});agent = new Agent({ model: openaiModel });response = await agent.invoke('What can you help me with?');더 많은 구성 옵션은 모델 제공자에 대한 Strands 문서를 참조하세요.
MCP 서버 사용
섹션 제목: “MCP 서버 사용”Strands 에이전트에 MCP 서버의 도구를 추가할 수 있습니다.
py#mcp-server 또는 ts#mcp-server 생성기를 사용하여 생성한 MCP 서버를 사용하려면 connection 생성기를 활용할 수 있습니다.
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- 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
- VSCode에서 Nx 콘솔 열기
- 클릭
Generate (UI)"Common Nx Commands" 섹션에서 - 검색
@aws/nx-plugin - connection - 필수 매개변수 입력
- 클릭
Generate
연결 설정 방법에 대한 자세한 내용은 connection 생성기 가이드를 참조하세요.
다른 MCP 서버의 경우 Strands 문서를 참조하세요.
더 보기
섹션 제목: “더 보기”Strands 에이전트 작성에 대한 더 심층적인 가이드는 Strands 문서를 참조하세요.
A2A 서버 (A2A 프로토콜)
섹션 제목: “A2A 서버 (A2A 프로토콜)”생성된 index.ts는 Strands A2A Express Server를 Express 앱에 마운트하여 생성된 에이전트가 /ping 헬스 체크와 함께 A2A 프로토콜 엔드포인트를 노출하도록 합니다. AgentCore에 배포될 때 진입점은 AppConfig에서 런타임의 공개 ARN을 확인하고 에이전트 카드에 광고합니다.
대부분의 사용자는 이 파일을 수정할 필요가 없습니다. 도구나 시스템 프롬프트를 변경하려면 agent.ts를 편집하세요. A2A 에이전트는 포트 9000에서 수신 대기하며(HTTP의 경우 8080), 생성된 Dockerfile 및 인프라가 이미 이에 맞게 구성되어 있습니다.
AG-UI 서버 (AG-UI 프로토콜)
섹션 제목: “AG-UI 서버 (AG-UI 프로토콜)”생성된 index.ts는 Strands Agent를 @ag-ui/aws-strands StrandsAgent로 래핑하고 createStrandsApp()을 통해 Express 앱을 생성합니다. 결과 앱은 Server-Sent Events (SSE)를 통해 AG-UI 이벤트를 스트리밍하는 단일 POST 엔드포인트와 AgentCore 런타임 헬스 체크를 위한 /ping을 노출합니다.
AG-UI 에이전트는 프론트엔드에서 직접 사용되도록 설계되었습니다. connection 생성기를 사용하여 CopilotKit 제공자 및 AG-UI HttpAgent 클라이언트로 React 웹사이트를 에이전트에 연결하세요.
대부분의 사용자는 index.ts를 수정할 필요가 없습니다. 도구나 시스템 프롬프트를 변경하려면 agent.ts를 편집하세요. AG-UI 에이전트는 포트 8080에서 수신 대기하며(HTTP와 동일), 생성된 Dockerfile 및 인프라가 이미 이에 맞게 구성되어 있습니다.
Agent 실행
섹션 제목: “Agent 실행”로컬 개발
섹션 제목: “로컬 개발”Agent(및 연결된 모든 것)를 로컬에서 실행하려면 프로젝트의 dev 타겟을 사용하세요:
pnpm nx dev your-projectyarn nx dev your-projectnpx nx dev your-projectbunx nx dev your-project프로젝트에 여러 구성 요소(에이전트, MCP 서버 등)를 추가한 경우 이 명령은 모두 시작합니다. 이 에이전트만 실행하려면 <your-agent-name>-dev 타겟을 대상으로 지정하세요:
pnpm nx agent-dev your-projectyarn nx agent-dev your-projectnpx nx agent-dev your-projectbunx nx agent-dev your-project이는 tsx --watch를 사용하여 파일이 변경될 때 서버를 자동으로 재시작합니다. 에이전트는 http://localhost:8081(또는 여러 에이전트가 있는 경우 할당된 포트)에서 사용할 수 있습니다.
Agent와 채팅
섹션 제목: “Agent와 채팅”생성기는 에이전트와 대화형 터미널 채팅을 할 수 있는 <your-agent-name>-chat Nx 타겟을 구성합니다.
채팅 타겟은 독립적으로 실행됩니다. 기본적으로 로컬에서 실행 중인 에이전트에 연결되므로 먼저 에이전트의 <your-agent-name>-dev 타겟을 시작하세요(별도의 터미널에서):
pnpm nx agent-dev your-projectyarn nx agent-dev your-projectnpx nx agent-dev your-projectbunx nx agent-dev your-project그런 다음 다른 터미널에서 채팅을 시작하세요:
pnpm nx run your-project:agent-chatyarn nx run your-project:agent-chatnpx nx run your-project:agent-chatbunx nx run your-project:agent-chat생성기는 모든 프로토콜에 대해 scripts/<your-agent-name>/chat.ts를 생성합니다. 에이전트의 입력 형태가 발전함에 따라 이를 커스터마이징할 수 있습니다. 기본적으로 로컬 에이전트에 연결하거나 RUNTIME_CONFIG_APP_ID가 설정된 경우 배포된 에이전트에 연결합니다(아래 배포된 에이전트와 채팅 참조).
배포된 에이전트와 채팅
섹션 제목: “배포된 에이전트와 채팅”Bedrock AgentCore에 배포된 에이전트와 채팅하려면 RUNTIME_CONFIG_APP_ID 환경 변수를 배포의 AppConfig 애플리케이션 ID(배포된 스택에서 RuntimeConfigApplicationId로 출력됨)로 설정하세요. 채팅 스크립트는 런타임 구성에서 에이전트의 런타임 ARN을 확인하고 배포된 엔드포인트에 연결합니다:
IAM 인증 에이전트의 경우 요청은 기본 AWS 자격 증명을 사용하여 SigV4로 서명됩니다. 환경에 런타임을 호출할 권한이 있는 AWS 자격 증명이 있는지 확인하세요:
RUNTIME_CONFIG_APP_ID=<app-id> pnpm nx run your-project:agent-chatRUNTIME_CONFIG_APP_ID=<app-id> yarn nx run your-project:agent-chatRUNTIME_CONFIG_APP_ID=<app-id> npx nx run your-project:agent-chatRUNTIME_CONFIG_APP_ID=<app-id> bunx nx run your-project:agent-chatCognito 인증 에이전트의 경우 AGENT_ACCESS_TOKEN 환경 변수를 통해 Cognito 액세스 토큰을 제공하세요. 이는 bearer 토큰으로 전송됩니다:
RUNTIME_CONFIG_APP_ID=<app-id> AGENT_ACCESS_TOKEN=<access-token> pnpm nx run your-project:agent-chatRUNTIME_CONFIG_APP_ID=<app-id> AGENT_ACCESS_TOKEN=<access-token> yarn nx run your-project:agent-chatRUNTIME_CONFIG_APP_ID=<app-id> AGENT_ACCESS_TOKEN=<access-token> npx nx run your-project:agent-chatRUNTIME_CONFIG_APP_ID=<app-id> AGENT_ACCESS_TOKEN=<access-token> bunx nx run your-project:agent-chatAWS CLI의 cognito-idp admin-initiate-auth 명령을 사용하여 액세스 토큰을 얻을 수 있습니다. 예를 들어:
aws cognito-idp admin-initiate-auth \ --user-pool-id <user-pool-id> \ --client-id <user-pool-client-id> \ --auth-flow ADMIN_NO_SRP_AUTH \ --auth-parameters USERNAME=<username>,PASSWORD=<password> \ --query 'AuthenticationResult.AccessToken' \ --output textBedrock AgentCore Runtime에 Agent 배포
섹션 제목: “Bedrock AgentCore Runtime에 Agent 배포”Infrastructure as Code
섹션 제목: “Infrastructure as Code”infra에 대해 agentcore를 선택한 경우, 관련 CDK 또는 Terraform 인프라가 생성되며 이를 사용하여 Agent를 Amazon Bedrock AgentCore Runtime에 배포할 수 있습니다.
제너레이터를 실행할 때 선택한 name을 기반으로 하거나 기본적으로 <ProjectName>Agent로 명명된 Agent용 CDK 구성이 생성됩니다.
이 CDK 구성을 CDK 애플리케이션에서 사용할 수 있습니다:
import { MyProjectAgent } from '@my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { new MyProjectAgent(this, 'MyProjectAgent'); }}제너레이터를 실행할 때 선택한 name을 기반으로 하거나 기본적으로 <ProjectName>-agent로 명명된 Terraform 모듈이 생성됩니다.
공유된 runtime_config_appconfig 모듈의 출력을 에이전트 모듈에 전달하세요:
module "my_project_agent" { source = "../../common/terraform/src/app/agents/my-project-agent"
appconfig_application_id = module.runtime_config_appconfig.application_id appconfig_application_arn = module.runtime_config_appconfig.application_arn}Authentication
섹션 제목: “Authentication”제너레이터는 Agent에 대한 인증을 구성하기 위한 auth 옵션을 제공합니다. 에이전트를 생성할 때 IAM(기본값) 또는 Cognito 인증 중에서 선택할 수 있습니다.
IAM
섹션 제목: “IAM”기본적으로 Agent는 IAM 인증을 사용하여 보호되며, 인수 없이 배포하면 됩니다:
import { MyProjectAgent } from '@my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { new MyProjectAgent(this, 'MyProjectAgent'); }}grantInvokeAccess 메서드를 사용하여 Bedrock AgentCore Runtime에서 에이전트를 호출할 수 있는 액세스 권한을 부여할 수 있습니다. 예를 들어:
import { MyProjectAgent } from '@my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { const agent = new MyProjectAgent(this, 'MyProjectAgent'); const lambdaFunction = new Function(this, ...);
agent.grantInvokeAccess(lambdaFunction); }}# Agentmodule "my_project_agent" { # Relative path to the generated module in the common/terraform project source = "../../common/terraform/src/app/agents/my-project-agent"
appconfig_application_id = module.runtime_config_appconfig.application_id appconfig_application_arn = module.runtime_config_appconfig.application_arn}에이전트를 호출할 수 있는 액세스 권한을 부여하려면 module.my_project_agent.agent_core_runtime_arn 출력을 참조하는 다음과 같은 정책을 추가해야 합니다:
{ Effect = "Allow" Action = [ "bedrock-agentcore:InvokeAgentRuntime" ] Resource = [ module.my_project_agent.agent_core_runtime_arn, "${module.my_project_agent.agent_core_runtime_arn}/*" ]}Cognito Authentication
섹션 제목: “Cognito Authentication”Cognito 인증을 선택하면 제너레이터가 Cognito를 사용하도록 에이전트를 구성합니다.
생성된 구성은 Cognito 인증을 구성하는 identity prop을 허용합니다:
import { MyProjectAgent, UserIdentity } from '@my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { const identity = new UserIdentity(this, 'Identity');
new MyProjectAgent(this, 'MyProjectAgent', { identity, }); }}UserIdentity 구성은 ts#website#auth 제너레이터를 사용하여 생성할 수 있으며, 또는 자체 CDK UserPool 및 UserPoolClient를 생성할 수 있습니다.
생성된 모듈은 Cognito 인증을 위한 user_pool_id 및 user_pool_client_ids 변수를 허용합니다:
module "user_identity" { source = "../../common/terraform/src/core/user-identity"}
module "my_project_agent" { source = "../../common/terraform/src/app/agents/my-project-agent"
appconfig_application_id = module.runtime_config_appconfig.application_id appconfig_application_arn = module.runtime_config_appconfig.application_arn
user_pool_id = module.user_identity.user_pool_id user_pool_client_ids = [module.user_identity.user_pool_client_id]}번들 타겟
섹션 제목: “번들 타겟”제너레이터는 Rolldown을 사용하여 배포 패키지를 생성하는 bundle 타겟을 자동으로 구성합니다:
pnpm nx bundle <project-name>yarn nx bundle <project-name>npx nx bundle <project-name>bunx nx bundle <project-name>Rolldown 구성은 rolldown.config.ts에서 찾을 수 있으며, 생성할 번들마다 항목이 있습니다. Rolldown은 정의된 경우 여러 번들을 병렬로 생성하는 것을 관리합니다.
번들 타겟은 Bedrock AgentCore Runtime에서 호스팅할 WebSocket 서버의 엔트리포인트로 index.ts를 사용합니다.
Docker 타겟
섹션 제목: “Docker 타겟”생성기는 에이전트 소스 디렉토리에서 번들 출력 디렉토리로 Dockerfile을 복사하는 <your-agent-name>-docker 타겟을 구성합니다. 이는 Dockerfile을 번들된 아티팩트와 함께 배치하여 CDK가 AgentRuntimeArtifact.fromAsset을 사용하여 Docker 이미지를 직접 빌드할 수 있도록 합니다.
여러 에이전트가 정의된 경우 모든 에이전트에 대한 docker 컨텍스트를 준비하는 docker 타겟도 생성됩니다.
이미지 스캔
섹션 제목: “이미지 스캔”이 프로젝트를 위해 빌드된 Docker 이미지는 ECR 호스팅 Trivy 이미지에서 실행되는 Trivy를 사용하여 취약점을 스캔할 수 있습니다.
trivy 타겟이 프로젝트에 추가되어 빌드된 이미지를 스캔하고 HIGH 또는 CRITICAL 심각도의 취약점이 발견되면 0이 아닌 값으로 종료합니다. 생성된 Dockerfile은 생성 시점에 이러한 심각도의 알려진 수정 가능한 취약점이 없는 베이스 이미지를 사용하며, 번들된 도구(예: npm)를 업그레이드하여 이를 유지합니다.
스캔은 이미지 빌드와 동일한 컨테이너 엔진(docker 또는 finch)을 사용하므로 추가 도구가 필요하지 않습니다. 스캔은 이미지가 변경될 때만 다시 실행되므로 변경되지 않은 이미지는 다시 스캔되지 않습니다. 제공되는 trivy 루트 스크립트는 워크스페이스의 모든 이미지를 스캔합니다:
pnpm trivyyarn trivynpm run trivybun trivyTrivy 결과 억제
섹션 제목: “Trivy 결과 억제”특정 취약점을 억제하고 싶은 경우가 있을 수 있습니다. 예를 들어 아직 수정 사항이 없고 위험을 허용 가능한 것으로 평가한 경우입니다.
프로젝트 루트의 .trivyignore 파일(즉, project.json 옆)에 취약점 ID를 한 줄에 하나씩 추가하세요:
# node-tar arbitrary file write - not exploitable in our usageCVE-2024-XXXXX결과 필터링에 대한 자세한 내용은 Trivy 필터링 문서를 참조하세요.
관찰성
섹션 제목: “관찰성”에이전트는 Dockerfile에서 자동 계측을 구성하여 AWS Distro for Open Telemetry (ADOT)를 사용한 관찰성으로 자동 구성됩니다.
CloudWatch AWS 콘솔에서 메뉴의 “GenAI Observability”를 선택하여 추적을 찾을 수 있습니다. 추적이 채워지려면 Transaction Search를 활성화해야 합니다.
자세한 내용은 관찰성에 대한 AgentCore 문서를 참조하세요.
세션 관리
섹션 제목: “세션 관리”session 옵션은 Strands SDK의 SessionManager를 사용하여 에이전트가 호출 간에 대화 상태(메시지 기록, 도구 상태 등)를 유지하는 방법을 제어합니다:
s3(기본값): CDK/Terraform 인프라는 전용 KMS 키로 암호화되고 모든 공개 액세스가 차단된 세션 데이터용 전용 S3 버킷을 프로비저닝합니다. 서버 액세스 로그는 동일한 키를 통해 CloudWatch Logs 로그 그룹으로 전달됩니다. 에이전트의 IAM 역할에는 버킷에 대한 읽기/쓰기/목록/삭제 액세스 권한과 키에 대한 복호화/데이터 키 생성 액세스 권한이 부여되며, 버킷 이름은 AppConfig 런타임 구성에서 에이전트의 ARN과 함께 등록됩니다.in-memory: 버킷이 프로비저닝되지 않습니다. 대화 상태는 실행 중인 프로세스의 수명 동안만 메모리에 유지되며 재시작이나 스케일 인에서 살아남지 못합니다.
이는 생성된 session.ts에 구현되어 있으며, 현재 세션에 대한 SessionManager를 확인하는 getSessionManager() 함수를 내보냅니다.
세션 ID 자체는 AgentCore Runtime 세션에서 가져오며(A2A/AG-UI의 경우 x-amzn-bedrock-agentcore-runtime-session-id 헤더를 통해, HTTP/tRPC의 경우 WebSocket 연결 컨텍스트를 통해 전파됨) AsyncLocalStorage 기반 컨텍스트에 바인딩되어 getCurrentSessionId()가 요청의 어디에서나 이를 확인할 수 있습니다. 여기에는 connection 생성기를 통해 연결된 다운스트림 MCP 또는 A2A 클라이언트도 포함되므로 전체 호출 체인이 일관된 세션을 공유합니다.
Agent 호출
섹션 제목: “Agent 호출”에이전트 통신은 WebSocket을 통한 tRPC를 통해 전송됩니다. 따라서 client.ts에서 생성된 타입 안전 클라이언트 팩토리를 사용하는 것이 좋습니다.
로컬 서버 호출
섹션 제목: “로컬 서버 호출”클라이언트 팩토리의 .local 팩토리 메서드를 사용하여 로컬에서 실행 중인 에이전트를 호출할 수 있습니다.
예를 들어 작업 공간에 클라이언트를 가져오는 scripts/test.ts라는 파일을 생성할 수 있습니다:
import { AgentClient } from '../packages/<project>/src/agent/client.js';
const client = AgentClient.local({ url: 'http://localhost:8081/ws' });
client.invoke.subscribe({ prompt: 'what is 1 plus 1?' }, { onData: console.log });배포된 Agent 호출
섹션 제목: “배포된 Agent 호출”Bedrock AgentCore Runtime에 배포된 Agent를 호출하려면 URL 인코딩된 런타임 ARN과 함께 Bedrock AgentCore Runtime 데이터플레인 엔드포인트로 POST 요청을 보낼 수 있습니다.
다음과 같이 인프라에서 런타임 ARN을 얻을 수 있습니다:
import { CfnOutput } from 'aws-cdk-lib';import { MyProjectAgent } from '@my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { const agent = new MyProjectAgent(this, 'MyProjectAgent');
new CfnOutput(this, 'AgentArn', { value: agent.agentCoreRuntime.agentRuntimeArn, }); }}# Agentmodule "my_project_agent" { # Relative path to the generated module in the common/terraform project source = "../../common/terraform/src/app/agents/my-project-agent"
appconfig_application_id = module.runtime_config_appconfig.application_id appconfig_application_arn = module.runtime_config_appconfig.application_arn}
output "agent_arn" { value = module.my_project_agent.agent_core_runtime_arn}ARN은 다음 형식을 갖습니다: arn:aws:bedrock-agentcore:<region>:<account>:runtime/<agent-runtime-id>.
그런 다음 :를 %3A로, /를 %2F로 바꿔서 ARN을 URL 인코딩할 수 있습니다.
에이전트를 호출하기 위한 Bedrock AgentCore Runtime 데이터플레인 URL은 다음과 같습니다:
https://bedrock-agentcore.<region>.amazonaws.com/runtimes/<url-encoded-arn>/invocations이 URL을 호출하는 정확한 방법은 사용된 인증 방법에 따라 다릅니다.
NodeJS
섹션 제목: “NodeJS”생성된 client.ts 파일에는 배포된 에이전트를 호출하는 데 사용할 수 있는 타입 안전 클라이언트 팩토리가 포함되어 있습니다.
IAM 인증
섹션 제목: “IAM 인증”withIamAuth 팩토리 메서드에 ARN을 전달하여 배포된 에이전트를 호출할 수 있습니다:
import { AgentClient } from './agent/client.js';
const client = AgentClient.withIamAuth({ agentRuntimeArn: 'arn:aws:bedrock-agentcore:us-west-2:123456789012:runtime/my-agent',});
client.invoke.subscribe({ prompt: 'what is 1 plus 1?' }, { onData: (message) => console.log(message), onError: (error) => console.error(error), onComplete: () => console.log('Done'),});JWT / Cognito 인증
섹션 제목: “JWT / Cognito 인증”JWT / Cognito 액세스 토큰으로 인증하려면 withJwtAuth 팩토리 메서드를 사용하세요.
const client = AgentClient.withJwtAuth({ agentRuntimeArn: 'arn:aws:bedrock-agentcore:us-west-2:123456789012:runtime/my-agent', accessTokenProvider: async () => `<access-token>`,});
client.invoke.subscribe({ prompt: 'what is 1 plus 1?' }, { onData: console.log,});accessTokenProvider는 요청을 인증하는 데 사용되는 토큰을 반환해야 합니다. 예를 들어 tRPC가 WebSocket 연결을 재시작할 때 새 자격 증명이 재사용되도록 이 메서드 내에서 토큰을 얻을 수 있습니다. 아래는 AWS SDK를 사용하여 Cognito에서 토큰을 얻는 방법을 보여줍니다:
import { CognitoIdentityProvider } from "@aws-sdk/client-cognito-identity-provider";
const cognito = new CognitoIdentityProvider();
const jwtClient = AgentClient.withJwtAuth({ agentRuntimeArn: 'arn:aws:bedrock-agentcore:us-west-2:123456789012:runtime/my-agent', accessTokenProvider: async () => { const response = await cognito.adminInitiateAuth({ UserPoolId: '<user-pool-id>', ClientId: '<user-pool-client-id>', AuthFlow: 'ADMIN_NO_SRP_AUTH', AuthParameters: { USERNAME: '<username>', PASSWORD: '<password>', }, }); return response.AuthenticationResult!.AccessToken!; },});브라우저 / React 웹사이트
섹션 제목: “브라우저 / React 웹사이트”React 웹사이트에서 Agent를 호출하려면 올바른 인증(IAM 또는 Cognito)으로 tRPC WebSocket 클라이언트를 자동으로 설정하는 connection 생성기를 활용할 수 있습니다.
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- 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
- VSCode에서 Nx 콘솔 열기
- 클릭
Generate (UI)"Common Nx Commands" 섹션에서 - 검색
@aws/nx-plugin - connection - 필수 매개변수 입력
- 클릭
Generate
연결 설정 방법에 대한 자세한 내용은 connection 생성기 가이드를 참조하세요.
A2A Agent를 도구로 호출
섹션 제목: “A2A Agent를 도구로 호출”이 에이전트에서 원격 A2A 에이전트(TypeScript 또는 Python)로 작업을 위임하려면 connection 생성기를 사용하세요. 대상 에이전트에 대한 SigV4 인증 클라이언트를 제공하고 이 에이전트의 agent.ts를 AST 변환하여 원격 A2A 에이전트를 Strands tool로 등록합니다.
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- 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
- VSCode에서 Nx 콘솔 열기
- 클릭
Generate (UI)"Common Nx Commands" 섹션에서 - 검색
@aws/nx-plugin - connection - 필수 매개변수 입력
- 클릭
Generate
연결 설정 방법에 대한 자세한 내용은 connection 생성기 가이드를 참조하세요.
AG-UI Agent 호출
섹션 제목: “AG-UI Agent 호출”React 웹사이트에서 AG-UI 에이전트를 호출하려면 올바른 인증(IAM 또는 Cognito)으로 배포된 에이전트에 대해 구성된 CopilotKit 클라이언트를 연결하는 connection 생성기를 사용하세요.
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- 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
- VSCode에서 Nx 콘솔 열기
- 클릭
Generate (UI)"Common Nx Commands" 섹션에서 - 검색
@aws/nx-plugin - connection - 필수 매개변수 입력
- 클릭
Generate
연결 설정 방법에 대한 자세한 내용은 connection 생성기 가이드를 참조하세요.
Agent 보안
섹션 제목: “Agent 보안”에이전트는 신뢰할 수 없는 입력에 대해 작동하며 도구를 통해 실제 작업을 수행할 수 있으므로, 처음부터 보안을 고려할 가치가 있습니다. 다음 관행은 생성된 에이전트에 적용됩니다.
모델 입력 및 출력을 신뢰할 수 없는 것으로 취급
섹션 제목: “모델 입력 및 출력을 신뢰할 수 없는 것으로 취급”프롬프트에는 적대적인 지시사항(프롬프트 인젝션)이 포함될 수 있으며, 모델 출력은 비결정적입니다. 따라서 보안에 민감한 로직에서 둘 다 신뢰해서는 안 됩니다:
- 생성된 예제 도구와 같이 도구에 대해 엄격한 입력 스키마를 정의하세요. 자유 형식 문자열을 허용하는 대신 도구가 실제로 필요로 하는 값(열거형, 길이 제한, 숫자 범위)으로 제한하세요.
- 모델 출력을 검증이나 인코딩 없이 셸 명령, SQL 쿼리, 코드 평가 또는 렌더링된 HTML에 직접 전달하지 마세요.
- 도구 및 다운스트림 서비스에 권한 부여 검사를 적용하세요. 모델이 액세스 권한이 있는 도구를 오용하지 못하도록 시스템 프롬프트에만 의존하지 마세요.
Strands의 Prompt Engineering 및 Responsible AI 가이드는 견고하고 안전을 고려한 시스템 프롬프트 작성을 다룹니다.
도구 권한을 엄격하게 범위 지정
섹션 제목: “도구 권한을 엄격하게 범위 지정”에이전트의 IAM 역할에 도구가 필요로 하는 권한만 부여하세요. 제공되는 CDK 구성 요소 및 Terraform 모듈은 이러한 목적을 위해 grant* 메서드와 범위가 지정된 정책을 노출합니다. 예를 들어 광범위한 관리형 정책을 연결하는 대신 특정 API를 호출할 수 있는 액세스 권한을 에이전트에 부여합니다. 도구가 사용자를 대신하여 작동하는 경우, 에이전트 자체의 앰비언트 권한보다 호출하는 사용자의 ID(요청 컨텍스트를 통해 전달됨)를 사용하여 작업을 승인하는 것을 선호하세요.
킬 스위치 제공
섹션 제목: “킬 스위치 제공”모델 동작이 예상치 못한 방식으로 변경될 수 있으므로, 코드 변경 없이 모델을 신속하게 비활성화하거나 교체할 수 있도록 계획하세요:
- 운영자가 구성을 업데이트하여 다른 모델로 전환하거나 롤백할 수 있도록 구성에서 모델 ID를 읽으세요(예:
MODEL_ID환경 변수). - AI 기능을 완전히 비활성화할 수 있도록 기능 플래그 뒤에 에이전트를 배치하세요. 비활성화된 경우 오류 대신 일반 메시지를 반환하고, 애플리케이션의 나머지 부분이 정상적으로 저하되도록 하세요.
운영 런북에 이러한 제어를 전환하는 방법을 문서화하세요.
민감한 데이터 보호
섹션 제목: “민감한 데이터 보호”- 사용자 데이터가 포함될 수 있는 프롬프트 및 완료를 로깅하지 마세요. 생성된 에이전트의 모델 오류 로깅 후크는 대화 내용이 아닌 오류 메타데이터만 로깅합니다. 자체 로깅을 추가할 때 이 속성을 유지하세요.
- 사용자에게 일반적인 오류 메시지를 반환하고, 상세한 오류는 서버 측에서 로깅하세요.
- 사용자와 세션 간에 대화 상태를 격리하고, 지속된 세션 데이터에 대한 액세스를 승인하세요.
- 프롬프트 및 출력에서 개인 식별 정보(PII)를 수정하세요. Bedrock Guardrail 민감한 정보 필터(아래 참조) 또는 Strands 에이전트의 경우 PII Redaction 가이드의 접근 방식을 사용하세요.
Amazon Bedrock Guardrails
섹션 제목: “Amazon Bedrock Guardrails”Amazon Bedrock Guardrails는 모델 입력 및 출력에서 평가되는 구성 가능한 콘텐츠 필터, 거부된 주제 및 민감한 정보(PII) 필터를 제공합니다. 생성된 에이전트가 사용하는 모델에 가드레일을 연결할 수 있습니다:
import { Agent } from '@strands-agents/sdk';import { BedrockModel } from '@strands-agents/sdk/models/bedrock';
const model = new BedrockModel({ modelId: process.env.MODEL_ID, guardrailConfig: { guardrailIdentifier: process.env.GUARDRAIL_ID!, guardrailVersion: process.env.GUARDRAIL_VERSION ?? 'DRAFT', },});
const agent = new Agent({ model, /* ... */ });자세한 내용은 Strands Guardrails 가이드를 참조하세요.
connection 생성기를 사용하여 이 프로젝트를 작업 공간의 다른 프로젝트와 통합하세요. 다음 연결은 이 프로젝트와 관련됩니다:
