> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ko/llms.txt # Amazon Bedrock AgentCore에 Mastra 배포 [AgentCore CLI](https://github.com/aws/agentcore-cli)를 사용하여 Mastra 애플리케이션을 [Amazon Bedrock AgentCore Runtime](https://docs.aws.amazon.com/bedrock-agentcore/)에 배포하세요. CLI는 BYO(Bring-Your-Own-Code) TypeScript 프로젝트를 스캐폴딩하고, AWS CodeBuild를 사용해 컨테이너를 빌드하며, 런타임을 프로비저닝합니다. 배포 시 로컬 Docker 데몬은 필요하지 않습니다. 이 가이드는 [공식 AgentCore TypeScript 가이드](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-get-started-cli-typescript.html)를 바탕으로, 호출 핸들러에서 Mastra Agent를 호출하도록 조정했습니다. > **정보:** 전체 Mastra 서버를 Lambda 기반으로 배포하는 방법은 [AWS Lambda 가이드](https://mastra.zisheng.pro/ko/guides/deployment/aws-lambda)를 참조하세요. 장기 실행 가상 머신을 사용하려면 [Amazon EC2 가이드](https://mastra.zisheng.pro/ko/guides/deployment/amazon-ec2)를 참조하세요. ## 시작하기 전에 다음이 필요합니다. - Amazon Bedrock AgentCore, AWS CodeBuild, Amazon ECR, AWS IAM에 대한 권한이 있는 [AWS 계정](https://aws.amazon.com/) - 설치 및 인증된 [AWS CLI](https://aws.amazon.com/cli/)(`aws configure` 또는 `aws sso login`) - Node.js `v22.13.0` 이상 - `agentcore dev`를 사용한 로컬 테스트용 [Docker](https://www.docker.com/), [Podman](https://podman.io/) 또는 [Finch](https://runfinch.com/)(`agentcore deploy`에는 필요하지 않음) Amazon Bedrock AgentCore Runtime은 [일부 AWS 리전](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/agentcore-regions.html)에서 사용할 수 있습니다. AgentCore를 사용할 수 있고 호출하려는 기반 Model이 활성화된 리전을 사용하세요. ## 새 AgentCore 프로젝트 만들기 다음 명령을 실행하여 새 AgentCore 프로젝트를 만듭니다. **npm**: ```bash npx @aws/agentcore create --name MastraOnAgentCore --no-agent ``` **pnpm**: ```bash pnpm dlx @aws/agentcore create --name MastraOnAgentCore --no-agent ``` **Yarn**: ```bash yarn dlx @aws/agentcore create --name MastraOnAgentCore --no-agent ``` **Bun**: ```bash bun x @aws/agentcore create --name MastraOnAgentCore --no-agent ``` 새로 생성된 항목으로 이동합니다.`MastraOnAgentCore` directory: ```bash cd MastraOnAgentCore ``` 내부에 생성될 BYO TypeScript Agent를 초기화합니다.`app/MastraAgent`: **npm**: ```bash npx @aws/agentcore add agent --name MastraAgent --type byo --build Container --language TypeScript --framework Strands --model-provider Bedrock --code-location app/MastraAgent ``` **pnpm**: ```bash pnpm dlx @aws/agentcore add agent --name MastraAgent --type byo --build Container --language TypeScript --framework Strands --model-provider Bedrock --code-location app/MastraAgent ``` **Yarn**: ```bash yarn dlx @aws/agentcore add agent --name MastraAgent --type byo --build Container --language TypeScript --framework Strands --model-provider Bedrock --code-location app/MastraAgent ``` **Bun**: ```bash bun x @aws/agentcore add agent --name MastraAgent --type byo --build Container --language TypeScript --framework Strands --model-provider Bedrock --code-location app/MastraAgent ``` CLI는 `agentcore/agentcore.json` 파일을 수정하고 빈 `app/MastraAgent` 디렉터리를 생성합니다. ## Agent 프로젝트 설정 `app/MastraAgent` 디렉터리로 이동하여 새 Node.js 프로젝트를 초기화하세요. ```bash cd app/MastraAgent npm init --init-type=module -y ``` 필요한 종속성을 설치하세요. `bedrock-agentcore` 패키지는 [AgentCore Runtime 서비스 계약](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-service-contract.html)을 구현하는 `BedrockAgentCoreApp` HTTP 서버를 제공합니다. `@ai-sdk/amazon-bedrock` 및 `@aws-sdk/credential-providers` 패키지를 사용하면 Mastra Agent가 AgentCore Runtime 실행 역할을 통해 Bedrock을 호출할 수 있습니다. **npm**: ```bash npm install bedrock-agentcore @opentelemetry/auto-instrumentations-node @ai-sdk/amazon-bedrock @aws-sdk/credential-providers --legacy-peer-deps ``` **pnpm**: ```bash pnpm add bedrock-agentcore @opentelemetry/auto-instrumentations-node @ai-sdk/amazon-bedrock @aws-sdk/credential-providers --legacy-peer-deps ``` **Yarn**: ```bash yarn add bedrock-agentcore @opentelemetry/auto-instrumentations-node @ai-sdk/amazon-bedrock @aws-sdk/credential-providers --legacy-peer-deps ``` **Bun**: ```bash bun add bedrock-agentcore @opentelemetry/auto-instrumentations-node @ai-sdk/amazon-bedrock @aws-sdk/credential-providers --legacy-peer-deps ``` 또한 TypeScript 및 관련 개발 종속성을 설치합니다. **npm**: ```bash npm install --save-dev typescript @types/node tsx ``` **pnpm**: ```bash pnpm add --save-dev typescript @types/node tsx ``` **Yarn**: ```bash yarn add --dev typescript @types/node tsx ``` **Bun**: ```bash bun add --dev typescript @types/node tsx ``` [`mastra init`](https://mastra.zisheng.pro/ko/reference/cli/mastra)을 실행하여 새 Mastra 프로젝트를 설정하세요. Prompt에서 선택한 Provider는 다음 단계에서 덮어쓰므로 어떤 값을 선택해도 됩니다. **npm**: ```bash npx mastra@latest init ``` **pnpm**: ```bash pnpm dlx mastra@latest init ``` **Yarn**: ```bash yarn dlx mastra@latest init ``` **Bun**: ```bash bun x mastra@latest init ``` 생성된 `src/mastra/agents/weather-agent.ts`를 교체하여 Amazon Bedrock을 사용하도록 하세요. 다음 단계에서 스토리지 계층을 제거하므로 기존의 `memory: new Memory()`도 제거합니다. ```ts import { Agent } from '@mastra/core/agent' import { createAmazonBedrock } from '@ai-sdk/amazon-bedrock' import { fromNodeProviderChain } from '@aws-sdk/credential-providers' import { weatherTool } from '../tools/weather-tool.js' const bedrock = createAmazonBedrock({ credentialProvider: fromNodeProviderChain(), }) export const weatherAgent = new Agent({ id: 'weather-agent', name: 'Weather Agent', instructions: 'You are a helpful weather assistant. Use the weatherTool to fetch current weather data.', model: bedrock('us.anthropic.claude-sonnet-4-6'), tools: { weatherTool }, }) ``` > **노트:** `fromNodeProviderChain()`Agent가 환경 변수만 대신 표준 SDK 확인 체인(환경 변수, 공유 구성 파일, SSO, 컨테이너 또는 EC2 역할)을 통해 AWS 자격 증명을 선택할 수 있습니다. 생성된 `src/mastra/index.ts`를 교체하여 기본 파일 기반 스토리지와 Observability 구성을 제거하세요. AgentCore Runtime 컨테이너는 읽기 전용 애플리케이션 디렉터리에서 루트가 아닌 사용자로 실행되므로 기본 `LibSQLStore`가 `./mastra.db`를 열 수 없으며 런타임 시작에 실패합니다. ```ts import { Mastra } from '@mastra/core/mastra' import { PinoLogger } from '@mastra/loggers' import { weatherWorkflow } from './workflows/weather-workflow.js' import { weatherAgent } from './agents/weather-agent.js' export const mastra = new Mastra({ workflows: { weatherWorkflow }, agents: { weatherAgent }, logger: new PinoLogger({ name: 'Mastra', level: 'info', }), }) ``` 다음 내용으로 `tsconfig.json` 파일을 생성하세요. ```json { "compilerOptions": { "outDir": "./dist", "rootDir": ".", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "declaration": true, "target": "ES2022", "module": "NodeNext", "moduleResolution": "NodeNext", "forceConsistentCasingInFileNames": true }, "include": ["*.ts", "src/**/*"], "exclude": ["node_modules", "dist"] } ``` > **노트:** `tsconfig.json` 파일을 추가하면 편집기에서 생성된 `src/mastra` 프로젝트 내부에 오류가 표시됩니다. 이제 구성에서 import에 파일 확장자를 요구하므로 예상되는 현상입니다. 다음 예와 같이 `.js`를 추가하여 해결할 수 있습니다. > > ```ts > // Before > import { weatherWorkflow } from './workflows/weather-workflow' > // After > import { weatherWorkflow } from './workflows/weather-workflow.js' > ``` 진입점과 빌드 스크립트를 설정하도록 `package.json`을 업데이트하세요. `npm pkg set`을 사용하면 `mastra init`이 추가한 종속성을 유지할 수 있습니다. ```bash npm pkg set main=dist/agent.js scripts.build=tsc scripts.start="node dist/agent.js" scripts.dev="npx tsx --watch agent.ts" ``` ## Agent 초기화 `agent.ts` 파일을 생성하세요. 이 핸들러는 모든 `POST /invocations` 요청에 대해 호출됩니다. 핸들러 안에서 Mastra Agent를 가져와 호출하세요. ```ts import { BedrockAgentCoreApp } from 'bedrock-agentcore/runtime' import { mastra } from './src/mastra/index.js' const app = new BedrockAgentCoreApp({ invocationHandler: { process: async (payload, context) => { const { prompt } = payload as { prompt: string } const agent = mastra.getAgentById('weather-agent') const response = await agent.generate(prompt, { runId: context.sessionId, }) return response.text }, }, }) app.run() ``` `npm run build`를 실행하여 프로젝트가 성공적으로 컴파일되는지 확인하세요. ## Dockerfile 만들기 `app/MastraAgent` 디렉터리에 `Dockerfile`을 생성하세요. 컨테이너 기반 배포에서는 다단계 Docker 빌드를 사용합니다. 빌더 단계에서는 TypeScript를 JavaScript로 컴파일하고, 프로덕션 단계에서는 컴파일된 출력만 실행합니다. 보안을 위해 이미지는 루트가 아닌 사용자로 실행되며 포트 8080(HTTP), 포트 8000(MCP), 포트 9000(A2A)을 노출합니다. OpenTelemetry 계측은 시작 시 자동으로 포함됩니다. ```dockerfile FROM node:22-slim AS builder WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . RUN npm run build FROM node:22-slim WORKDIR /app ENV AWS_REGION=us-east-1 COPY --from=builder /app/dist ./dist COPY --from=builder /app/node_modules ./node_modules COPY --from=builder /app/package*.json ./ RUN useradd -m bedrock_agentcore USER bedrock_agentcore EXPOSE 8080 8000 9000 CMD ["node", "--require", "@opentelemetry/auto-instrumentations-node/register", "dist/agent.js"] ``` > **노트:** Bedrock Model ID 접두사(`us.`, `jp.`, `eu.` 또는 `global.`)와 일치하는 `AWS_REGION`을 선택하세요. Docker 빌드 컨텍스트에서 불필요한 파일을 제외하도록 `.dockerignore` 파일도 생성하세요. ```bash node_modules dist .git *.log ``` ## Agent 테스트 프로젝트 루트로 돌아가기: ```bash cd ../.. ``` Agent를 로컬에서 테스트합니다. **npm**: ```bash npx @aws/agentcore dev --runtime MastraAgent ``` **pnpm**: ```bash pnpm dlx @aws/agentcore dev --runtime MastraAgent ``` **Yarn**: ```bash yarn dlx @aws/agentcore dev --runtime MastraAgent ``` **Bun**: ```bash bun x @aws/agentcore dev --runtime MastraAgent ``` 별도의 터미널에서 테스트 요청을 보냅니다. **npm**: ```bash npx @aws/agentcore dev "What is the weather in Tokyo?" ``` **pnpm**: ```bash pnpm dlx @aws/agentcore dev "What is the weather in Tokyo?" ``` **Yarn**: ```bash yarn dlx @aws/agentcore dev "What is the weather in Tokyo?" ``` **Bun**: ```bash bun x @aws/agentcore dev "What is the weather in Tokyo?" ``` ## Agent 배포 AWS 계정과 지역을 설정하세요.`agentcore/aws-targets.json`: ```json [ { "name": "default", "account": "123456789012", "region": "us-east-1" } ] ``` AgentCore 런타임에 배포합니다. CLI는 AWS CodeBuild를 사용하여 이미지를 빌드하고 이를 Amazon ECR에 푸시한 다음 런타임과`DEFAULT` endpoint: **npm**: ```bash npx @aws/agentcore deploy ``` **pnpm**: ```bash pnpm dlx @aws/agentcore deploy ``` **Yarn**: ```bash yarn dlx @aws/agentcore deploy ``` **Bun**: ```bash bun x @aws/agentcore deploy ``` > **노트:** 배포하기 전에 Provider API 키와 기타 비밀 값을 `agentcore/agentcore.json`에 있는 Agent의 `environmentVariables` 필드에 설정하세요. ## 배포 확인 `agentcore status`를 실행하여 런타임 ARN, 엔드포인트 및 최근 호출을 확인하세요. 그런 다음 CLI에서 배포된 Agent를 호출하세요. ```bash npx @aws/agentcore invoke "What is the weather in Tokyo?" ``` 토큰이 생성될 때 스트리밍하려면 다음을 사용하세요.`--stream`: ```bash npx @aws/agentcore invoke --stream "Plan a 3-day trip to Tokyo" ``` ## 관련된 - [Amazon Bedrock AgentCore 문서](https://docs.aws.amazon.com/bedrock-agentcore/) - [GitHub의 AgentCore CLI](https://github.com/aws/agentcore-cli)