Mastra フレームワーク完全ガイド:TypeScript 開発者のための AI Agent 必携ツール
なぜ Mastra を選ぶのか?
もしあなたが TypeScript/JavaScript 開発者で、AI アプリ開発において Python 開発者と同じ生産性を獲得したいなら、Mastra はあなたのために作られたフレームワークです。
Mastra は Y Combinator に支援されたオープンソースの TypeScript ネイティブ AI Agent フレームワークで、ウェブ開発者のために設計されています。AI アプリケーションの構築、テスト、デプロイに必要なすべてのプリミティブを提供し、アイデアから本番環境まで迅速に進めることができます。
コアアドバンテージ
- TypeScript ネイティブ: 完全な型サポートと IDE インテリセンス
- 本番準備完了: ワークフロー、メモリ、RAG、評価、トレーシングを内蔵
- 開発者体験: インタラクティブな Playground とリアルタイムデバッグ
- オープンソース無料: MIT ライセンス、コミュニティ駆動
クイックスタート
Mastra のインストール
# 新規プロジェクトの作成
npx create-mastra@latest my-ai-app
# プロジェクトディレクトリに移動
cd my-ai-app
# 依存関係のインストール
npm install
プロジェクト構造
my-ai-app/
├── src/
│ ├── mastra/
│ │ ├── agents/ # Agent 定義
│ │ ├── tools/ # カスタムツール
│ │ ├── workflows/ # ワークフロー
│ │ └── index.ts # メインエントリ
│ └── index.ts
├── package.json
└── mastra.config.ts
コアコンセプト
1. Agent の作成
Agent は Mastra のコアビルディングブロックです。各 Agent には特定の役割、ツール、メモリがあります。
// src/mastra/agents/customer-support.ts
import { Agent } from '@mastra/core/agent';
export const customerSupportAgent = new Agent({
name: 'Customer Support Agent',
instructions: `
あなたはプロフェッショナルなカスタマーサポートアシスタントで、製品に関するユーザーの質問に対応します。
- フレンドリーでプロフェッショナルなトーンを維持
- 正確な情報を提供
- 答えがわからない場合は正直に伝え、人工サポートへの連絡を提案
`,
model: {
provider: 'ANTHROPIC',
name: 'claude-sonnet-4-20250514',
},
});
2. カスタムツールの作成
ツールは Agent がデータベースのクエリや API 呼び出しなどの具体的なアクションを実行できるようにします。
// src/mastra/tools/order-lookup.ts
import { createTool } from '@mastra/core/tools';
import { z } from 'zod';
export const orderLookupTool = createTool({
id: 'order-lookup',
description: '注文番号で注文ステータスを照会',
inputSchema: z.object({
orderId: z.string().describe('注文番号'),
}),
execute: async ({ context }) => {
const { orderId } = context;
// データベースクエリのシミュレーション
const order = await db.orders.findUnique({
where: { id: orderId },
});
return {
status: order?.status || 'not_found',
items: order?.items || [],
total: order?.total || 0,
};
},
});
3. ツールを Agent にバインド
// src/mastra/agents/customer-support.ts
import { customerSupportAgent } from './customer-support';
import { orderLookupTool } from '../tools/order-lookup';
// ツールを追加
customerSupportAgent.addTools([orderLookupTool]);
4. ワークフローの作成
ワークフローにより、複数の Agent とツールをオーケストレーションして複雑なビジネスプロセスを実装できます。
// src/mastra/workflows/order-processing.ts
import { Workflow } from '@mastra/core/workflows';
import { agentStep } from '@mastra/core/step';
export const orderProcessingWorkflow = new Workflow({
name: 'order-processing',
triggerSchema: z.object({
orderId: z.string(),
customerEmail: z.string().email(),
}),
});
// ステップを定義
const checkOrder = agentStep({
agent: customerSupportAgent,
outputSchema: z.object({
status: z.string(),
canRefund: z.boolean(),
}),
});
const sendEmail = agentStep({
agent: emailAgent,
outputSchema: z.object({
sent: z.boolean(),
}),
});
// フローをオーケストレーション
orderProcessingWorkflow
.step(checkOrder)
.then(sendEmail, {
when: { ref: checkOrder, path: 'canRefund', eq: true },
});
実践例:カスタマーサービスボットの構築
注文照会、返品リクエスト、製品相談を処理できる完全なカスタマーサービスボットを構築しましょう。
完全なコード
// src/mastra/index.ts
import { Mastra } from '@mastra/core/mastra';
import { customerSupportAgent } from './agents/customer-support';
import { orderLookupTool } from './tools/order-lookup';
import { refundTool } from './tools/refund';
import { orderProcessingWorkflow } from './workflows/order-processing';
export const mastra = new Mastra({
agents: {
'customer-support': customerSupportAgent,
},
tools: {
'order-lookup': orderLookupTool,
'refund': refundTool,
},
workflows: {
'order-processing': orderProcessingWorkflow,
},
});
開発サーバーの起動
# Mastra 開発サーバーを起動(Playground 含む)
npx mastra dev
http://localhost:4111 にアクセスしてインタラクティブな Playground を開き、Agent をリアルタイムでテストできます。
Agent の呼び出し
// src/index.ts
import { mastra } from './mastra';
async function main() {
const agent = mastra.getAgent('customer-support');
const response = await agent.generate(
'注文番号は ORD-12345 です。ステータスを教えてください'
);
console.log(response.text);
}
main();
高度な機能
メモリシステム
Mastra にはメモリが内蔵されており、Agent が会話履歴を記憶できます。
import { Memory } from '@mastra/memory';
const memory = new Memory({
storage: {
type: 'postgres',
connectionString: process.env.DATABASE_URL,
},
});
const agent = new Agent({
name: 'Support Agent',
memory,
// ...その他の設定
});
RAG(検索拡張生成)
import { RAG } from '@mastra/rag';
const rag = new RAG({
vectorStore: {
type: 'pinecone',
apiKey: process.env.PINECONE_API_KEY,
},
});
// ドキュメントをインデックス化
await rag.index({
documents: ['./docs/product-manual.pdf'],
indexName: 'product-knowledge',
});
// Agent で使用
const agent = new Agent({
name: 'Product Expert',
rag: {
indexes: ['product-knowledge'],
},
});
評価とトレーシング
import { Eval } from '@mastra/evals';
const eval = new Eval({
name: 'response-quality',
criteria: [
{ name: 'accuracy', weight: 0.4 },
{ name: 'helpfulness', weight: 0.3 },
{ name: 'tone', weight: 0.3 },
],
});
// 評価を実行
const results = await eval.evaluate(agent, testCases);
console.log(results.summary);
本番デプロイ
Vercel へのデプロイ
# Vercel CLI のインストール
npm i -g vercel
# デプロイ
vercel deploy --prod
Docker へのデプロイ
# Dockerfile
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
EXPOSE 3000
CMD ["npm", "start"]
# ビルドと実行
docker build -t my-mastra-app .
docker run -p 3000:3000 my-mastra-app
パフォーマンス最適化のヒント
- ストリーミング応答を使用: 長文生成では、streaming を有効にしてユーザー体験を向上
- ツール結果をキャッシュ: 頻繁に呼び出されるツールには結果キャッシュを実装
- バッチ処理: 複数の類似リクエストにはバッチ API 呼び出しを使用
- レイテンシを監視: Mastra 内蔵のトレーシングで各ステップの所要時間を監視
他のフレームワークとの比較
| 機能 | Mastra | LangChain.js | Vercel AI SDK |
|---|---|---|---|
| TypeScript ネイティブ | ✅ | ⚠️ | ✅ |
| 内蔵ワークフロー | ✅ | ✅ | ❌ |
| インタラクティブ Playground | ✅ | ❌ | ❌ |
| メモリシステム | ✅ | ✅ | ⚠️ |
| RAG サポート | ✅ | ✅ | ❌ |
| 評価ツール | ✅ | ⚠️ | ❌ |
| 学習曲線 | 中程度 | 急 | 緩やか |
まとめ
Mastra は TypeScript 開発者が AI Agent 開発に入るための最適な選択肢の一つです。以下を提供します:
- 🎯 開発者に優しい API: 型安全、インテリセンス完全サポート
- 🔧 豊富な内蔵機能: ワークフロー、メモリ、RAG、評価をワンストップで
- 🚀 本番準備完了: 開発からデプロイまでの完全なツールチェーン
- 📚 優れたドキュメント: 詳細なチュートリアルと例
すでに TypeScript エコシステムで作業していて、AI アプリを迅速に構築したいなら、Mastra は試す価値があります。
参考リソース
関連記事推奨: