建立開發助手
本指南會教你建立一個結合所有 Workspace 功能的完整開發助手:
你會設定一個包含範例項目的 Workspace,並以 Skill 形式加入編程標準。然後,你會建立一個按照 TDD 實務編寫程式碼的 Agent。完成後,Agent 可以讀取現有程式碼並編寫新的實作,接着在 Sandbox 中執行測試,再根據結果反覆改進。
前置要求前置要求 的直接連結
- 已安裝 Node.js
v22.13.0或更新版本 - 已取得支援的 Model Provider 所提供的 API 金鑰
- 已有 Mastra 項目(請按照安裝指南設定新項目)
安裝 vitest安裝 vitest 的直接連結
開發助手會使用 Vitest 在 Workspace Sandbox 內執行測試。請在項目中將它安裝為開發依賴套件:
- npm
- pnpm
- Yarn
- Bun
npm install -D vitest
pnpm add -D vitest
yarn add --dev vitest
bun add --dev vitest
設定 Workspace設定 Workspace 的直接連結
Workspace 使用本機檔案系統管理文件檔案。Agent 會在 Workspace 目錄內讀寫檔案。在 src/mastra/index.ts 檔案中,匯入 Workspace、LocalFilesystem 和 LocalSandbox 類別。
此外,啟用 BM25 搜尋索引,並從 skills 目錄載入 Skill。
import { Mastra } from '@mastra/core'
import { resolve } from 'node:path'
import { Workspace, LocalFilesystem, LocalSandbox } from '@mastra/core/workspace'
const workspace = new Workspace({
filesystem: new LocalFilesystem({ basePath: resolve(import.meta.dirname, '../../workspace') }),
sandbox: new LocalSandbox({ workingDirectory: resolve(import.meta.dirname, '../../workspace') }),
skills: ['skills'],
bm25: true,
autoIndexPaths: ['docs', 'src'],
})
export const mastra = new Mastra({
workspace,
})
在項目根目錄建立名為 workspace 的新資料夾。所有檔案都會儲存於此,並由 Agent 管理。
加入範例項目檔案加入範例項目檔案 的直接連結
Workspace 使用以下資料夾結構:
workspace/src/:範例項目的原始碼workspace/tests/:測試檔案workspace/docs/:項目文件workspace/skills/:以 Agent Skills 形式提供的編程標準和指引
首先建立含有一些實用函式的 workspace/src/utils/string-helpers.ts 檔案,以及對應的測試檔案 workspace/tests/string-helpers.test.ts。
export function capitalize(str: string): string {
if (!str) return str
return str.charAt(0).toUpperCase() + str.slice(1)
}
export function slugify(str: string): string {
return str
.toLowerCase()
.replace(/[^\w\s-]/g, '')
.replace(/\s+/g, '-')
}
import { describe, it, expect } from 'vitest'
import { capitalize, slugify } from '../src/utils/string-helpers'
describe('String Helpers', () => {
describe('capitalize', () => {
it('capitalizes first letter', () => {
expect(capitalize('hello')).toBe('Hello')
})
})
describe('slugify', () => {
it('converts to lowercase and replaces spaces', () => {
expect(slugify('Hello World')).toBe('hello-world')
})
})
})
在 workspace/skills/coding-standards/SKILL.md 建立 Skill 定義。這會告訴 Agent 如何編寫及測試程式碼:
---
name: coding-standards
description: Project coding standards and testing guidelines
---
# Coding Standards
## Code quality
- Functions under 50 lines
- Use descriptive variable names
- Always add TypeScript types
## Testing
- Test all exported functions
- Use AAA pattern: Arrange, Act, Assert
- Cover happy paths and edge cases
## Before committing
1. Write implementation
2. Write comprehensive tests
3. Run tests: `npm test`
4. All tests must pass
在 workspace/skills/coding-standards/references/testing-guide.md 建立包含詳細測試模式的參考檔案:
# Testing Guide
## AAA pattern
```typescript
it('descriptive test name', () => {
// Arrange: Set up test data
const input = 'test'
// Act: Execute the function
const result = doSomething(input)
// Assert: Verify the result
expect(result).toBe('expected')
})
```
## What to test
- Happy paths (normal inputs)
- Edge cases (empty, null, boundary values)
- Error cases (invalid inputs, exceptions)
建立開發助手建立開發助手 的直接連結
Workspace 設定完成後,就可以建立開發助手 Agent。此 Agent 會包含使用測試驅動開發(TDD)加入新功能的指示。
建立新檔案 src/mastra/agents/dev-assistant.ts 並定義 Agent:
import { Agent } from '@mastra/core/agent'
export const devAssistant = new Agent({
id: 'dev-assistant',
name: 'Dev Assistant',
instructions: `You are a development assistant.
When adding features:
1. Activate 'coding-standards' skill
2. Search workspace for similar code examples
3. Write the implementation following standards
4. Write comprehensive tests. Leave existing tests in place, only add your new tests
5. Execute the command \`npx vitest run\` to validate that all tests pass
6. Update documentation if needed
For every new feature: Write code → Write tests → Run tests → Update docs
Always explain your reasoning and steps.`,
model: 'openai/gpt-5.6-sol',
})
在 src/mastra/index.ts 中匯入 Agent,並將它註冊至 Mastra 實例,以完成 Agent 定義:
import { Mastra } from '@mastra/core'
import { resolve } from 'node:path'
import { Workspace, LocalFilesystem, LocalSandbox } from '@mastra/core/workspace'
import { devAssistant } from './agents/dev-assistant'
const workspace = new Workspace({
filesystem: new LocalFilesystem({ basePath: resolve(import.meta.dirname, '../../workspace') }),
sandbox: new LocalSandbox({ workingDirectory: resolve(import.meta.dirname, '../../workspace') }),
skills: ['skills'],
bm25: true,
autoIndexPaths: ['docs', 'src'],
})
export const mastra = new Mastra({
workspace,
agents: { devAssistant },
})
測試助手測試助手 的直接連結
啟動 Studio,並與 Agent 互動,查看實際運作情況。
- npm
- pnpm
- Yarn
- Bun
npm run dev
pnpm run dev
yarn dev
bun run dev
開啟 localhost:4111,然後前往開發助手。
嘗試要求 Agent 使用 TDD 加入新函式:
Add a 'truncate' function to string-helpers.ts that shortens strings to a max length. Add '...' if truncated.
Follow TDD: write tests first, then implementation.
由於 Agent 回應並非確定不變,實際輸出會有所不同。不過,你應會看到 Agent 遵循類似以下的流程:
-
啟用 coding-standards Skill
-
在 Workspace 搜尋類似的程式碼模式
-
先編寫測試,例如:
describe('truncate', () => {it('truncates long strings', () => {expect(truncate('Hello World', 5)).toBe('He...')})it('keeps short strings unchanged', () => {expect(truncate('Hi', 10)).toBe('Hi')})it('handles edge cases', () => {expect(truncate('', 5)).toBe('')})}) -
編寫實作,例如:
export function truncate(str: string, maxLength: number): string {if (!str || maxLength < 0) return strif (str.length <= maxLength) return strif (maxLength === 0) return '...'return str.slice(0, maxLength - 3) + '...'} -
執行測試並確認全部通過
後續步驟後續步驟 的直接連結
你可以透過以下方式擴充此助手:
- 為不同語言或框架加入更多 Skill
- 為後端、前端或 DevOps 建立專門的 Agent
- 與 GitHub 整合,自動審查 PR
- 建立 CI/CD 自動化
- 加入多 Agent Workflow