> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # 将 Mastra 部署到 Amazon Bedrock AgentCore 使用 [AgentCore CLI](https://github.com/aws/agentcore-cli) 将 Mastra 应用部署到 [Amazon Bedrock AgentCore Runtime](https://docs.aws.amazon.com/bedrock-agentcore/)。该 CLI 会搭建自带代码(BYO)TypeScript 项目,使用 AWS CodeBuild 构建容器,并预置 Runtime。部署不需要本地 Docker daemon。 本指南遵循[官方 AgentCore TypeScript 演练](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-get-started-cli-typescript.html),并对其进行调整,以便从调用 handler 中调用 Mastra Agent。 > **信息:** 如需基于 Lambda 部署完整 Mastra Server,请参阅 [AWS Lambda 指南](https://mastra.zisheng.pro/guides/deployment/aws-lambda)。如需使用长时运行的虚拟机,请参阅 [Amazon EC2 指南](https://mastra.zisheng.pro/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 可用且已启用计划调用基础模型的区域。 ## 创建新的 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` 目录: ```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 Server。`@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/reference/cli/mastra) 设置新的 Mastra 项目。提示中选择的 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()` 已移除,因为下一步会移除 Storage 层: ```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`,移除默认的基于文件的 Storage 和 observability 配置。AgentCore Runtime 容器以非 root 用户身份运行,应用目录为只读,因此默认 `LibSQLStore` 无法打开 `./mastra.db`,导致 Runtime 启动失败: ```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` 请求都会调用此 handler。在 handler 中解析并调用 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 构建:builder 阶段将 TypeScript 编译为 JavaScript,生产阶段只运行编译后的输出。为保证安全,镜像以非 root 用户身份运行,并暴露 8080(HTTP)、8000(MCP)和 9000(A2A)端口。启动时会自动包含 OpenTelemetry instrumentation。 ```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 构建上下文中排除不必要的文件: ```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 在 `agentcore/aws-targets.json` 中设置 AWS 账户和区域: ```json [ { "name": "default", "account": "123456789012", "region": "us-east-1" } ] ``` 部署到 AgentCore Runtime。CLI 会使用 AWS CodeBuild 构建镜像,将其推送到 Amazon ECR,并创建 Runtime 和 `DEFAULT` 端点: **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 ``` > **备注:** 部署前,请在 `agentcore/agentcore.json` 中 Agent 的 `environmentVariables` 字段下设置 Provider API Key 和其他 secret。 ## 验证部署 运行 `agentcore status` 查看 Runtime ARN、端点和最近的调用。然后从 CLI 调用已部署的 Agent: ```bash npx @aws/agentcore invoke "What is the weather in Tokyo?" ``` 如需在 token 生成时进行流式传输,请使用 `--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)