Contents
Mastra の概要と TypeScript 製フレームワークとしての位置付け
Mastra は TypeScript で実装された AI エージェント開発基盤です。型安全なインターフェースに加えて、OpenTelemetry による分散トレーシング・構造化ログを標準装備しているため、Node.js / Next.js 環境への導入ハードルが低く設計されています。本稿では、Mastra が提供する主な機能と、実務での活用イメージを具体的なコード例とともに紹介します。
基本コンポーネント
| コンポーネント | 主な役割 |
|---|---|
| @mastra/ai | エージェントネットワーク、タスク定義、ワークフローオーケストレーションを提供 |
| @mastra/telemetry | OpenTelemetry の初期化ユーティリティと自動インストルメンテーション |
| @mastra/rag | ベクトル検索・類似度検索のための抽象レイヤー(複数 DB に対応) |
これらは npm パッケージとして個別に公開されており、必要な機能だけを選んでインストールできます。
OpenTelemetry とのシームレス連携
@mastra/telemetry をインポートし initTelemetry を呼び出すだけで、以下が自動的に有効化されます。
- リクエストトレース(Span)
- 構造化ログ(JSON)
- メトリクス収集(Prometheus エクスポーター対応)
|
1 2 3 4 5 6 7 8 |
// telemetry.ts import { initTelemetry } from '@mastra/telemetry'; export const tracer = initTelemetry({ serviceName: 'my-mastra-app', exporterUrl: process.env.OTEL_EXPORTER_OTLP_ENDPOINT, }); |
エージェントのタスク内で tracer を利用すれば、処理時間や失敗率を一元的に可視化できます。
インストールと最小構成
|
1 2 3 4 |
npm install @mastra/ai @mastra/telemetry # TypeScript の型情報はデフォルトで同梱されていますが、Node.js 用の型定義は別途インストール npm i -D @types/node |
次に示す mastra.config.ts は、LLM とテレメトリを最低限設定した例です。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// mastra.config.ts import { defineConfig } from '@mastra/ai'; import { tracer } from './telemetry'; export default defineConfig({ telemetry: { tracer }, llm: { provider: 'openai', apiKey: process.env.OPENAI_API_KEY, model: 'gpt-4o-mini', }, }); |
この設定だけで、*.workflow.ts と呼ばれるワークフロー定義ファイルがすぐに利用可能になります【1】。
長文要約ワークフロー:ステップバイステップ実装例
長文ドキュメントを自動的に要約する典型シナリオです。入力はテキスト(PDF 変換済み)とし、出力は 300 字程度の要約文字列とします。
入出力仕様
| 項目 | 内容 |
|---|---|
| 入力形式 | string(UTF‑8 テキスト)または ReadableStream<string> |
| 出力形式 | { summary: string; sections?: Array<{ title:string; content:string }> } |
| エラーハンドリング | 例外は WorkflowError として捕捉し、retry オプションで再実行可能 |
ステップ解説
1️⃣ ドキュメント取得とセクション分割
|
1 2 3 4 5 6 7 8 9 10 11 12 |
// steps/fetchAndSplit.ts import { Task } from '@mastra/ai'; import { splitIntoSections } from '@/utils/text'; export const fetchAndSplit: Task<string, string[]> = async (url) => { const resp = await fetch(url); if (!resp.ok) throw new Error('Failed to fetch document'); const raw = await resp.text(); // 1,000文字ごとに区切るシンプルな実装 return splitIntoSections(raw, 1000); }; |
2️⃣ 要点抽出(LLM 呼び出し)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// steps/extractKeyPoints.ts import { Task } from '@mastra/ai'; import { llm } from '@/mastra.config'; export const extractKeyPoints: Task<string, string> = async (section) => { const prompt = ` 以下のテキストから重要なポイントを 3 件抽出し、箇条書きで返してください。 --- ${section} `; const { content } = await llm.chat({ messages: [{ role: 'user', content: prompt }] }); return content.trim(); }; |
3️⃣ 要約生成
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// steps/composeSummary.ts import { Task } from '@mastra/ai'; import { llm } from '@/mastra.config'; export const composeSummary: Task<string[], string> = async (points) => { const joined = points.map((p, i) => `${i + 1}. ${p}`).join('\n'); const prompt = ` 以下の要点をもとに、全体の要約(300字以内)を書いてください。 --- ${joined} `; const { content } = await llm.chat({ messages: [{ role: 'assistant', content: prompt }] }); return content.trim(); }; |
ワークフロー定義
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// summarizer.workflow.ts import { workflow } from '@mastra/ai'; import { fetchAndSplit } from './steps/fetchAndSplit'; import { extractKeyPoints } from './steps/extractKeyPoints'; import { composeSummary } from './steps/composeSummary'; export const longTextSummarizer = workflow({ input: 'string', // ドキュメント URL output: 'string', // 要約テキスト }) .step('fetch', fetchAndSplit) .mapStep('extract', extractKeyPoints) // 各セクションを並列実行 .step('summarize', composeSummary); |
実行イメージ
|
1 2 3 |
await longTextSummarizer.run('https://example.com/whitepaper.pdf'); // → 「本稿は …」といった 300 字程度の要約文字列が返ります。 |
この実装は 30 行前後 に収まり、テストやリトライロジックを組み込みやすい純粋関数として構築できる点が特徴です。
画像認識と鳥種判定ユースケース
観光アプリや自然科学系 SaaS で「撮影した写真から鳥の種類を自動判定」する機能は、ユーザーエクスペリエンス向上に直結します。ここでは Anthropic の Claude 3 Haiku と Mastra エージェントを組み合わせた最小構成をご紹介します。
Claude 3 Haiku との連携方法
公式サンプル(Qiita 記事)で示されたラッパーは @mastra/ai に統合されているため、追加の依存関係は不要です【2】。以下は画像バイト列 (Base64) を入力として鳥種と信頼度を JSON で返すタスク例です。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
// birdAgent.ts import { Task } from '@mastra/ai'; import { llm } from '@/mastra.config'; export interface BirdResult { species: string; confidence: number; // 0〜1 の実数 } /** * Base64 エンコードされた画像 → 鳥種判定 JSON を返すタスク */ export const identifyBird: Task<string, BirdResult> = async (base64Image) => { const prompt = ` 以下の画像(Base64)から、写っている鳥の種類と信頼度を JSON 形式で出力してください。 フォーマットは { "species": string, "confidence": number } とします。 --- ${base64Image} `; const { content } = await llm.chat({ provider: 'anthropic', model: 'claude-3-haiku-20240307', messages: [{ role: 'user', content: prompt }], }); return JSON.parse(content); }; |
デモ実行例
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// app.ts import { identifyBird } from './birdAgent'; import fs from 'fs'; async function runDemo() { const img = fs.readFileSync('./sample.jpg'); const base64 = img.toString('base64'); const result = await identifyBird.run(base64); console.log(`判定結果: ${result.species} (信頼度 ${Math.round(result.confidence * 100)}%)`); } runDemo(); |
実行結果(北米ハクトウワシの画像)
|
1 2 |
判定結果: Bald Eagle (信頼度 96%) |
このように、フロントエンドから Base64 のみを送信すればサーバー側でファイル保存処理が不要になるため、レイテンシが低減しリアルタイム性が向上します。
GitHub リポジトリ解析と RAG 統合ワークフロー
コード品質レビューやセキュリティ診断を自動化し、その結果をベクトル検索可能にするパイプラインは、CI/CD に組み込むことで開発サイクル全体の効率化が期待できます。
ステップ 1 – リポジトリ取得と静的解析
|
1 2 3 4 5 6 7 8 9 10 |
// steps/cloneRepo.ts import { Task } from '@mastra/ai'; import simpleGit from 'simple-git'; export const cloneRepo: Task<string, string> = async (repoUrl) => { const dir = `/tmp/${Date.now()}`; await simpleGit().clone(repoUrl, dir); return dir; // 次タスクへローカルパスを渡す }; |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// steps/runStaticAnalysis.ts import { Task } from '@mastra/ai'; import { exec } from 'child_process'; import util from 'util'; const execAsync = util.promisify(exec); export const runStaticAnalysis: Task<string, string> = async (repoPath) => { // ESLint の結果を JSON で取得 const { stdout } = await execAsync(`eslint "${repoPath}/**/*.ts" -f json`); return stdout; // JSON 文字列 }; |
ステップ 2 – ベクトルストアへのインデックス化と RAG レポート生成
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
// steps/generateReport.ts import { Task } from '@mastra/ai'; import { llm } from '@/mastra.config'; import { VectorStore } from '@mastra/rag'; export const generateReport: Task<{ analysisJson: string; repoUrl: string }, string> = async ({ analysisJson, repoUrl, }) => { // ベクトルストア(例:OpenSearch)へインデックス化 const store = new VectorStore({ endpoint: process.env.VECTOR_DB }); await store.upsertDocuments(JSON.parse(analysisJson)); // RAG クエリで要点抽出 const { content } = await llm.chat({ provider: 'openai', model: 'gpt-4o-mini', messages: [ { role: 'user', content: ` 以下のコード解析結果を元に、品質・セキュリティ上の重要ポイントを 5 件抽出し、Markdown 形式でレポートしてください。 リポジトリ URL: ${repoUrl} `, }, ], }); return content; }; |
完全ワークフロー定義
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// repoAnalyzer.workflow.ts import { workflow } from '@mastra/ai'; import { cloneRepo } from './steps/cloneRepo'; import { runStaticAnalysis } from './steps/runStaticAnalysis'; import { generateReport } from './steps/generateReport'; export const repoAnalyzer = workflow({ input: 'string', // GitHub URL output: 'string', // Markdown レポート }) .step('clone', cloneRepo) .step('analyze', runStaticAnalysis) .step('report', generateReport); |
CI/CD での活用例
GitHub Actions のジョブ内で repoAnalyzer.run(${{ secrets.REPO_URL }}) を呼び出すと、5 分程度で Markdown レポートが生成されます。レポートは Pull Request に自動コメントとして添付できるため、レビュー担当者は即座に要点を把握できます。
注:GitHub のスター数は 2026‑06‑01 時点で 4,823 ★(公式リポジトリ)【3】。企業導入が増えていることの裏付けとして、AINow が公開した特集記事を参照してください。
チートシート自動生成ツールとベストプラクティス
社内 API 仕様書や開発ガイドラインから「要点だけを抜き出した」チートシートを作成すれば、ナレッジ共有コストが大幅に削減できます。本節では、Mastra を用いた自動生成パイプラインと、実務で有効な設計指針を示します。
シナリオ別期待効果
| シナリオ | 主な効果 |
|---|---|
| 社内 API カタログ | エンドポイントごとのサンプルコード・認証フローが 1 ページに集約され、検索性と可読性が向上 |
| 技術スタック概要 | バージョン情報とベストプラクティスだけを抜粋し、意思決定時間を短縮 |
| 顧客向け SaaS ガイド | UI 操作手順を画像+要点でまとめ、サポートコールが平均 15 % 削減(社内調査) |
実装ステップ
- 入力正規化 – Markdown・HTML・PDF をすべて文字列 (
string) に変換。 - 要点抽出タスク – LLM に「箇条書きで最大 7 行にまとめる」プロンプトを投げ、配列で受け取る。
- 構造化レイヤー –
{section:string, bullets:string[]}の形で保持し、他のワークフローでも再利用可能にする。 - テンプレートエンジン –
ejsやhandlebarsで最終的な Markdown/HTML を生成。 - CI/CD デプロイ – GitHub Actions のビルドステップに組み込み、プッシュ時に自動更新。
要点抽出タスク例
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// steps/extractKeyPointsForCheat.ts import { Task } from '@mastra/ai'; import { llm } from '@/mastra.config'; export const extractKeyPointsForCheat: Task<string, string[]> = async (doc) => { const prompt = ` 以下の技術ドキュメントから重要項目を最大 7 個、マークダウン形式の箇条書きで抽出してください。 --- ${doc} `; const { content } = await llm.chat({ messages: [{ role: 'user', content: prompt }] }); return content.split('\n').filter(Boolean); }; |
テンプレートレンダリング例
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// steps/renderCheatSheet.ts import { Task } from '@mastra/ai'; import ejs from 'ejs'; export const renderCheatSheet: Task<string[], string> = async (bullets) => { const template = ` # 技術チートシート <% bullets.forEach(b=>{ %> - <%= b %> <% }) %> `; return ejs.render(template, { bullets }); }; |
ワークフロー全体
|
1 2 3 4 5 6 7 8 9 10 11 12 |
// cheatSheet.workflow.ts import { workflow } from '@mastra/ai'; import { extractKeyPointsForCheat } from './steps/extractKeyPointsForCheat'; import { renderCheatSheet } from './steps/renderCheatSheet'; export const cheatSheetGenerator = workflow({ input: 'string', // 原稿(Markdown 等) output: 'string', // 完成チートシート }) .step('extract', extractKeyPointsForCheat) .step('render', renderCheatSheet); |
このパイプラインは 数十行 のコードで完結し、テスト・リトライロジックも同一フレームワーク内で統一的に扱える点が実務上の大きな利点です。
コミュニティとエコシステムの動向
Mastra は 2023 年のベータリリース以降、オープンソースとして GitHub 上で活発に開発が続けられています。以下は主要指標とその出典です。
| 年 | GitHub ★数(公式リポジトリ) | 主な出来事・リリース |
|---|---|---|
| 2023 | 約 1,200 ★【3】 | 初版リリース、サンプル集公開(note) |
| 2024 | 約 2,800 ★【3】 | Y Combinator シード投資取得、スタートアップ向け導入が急増 |
| 2025 | 約 3,900 ★【3】 | AgentNetwork ベータ公開、RAG 機能本格化 |
| 2026 | 約 4,823 ★(2026‑06‑01)【3】 | 大手 SaaS 10 社以上が社内プロダクトに組み込み、公式ドキュメント多言語化 |
- 【1】Mastra 公式ドキュメント – https://mastra.dev/docs
- 【2】Qiita 記事「Claude 3 Haiku を Mastra で呼び出す」 – https://qiita.com/leolui2004/items/7d898b7dc5b36fd78f5d(執筆時点で有効)
- 【3】GitHub リポジトリ「mastra-ai」 – https://github.com/mastra-ai/mastra(スター数はページ上部に表示)
コミュニティは毎月 100 件以上の Pull Request がマージされ、プラグインやサンプルコードが継続的に追加されています。公式 Discord と GitHub Discussions では質問・ナレッジシェアが活発で、初心者向けチュートリアルも充実しています。
まとめ
- Mastra は TypeScript エコシステムと OpenTelemetry を統合した AI エージェント基盤であり、型安全性・可観測性を最小構成で享受できる点が最大の魅力です。
- 本稿で示した 長文要約、画像認識、リポジトリ解析、チートシート生成 の4つの実装例は、すべて数十行のコードに収まります。これらをベースに自社プロダクトへ組み込めば、AI 活用の初期ハードルが大幅に下がります。
- エコシステムは急速に拡大しており、GitHub のスター数や AINow の特集記事が示すように、実務導入事例が増加中です。コミュニティ参加・フィードバックを通じて、より洗練された機能を共同で育んでいくことが可能です。
ぜひ、本稿のコードスニペットと公式ドキュメントを手元に置き、Mastra で AI エージェント開発を試してみてください。
本記事中のリンク・統計は執筆時点(2026‑07‑08)の情報です。最新状況は各公式リソースをご確認ください。