본문으로 건너뛰기

Amazon Bedrock AgentCore에 Mastra 배포

AgentCore CLI를 사용하여 Mastra 애플리케이션을 Amazon Bedrock AgentCore Runtime에 배포하세요. CLI는 BYO(Bring-Your-Own-Code) TypeScript 프로젝트를 스캐폴딩하고, AWS CodeBuild를 사용해 컨테이너를 빌드하며, 런타임을 프로비저닝합니다. 배포 시 로컬 Docker 데몬은 필요하지 않습니다. 이 가이드는 공식 AgentCore TypeScript 가이드를 바탕으로, 호출 핸들러에서 Mastra Agent를 호출하도록 조정했습니다.

정보

전체 Mastra 서버를 Lambda 기반으로 배포하는 방법은 AWS Lambda 가이드를 참조하세요. 장기 실행 가상 머신을 사용하려면 Amazon EC2 가이드를 참조하세요.

시작하기 전에
시작하기 전에에 대한 직접 링크

다음이 필요합니다.

  • Amazon Bedrock AgentCore, AWS CodeBuild, Amazon ECR, AWS IAM에 대한 권한이 있는 AWS 계정
  • 설치 및 인증된 AWS CLI(aws configure 또는 aws sso login)
  • Node.js v22.13.0 이상
  • agentcore dev를 사용한 로컬 테스트용 Docker, Podman 또는 Finch(agentcore deploy에는 필요하지 않음) Amazon Bedrock AgentCore Runtime은 일부 AWS 리전에서 사용할 수 있습니다. AgentCore를 사용할 수 있고 호출하려는 기반 Model이 활성화된 리전을 사용하세요.

새 AgentCore 프로젝트 만들기
새 AgentCore 프로젝트 만들기에 대한 직접 링크

다음 명령을 실행하여 새 AgentCore 프로젝트를 만듭니다.

npx @aws/agentcore create --name MastraOnAgentCore --no-agent

새로 생성된 항목으로 이동합니다.MastraOnAgentCore directory:

cd MastraOnAgentCore

내부에 생성될 BYO TypeScript Agent를 초기화합니다.app/MastraAgent:

npx @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 프로젝트 설정
Agent 프로젝트 설정에 대한 직접 링크

app/MastraAgent 디렉터리로 이동하여 새 Node.js 프로젝트를 초기화하세요.

cd app/MastraAgent
npm init --init-type=module -y

필요한 종속성을 설치하세요. bedrock-agentcore 패키지는 AgentCore Runtime 서비스 계약을 구현하는 BedrockAgentCoreApp HTTP 서버를 제공합니다. @ai-sdk/amazon-bedrock@aws-sdk/credential-providers 패키지를 사용하면 Mastra Agent가 AgentCore Runtime 실행 역할을 통해 Bedrock을 호출할 수 있습니다.

npm install bedrock-agentcore @opentelemetry/auto-instrumentations-node @ai-sdk/amazon-bedrock @aws-sdk/credential-providers --legacy-peer-deps

또한 TypeScript 및 관련 개발 종속성을 설치합니다.

npm install --save-dev typescript @types/node tsx

mastra init을 실행하여 새 Mastra 프로젝트를 설정하세요. Prompt에서 선택한 Provider는 다음 단계에서 덮어쓰므로 어떤 값을 선택해도 됩니다.

npx mastra@latest init

생성된 src/mastra/agents/weather-agent.ts를 교체하여 Amazon Bedrock을 사용하도록 하세요. 다음 단계에서 스토리지 계층을 제거하므로 기존의 memory: new Memory()도 제거합니다.

app/MastraAgent/src/mastra/agents/weather-agent.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를 열 수 없으며 런타임 시작에 실패합니다.

app/MastraAgent/src/mastra/index.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 파일을 생성하세요.

app/MastraAgent/tsconfig.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를 추가하여 해결할 수 있습니다.

app/MastraAgent/src/mastra/index.ts
// Before
import { weatherWorkflow } from './workflows/weather-workflow'
// After
import { weatherWorkflow } from './workflows/weather-workflow.js'

진입점과 빌드 스크립트를 설정하도록 package.json을 업데이트하세요. npm pkg set을 사용하면 mastra init이 추가한 종속성을 유지할 수 있습니다.

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 초기화에 대한 직접 링크

agent.ts 파일을 생성하세요. 이 핸들러는 모든 POST /invocations 요청에 대해 호출됩니다. 핸들러 안에서 Mastra Agent를 가져와 호출하세요.

app/MastraAgent/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 만들기
Dockerfile 만들기에 대한 직접 링크

app/MastraAgent 디렉터리에 Dockerfile을 생성하세요. 컨테이너 기반 배포에서는 다단계 Docker 빌드를 사용합니다. 빌더 단계에서는 TypeScript를 JavaScript로 컴파일하고, 프로덕션 단계에서는 컴파일된 출력만 실행합니다. 보안을 위해 이미지는 루트가 아닌 사용자로 실행되며 포트 8080(HTTP), 포트 8000(MCP), 포트 9000(A2A)을 노출합니다. OpenTelemetry 계측은 시작 시 자동으로 포함됩니다.

app/MastraAgent/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 파일도 생성하세요.

node_modules
dist
.git
*.log

Agent 테스트
Agent 테스트에 대한 직접 링크

프로젝트 루트로 돌아가기:

cd ../..

Agent를 로컬에서 테스트합니다.

npx @aws/agentcore dev --runtime MastraAgent

별도의 터미널에서 테스트 요청을 보냅니다.

npx @aws/agentcore dev "What is the weather in Tokyo?"

Agent 배포
Agent 배포에 대한 직접 링크

AWS 계정과 지역을 설정하세요.agentcore/aws-targets.json:

agentcore/aws-targets.json
[
{
"name": "default",
"account": "123456789012",
"region": "us-east-1"
}
]

AgentCore 런타임에 배포합니다. CLI는 AWS CodeBuild를 사용하여 이미지를 빌드하고 이를 Amazon ECR에 푸시한 다음 런타임과DEFAULT endpoint:

npx @aws/agentcore deploy
노트

배포하기 전에 Provider API 키와 기타 비밀 값을 agentcore/agentcore.json에 있는 Agent의 environmentVariables 필드에 설정하세요.

배포 확인
배포 확인에 대한 직접 링크

agentcore status를 실행하여 런타임 ARN, 엔드포인트 및 최근 호출을 확인하세요. 그런 다음 CLI에서 배포된 Agent를 호출하세요.

npx @aws/agentcore invoke "What is the weather in Tokyo?"

토큰이 생성될 때 스트리밍하려면 다음을 사용하세요.--stream:

npx @aws/agentcore invoke --stream "Plan a 3-day trip to Tokyo"