跳至主要內容

將 Mastra 部署至 Amazon Bedrock AgentCore

使用 AgentCore CLI,將你的 Mastra 應用程式部署至 Amazon Bedrock AgentCore Runtime。CLI 會建立自備程式碼(BYO)TypeScript 項目的基本結構、使用 AWS CodeBuild 建置容器,並佈建 Runtime。部署時無需本機 Docker 背景程序。

本指南依照官方 AgentCore TypeScript 逐步指南,並作出調整,以便從調用處理程式呼叫 Mastra Agent。

資訊

如要以 Lambda 部署完整的 Mastra 伺服器,請參閱 AWS Lambda 指南。如要使用長時間運行的虛擬機器,請參閱 Amazon EC2 指南

開始之前
開始之前 的直接連結

你需要:

  • 一個具有 Amazon Bedrock AgentCore、AWS CodeBuild、Amazon ECR 和 AWS IAM 權限的 AWS 帳戶
  • 已安裝並完成驗證的 AWS CLIaws configureaws sso login
  • 已安裝 Node.js v22.13.0 或以上版本
  • 用於透過 agentcore dev 進行本機測試的 DockerPodmanFinchagentcore deploy 並不需要)

Amazon Bedrock AgentCore Runtime 只在部分 AWS 區域提供。請使用 AgentCore 可用,而且已啟用你計劃呼叫的基礎模型之區域。

建立新的 AgentCore 項目
建立新的 AgentCore 項目 的直接連結

運行以下命令以建立新的 AgentCore 項目:

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

前往新建立的 MastraOnAgentCore 目錄:

cd MastraOnAgentCore

初始化將在 app/MastraAgent 內建立的 BYO TypeScript Agent:

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 項目。系統會在下一步覆寫你在提示中選擇的 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,以移除預設的檔案式儲存和可觀測性設定。AgentCore Runtime 容器會以非 root 使用者身分運行,而應用程式目錄為唯讀,因此預設的 LibSQLStore 無法開啟 ./mastra.db,導致 Runtime 啟動失敗:

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,而生產階段只運行編譯後的輸出。映像檔會以非 root 使用者身分運行以提高安全性,並開放連接埠 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 模型 ID 前綴(us.jp.eu.global.)相配的 AWS_REGION

另請建立 .dockerignore 檔案,從 Docker 建置內容中排除不必要的檔案:

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 的直接連結

agentcore/aws-targets.json 中設定 AWS 帳戶和區域:

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

部署至 AgentCore Runtime。CLI 會使用 AWS CodeBuild 建置映像檔、將其推送至 Amazon ECR,並建立 Runtime 和一個 DEFAULT 端點:

npx @aws/agentcore deploy
備註

部署前,請在 agentcore/agentcore.json 內 Agent 的 environmentVariables 欄位中設定 Provider API 金鑰和其他秘密資料。

驗證部署
驗證部署 的直接連結

運行 agentcore status,查看 Runtime ARN、端點和最近的調用。然後從 CLI 呼叫已部署的 Agent:

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

如要在 token 產生時串流傳送,請使用 --stream

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