
Mastra 项目结构详解src/mastra目录约定与 CLI 脚手架源码剖析【免费下载链接】mastraMastra is the modern TypeScript framework for AI-powered applications and agents.项目地址: https://gitcode.com/GitHub_Trending/ma/mastra本文是 Mastra 入门系列docs/src/course/01-first-agent/04-project-structure.md的扩展解读核心讲解 Mastra 官方约定的项目目录结构src/mastra下的index.ts入口、agents/、tools/、workflows/、scorers/四个组件目录各自承担什么职责以及这些目录和示例文件是由create-mastra/mastra init脚手架在底层如何生成与识别的。读完本文你将能独立检查自己的 Mastra 项目结构是否正确并理解该约定对开发服务器mastra dev的运行时意义。为什么目录结构如此重要Mastra 的代码组织约定Mastra 是一个 TypeScript 优先的 AI 应用框架。与许多框架要求所有代码堆在一个文件里不同Mastra 通过按组件类型分目录的约定来组织 Agent 应用src/mastra/ ├── index.ts # Mastra 项目主入口 ├── agents/ # 存放 Agent 定义文件 ├── scorers/ # 存放 Scorer评分器定义文件 ├── tools/ # 存放 Tool工具定义文件 └── workflows/ # 存放 Workflow工作流定义文件这一约定并非随意设计。从源码看CLI 的初始化逻辑里明确将组件类型定义为四个枚举值// packages/cli/src/commands/init/utils.ts#L21 export const COMPONENTS [agents, workflows, tools, scorers] as const;这意味着agents、workflows、tools、scorers是 Mastra 官方认可的四种一等组件first-class components它们在脚手架、打包器、开发服务器中被统一对待。index.ts则是整个 Mastra 实例的组装点——所有组件在这里被导入并注册到Mastra类上。src/mastra/index.ts项目主入口index.ts是整个 Mastra 项目的核心入口文件其作用等价于从mastra/core/mastra导入Mastra类导入各组件Agent、Workflow、Scorer的定义实例化new Mastra({ ... })并导出供mastra dev/mastra build/mastra start消费。最简单的空项目入口只需要两行来自脚手架测试的断言见 scaffold.test.tsimport { Mastra } from mastra/core/mastra; export const mastra new Mastra({});如果脚手架生成的是带示例的完整项目index.ts会同时装配存储、日志与可观测性结构大致如下由writeIndexFile生成见 init/utils.tsimport { Mastra } from mastra/core/mastra; import { PinoLogger } from mastra/loggers; import { LibSQLStore } from mastra/libsql; import { MastraCompositeStore } from mastra/core/storage; // ... import { weatherWorkflow } from ./workflows/weather-workflow; import { weatherAgent } from ./agents/weather-agent; import { toolCallAppropriatenessScorer, completenessScorer, translationScorer } from ./scorers/weather-scorer; export const mastra new Mastra({ agents: { weatherAgent }, workflows: { weatherWorkflow }, scorers: { toolCallAppropriatenessScorer, completenessScorer, translationScorer }, storage: new MastraCompositeStore({ default: new LibSQLStore({ url: process.env.TURSO_DATABASE_URL ?? file:./mastra.db, }), }), logger: new PinoLogger({ name: Mastra, level: info }), });入口文件的运行时意义从源码看开发服务器mastra dev依赖index.ts作为打包入口。DevBundler在 DevBundler.ts 中调用 Rollup watcher 监听index.ts及其依赖实现热更新。因此文件命名必须是index.ts或index.js。CLI 工具 find-mastra-entry.ts 会依次查找index.ts、index.js若两者都不存在则返回undefined此时 bundler 会退化为根据文件系统自动构建 Mastra 实例的模式即 auto-discover。index.ts必须导出mastra实例否则 dev 服务器无法获得你的应用配置。agents/Agent 定义目录agents/目录存放一个个独立的 Agent 文件。CLI 生成的示例名为weather-agent.ts内部通过mastra/core/agent的Agent类定义由writeAgentSample生成见 init/utils.tsimport { Agent } from mastra/core/agent; import { Memory } from mastra/memory; import { weatherTool } from ../tools/weather-tool; export const weatherAgent new Agent({ id: weather-agent, name: Weather Agent, instructions: You are a helpful weather assistant ..., model: openai/gpt-5-mini, tools: { weatherTool }, memory: new Memory(), });命名约定是weather-{component}.ts形式writeCodeSample函数中目标文件名被固定拼装为weather-${component.slice(0, -1)}.ts见 init/utils.ts即agents对应weather-agent.ts、scorers对应weather-scorer.ts、tools对应weather-tool.ts、workflows对应weather-workflow.ts。这解释了课程文档中那四个示例文件的来源。Agent 文件可以进一步依赖tools/与memory等模块通过相对路径如../tools/weather-tool导入——这是同一src/mastra体系内跨目录引用的标准方式。tools/工具定义目录tools/目录存放 Agent 可调用的工具Tool。示例weather-tool.ts通过mastra/core/tools的createTool定义并配合 Zod 描述输入输出 Schema。仓库中 starter-files/tools.ts 展示了完整形态import { createTool } from mastra/core/tools; import { z } from zod; export const weatherTool createTool({ id: get-weather, description: Get current weather for a location, inputSchema: z.object({ location: z.string().describe(City name), }), outputSchema: z.object({ temperature: z.number(), feelsLike: z.number(), humidity: z.number(), windSpeed: z.number(), windGust: z.number(), conditions: z.string(), location: z.string(), }), execute: async (inputData) { return await getWeather(inputData.location); }, });工具目录的运行时意义工具目录不只用于组织代码。在mastra dev中DevBundler会扫描以tools/开头的模块并单独打包成tools.mjs见 DevBundler.ts供 Mastra Studio 直接测试工具——这是 课程文档 05-running-playground 中Test tools directly能力的底层来源。因此保持工具文件位于src/mastra/tools/下能让开发工具链自动识别并暴露它们。workflows/工作流定义目录workflows/目录存放多步骤工作流定义。示例weather-workflow.ts使用mastra/core/workflows的createStep与createWorkflow由writeWorkflowSample生成见 init/utils.ts其骨架为import { createStep, createWorkflow } from mastra/core/workflows; import { z } from zod; const fetchWeather createStep({ id: fetch-weather, /* ... */ }); const planActivities createStep({ id: plan-activities, /* ... */ }); const weatherWorkflow createWorkflow({ id: weather-workflow, inputSchema: z.object({ city: z.string() }), }) .then(fetchWeather) .then(planActivities); weatherWorkflow.commit(); export { weatherWorkflow };值得注意的细节工作流示例中planActivities步骤通过mastra?.getAgent(weatherAgent)反查 Agent 实例见 init/utils.ts这说明 Workflow 与 Agent 可以在运行时互相协作——而这一切都建立在index.ts中统一注册的前提上。scorers/评分器定义目录scorers/目录存放用于评估 Agent 输出质量的 Scorer评分器。示例weather-scorer.ts由writeScorersSample生成见 init/utils.ts通常包含三类预置评分器如createToolCallAccuracyScorerCode检查是否正确调用预期工具与createCompletenessScorer检查回答完整性来自mastra/evals/scorers/prebuilt自定义 LLM 裁判评分器通过mastra/core/evals的createScorer定义支持preprocess/analyze/generateScore/generateReason四阶段流水线统一导出将多个 scorer 聚合为export const scorers { ... }供index.ts与 Agent 配置引用。课程文档强调scorers/weather-scorer.ts存在的原因在于src/mastra的四个组件目录是对称的——Agent 决定做什么Tool 决定能做什么Workflow 决定按什么顺序做Scorer 决定做得好不好。将评分逻辑独立成目录是为了让评估代码与应用逻辑解耦便于在 Mastra Studio 中单独调试与迭代。CLI 是如何生成这套结构的源码级验证如果你使用npm -y create mastralatest详见课程文档 03-verifying-installation或mastra init初始化项目脚手架会按以下流程生成上述结构创建src/{目录}/mastracreateMastraDir使用fsExtra.ensureDir递归创建目录见 init/utils.ts默认放在src/下。按用户选择生成组件writeCodeSampleForComponents根据用户勾选的组件agents / workflows / tools / scorers分别调用writeAgentSample、writeWorkflowSample、writeToolSample、writeScorersSample见 init/utils.ts。生成index.ts汇总注册writeIndexFile根据用户选择拼装导入语句与Mastra实例配置见 init/utils.ts。写入依赖与环境变量checkAndInstallCoreDeps确保mastra/core、mastra、zod以及选择示例时的mastra/libsql被安装见 init/utils.tswriteAPIKey将OPENAI_API_KEY等环境变量写入.env或.env.example见 init/utils.ts。脚手架测试scaffold.test.ts还验证了空脚手架只生成四个文件的确定性.gitignore、package.json、src/mastra/index.ts、tsconfig.json其中package.json内置了dev: mastra dev、build: mastra build、start: mastra start三个脚本——这正是你之后运行 Mastra Studionpm run dev的入口。如何检查你的项目结构是否正确对照课程文档的核查清单逐项确认检查项期望结果src/mastra/目录存在且包含以下五个条目src/mastra/index.ts存在导出mastra实例new Mastra({ ... })src/mastra/agents/存在若选择 Agent含weather-agent.ts等示例src/mastra/tools/存在若选择 Tool含weather-tool.ts等示例src/mastra/workflows/存在若选择 Workflow含weather-workflow.ts等示例src/mastra/scorers/存在若选择 Scorer含weather-scorer.ts等示例package.json包含mastra/core依赖与mastra开发依赖含dev/build/start脚本如果你是从零手动搭建未使用 CLI需要自己创建上述目录与文件若项目由 CLI 生成则示例文件应已就位。验证通过后运行npm run dev启动 Mastra Studio默认地址http://localhost:4111即可在浏览器中与 Agent 对话、查看其思考过程、直接测试工具并调试问题——这也是下一课 运行 Mastra Studio 的主题。小结Mastra 的目录结构约定可以概括为一句话src/mastra/index.ts负责组装四个组件目录负责分门别类地定义 Agent、Tool、Workflow 与 Scorer。这套约定不仅让代码组织清晰、便于团队协作与复用更与 CLI 脚手架、开发服务器、Mastra Studio 深度绑定——理解它是后续创建第一个 Agent课程 07-creating-your-agent与导出 Agent课程 08-exporting-your-agent的前提。【免费下载链接】mastraMastra is the modern TypeScript framework for AI-powered applications and agents.项目地址: https://gitcode.com/GitHub_Trending/ma/mastra创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考