Skip to content

Chapter 2 · Project Structure and Mastra Studio ​

Chapter goals: Understand the scaffold-generated directory structure, master the four major panels of Mastra Studio, and develop a "code change → Studio verify" development rhythm.

2.1 Scaffold Directory Walkthrough ​

A project created with npm create mastra@latest has this structure:

text
my-mastra-app/
├── src/
│   └── mastra/               # ★ All Mastra resources go here
│       ├── index.ts          # Entry: new Mastra({...}) registers all resources
│       ├── agents/           # Agent definitions
│       │   └── weather-agent.ts
│       ├── tools/            # Tool definitions
│       │   └── weather-tool.ts
│       └── workflows/        # Workflow definitions
│           └── test-workflow.ts
├── package.json
├── tsconfig.json
└── .env                      # API keys and other env vars

Convention over configuration: mastra dev scans the src/mastra/ directory to auto-discover and hot-reload resources — you don't need to manually register file paths.

2.2 The Entry File index.ts ​

The entry file is the assembly point for the entire application:

typescript
// src/mastra/index.ts
import { Mastra } from '@mastra/core';
import { weatherAgent } from './agents/weather-agent';
// import { testWorkflow } from './workflows/test-workflow';

export const mastra = new Mastra({
  // Register agents; the key becomes the id used in getAgent('xxx')
  agents: { weatherAgent },
  // workflows: { testWorkflow },  // Uncomment when you have workflows
  // storage, memory, logger etc. are also configured here (covered in later chapters)
});
typescript
// Verify resources are discovered correctly in any script
import { mastra } from './mastra';

console.log(Object.keys(mastra.getAgents())); // Should output ['weatherAgent']

All resources (agents / workflows / tools / storage) are registered in one place, forming the application's resource graph.

2.3 Studio Four Panels ​

After starting npm run dev, open http://localhost:4111:

PanelFunctionTypical Use
AgentsChat with any registered Agent for testingDebug instructions, observe tool calls
WorkflowsGraphical view of step flows and execution pathsVerify .then/.branch connections match expectations
TracesView the complete call chain for each invocationDebug latency and token consumption
LogsRuntime log streamQuickly locate errors during development

2.4 Debugging Your First Agent with Studio ​

Select weatherAgent in the Agents panel, enter "上海明天适合跑步吗" (Is it suitable for running in Shanghai tomorrow?), and the right side expands to show the full execution process:

text
User: 上海明天适合跑步吗
 ├─ tool-call: weatherTool({ city: "Shanghai" })
 │   └─ tool-result: { temp: "22°C", condition: "Cloudy" }
 └─ Assistant: Tomorrow in Shanghai it will be cloudy with ~22°C, moderate humidity — perfect for outdoor running.

Tool call parameters and return values are fully visible throughout — the fastest way to debug "why didn't the model call my tool" issues.

2.5 Environment Variables and Secret Management ​

The scaffold generates a .env template based on the selected provider:

bash
# .env — never commit to git
OPENAI_API_KEY=sk-...
# If using anthropic provider instead:
# ANTHROPIC_API_KEY=sk-ant-...
typescript
// mastra dev auto-loads .env; no need to manually pass process.env in code
// But for custom deployments, use dotenv explicitly:
import 'dotenv/config'; // Must be placed at the very top, before任何其他 imports
typescript
// Explicit loading example for production deployment:
import 'dotenv/config';
import { mastra } from './mastra';

if (!process.env.OPENAI_API_KEY) {
  throw new Error('Missing OPENAI_API_KEY — check .env or platform environment variables');
}
console.log('Resources loaded:', Object.keys(mastra.getAgents()));

Security note

.env has already been added to .gitignore by the scaffold. If a key is accidentally leaked, revoke and rotate it immediately in the provider's console.

2.6 Chapter Summary ​

  • src/mastra/ is the only source directory you need to care about; index.ts is the resource assembly entry;
  • Studio's four panels: Agents chat testing, Workflows graphical view, Traces call-chain tracing, Logs;
  • Studio shows the complete tool call chain — the first stop for debugging Agent behavior;
  • API keys go in .env and are confirmed gitignored.

🧪 随堂测验

点击你认为正确的选项。答错时会展示正确答案与原因解析。

1. In a Mastra project, where are Agent / Tool / Workflow resources stored by default?

2. To view which tools were called and with what parameters during an Agent response, which panel do you use?

3. Regarding Mastra environment variable loading, which statement is correct?

4. What does new Mastra({ agents: { weatherAgent } }) do in src/mastra/index.ts?

🛠️ Hands-On Exercises ​

  1. In Studio's Agents panel, modify instructions (e.g., "always answer in Chinese"); observe the reply style change and feel the power of prompt design.
  2. Intentionally misspell the API Key in .env; observe the error message in Studio, then fix it.
  3. In the Traces panel, find a conversation record and count how many spans a single generate call contains.

Next: Chapter 3 · Model Routing