Mastra 完整教學 2026:TypeScript 開發者的第一個 AI Agent
📋 本文目錄
Mastra 是 2026 年 TypeScript 生態中成長最快的 AI Agent Framework,GitHub 27.9K★,YC W25 投資,300K+ npm 週下載。如果你是 React / Next.js / TypeScript 開發者,Mastra 是比 Python LangChain 更自然的選擇。本文繁中首發完整教學。
一、Mastra 是什麼?為什麼 TypeScript 開發者需要它
2026 年的 AI Agent 生態已經不缺框架——LangChain、CrewAI、AutoGen、Agno……但幾乎所有主流框架都是 Python 優先。對於台灣大多數前端、全端開發者來說,切換到 Python 生態系意味著:重新學習套件管理、放棄熟悉的 TypeScript 型別系統、拋開現有的 Next.js/Express 基礎設施。
Mastra 就是為了解決這個問題而生的。
Mastra 核心背景
- 🏢 出品方:Gatsby 原班人馬(Kyle Mathews 等),TypeScript/Web 基因深植
- 💰 融資:YC W25,$13M 種子輪,Andreessen Horowitz 跟投
- 📦 版本:v1.0(2026 年 1 月 GA),目前最新 v1.14.x
- ⭐ GitHub:27,902 stars,2,756 forks(2026-09-11)
- 📥 npm:300,000+ 週下載,PH September 2026 月榜 Top 3
- 📡 Sep 1 新功能:Harness Channels GA(Slack/iMessage/WhatsApp/Discord 多人 agent)
Mastra 四大核心模組
Mastra 的架構圍繞四個模組設計,每個模組都有完整的 TypeScript 型別定義:
| 模組 | 功能 | 對應 LangChain |
|---|---|---|
| Agents | 定義 LLM 行為、工具、指令 | Agent / Chain |
| Tools | Zod schema 型別化的工具呼叫 | Tools / Functions |
| Memory | 向量記憶體、對話歷史、語義搜尋 | Memory / VectorStore |
| Workflows | 有向無環圖(DAG)工作流,條件分支 | Chains / Graphs |
Mastra 的工具定義使用 Zod schema,這意味著你在 IDE 中可以獲得完整的自動補全和型別檢查。當 LLM 的 function call 回傳資料時,TypeScript 編譯器就能在執行前幫你抓到型別錯誤——這是 Python LangChain 無法提供的開發體驗。
二、Mastra vs LangChain vs Agno vs OpenAI SDK 深度比較
選框架前,先看清楚各方的定位差異:
| 特性 | Mastra ✓ 推薦 | LangChain | Agno | OpenAI Agents SDK |
|---|---|---|---|---|
| 主要語言 | TypeScript | Python(JS 版功能少) | Python | Python |
| 型別系統 | Zod schema,完整型別 | Pydantic(Python),JS 版弱 | Pydantic | Pydantic |
| 記憶體 | 內建(向量 + 對話 + 語義) | 需手動配置 | 需手動配置 | 基本記憶體 |
| 工作流引擎 | 內建 DAG Workflows | LangGraph(額外學習) | 有 | 無 |
| Observability | 內建 OTel tracing | LangSmith(付費) | 第三方 | 無內建 |
| 部署方式 | Mastra Cloud / Docker / Vercel | LangChain Cloud / 自架 | 自架 | 自架 |
| GitHub Stars | 27.9K★ | 91K★ | 22K★ | 12K★ |
| 適合受眾 | TypeScript/React/Next.js 開發者 | Python ML 工程師 | Python 開發者 | OpenAI 深度用戶 |
三、5 步驟安裝與建立第一個 Mastra Agent
前置需求
- Node.js 18+ 或 20+(推薦 20 LTS)
- npm / pnpm / yarn(推薦 pnpm)
- Anthropic API Key 或 OpenAI API Key
Step 1:建立新專案
# 使用 Mastra CLI 初始化(推薦)
npx create-mastra@latest my-agent
cd my-agent
# 或在現有 Next.js / Express 專案中安裝
npm install @mastra/core @mastra/cli
Step 2:設定環境變數
# .env.local
ANTHROPIC_API_KEY=sk-ant-xxxxx
# 或使用 OpenAI
# OPENAI_API_KEY=sk-xxxxx
# 可選:Mastra Cloud 部署
MASTRA_CLOUD_API_KEY=mstr-xxxxx
Step 3:定義你的第一個 Agent
// src/agents/my-first-agent.ts
import { Agent } from "@mastra/core/agent";
import { anthropic } from "@ai-sdk/anthropic";
export const myFirstAgent = new Agent({
name: "My First Agent",
instructions: `你是一個專業的台灣科技新聞分析師。
用繁體中文回答,語氣簡潔專業。
分析新聞時要點出:商業影響、技術意義、台灣市場觀點。`,
model: anthropic("claude-sonnet-4-5"),
});
Step 4:建立 Mastra 實例並註冊 Agent
// src/mastra/index.ts
import { Mastra } from "@mastra/core";
import { myFirstAgent } from "../agents/my-first-agent";
export const mastra = new Mastra({
agents: { myFirstAgent },
});
Step 5:執行你的第一次對話
// src/index.ts
import { mastra } from "./mastra";
async function main() {
const agent = mastra.getAgent("myFirstAgent");
const response = await agent.generate(
"分析 Mastra 框架對台灣 TypeScript 開發者的影響"
);
console.log(response.text);
}
main();
npx ts-node src/index.ts,你的第一個 Mastra Agent 就跑起來了。接下來讓我們加入真正有用的工具。
四、TypeScript Typed Tools 實作教學
Mastra 的 Tools 系統是它最大的亮點——使用 Zod schema 定義工具參數,完全型別安全。
建立一個搜尋股票資料的工具
// src/tools/stock-tool.ts
import { createTool } from "@mastra/core/tools";
import { z } from "zod";
export const stockTool = createTool({
id: "get-stock-price",
description: "查詢台灣股票即時資訊(台灣證交所)",
// 完整型別定義,IDE 自動補全
inputSchema: z.object({
ticker: z.string().describe("股票代號,例如:2330 (台積電)"),
date: z.string().optional().describe("查詢日期,格式 YYYY-MM-DD"),
}),
outputSchema: z.object({
price: z.number(),
change: z.number(),
changePercent: z.string(),
volume: z.number(),
}),
// 執行函數——TypeScript 完整型別推斷
execute: async ({ context }) => {
const { ticker, date } = context;
// 呼叫台灣證交所 API
const response = await fetch(
`https://mis.twse.com.tw/stock/api/getStockInfo.jsp?ex_ch=tse_${ticker}.tw`
);
const data = await response.json();
return {
price: parseFloat(data.msgArray?.[0]?.z || "0"),
change: parseFloat(data.msgArray?.[0]?.ud || "0"),
changePercent: data.msgArray?.[0]?.pz || "0%",
volume: parseInt(data.msgArray?.[0]?.v || "0"),
};
},
});
將工具掛載到 Agent
// src/agents/stock-agent.ts
import { Agent } from "@mastra/core/agent";
import { anthropic } from "@ai-sdk/anthropic";
import { stockTool } from "../tools/stock-tool";
export const stockAgent = new Agent({
name: "Taiwan Stock Analyst",
instructions: "你是台灣股票分析師,使用繁體中文提供股票資訊和分析。",
model: anthropic("claude-sonnet-4-5"),
tools: { stockTool }, // 工具掛載,完整型別
});
五、Mastra Memory Gateway:讓 Agent 記住一切
Mastra 內建三層記憶體系統,無需額外配置向量資料庫:
| 記憶體類型 | 用途 | 儲存位置 |
|---|---|---|
| Working Memory | 當前對話上下文 | 記憶體(自動) |
| Semantic Memory | 語義搜尋相關對話片段 | Mastra Cloud 或本地向量庫 |
| Entity Memory | 使用者偏好、重要資訊 | 持久化儲存 |
配置持久記憶體
// src/mastra/index.ts
import { Mastra } from "@mastra/core";
import { Memory } from "@mastra/memory";
import { LibSQLStore } from "@mastra/memory/stores/libsql";
const memory = new Memory({
storage: new LibSQLStore({
url: "file:./mastra.db", // 本地 SQLite,生產可用 Turso
}),
vector: {
provider: "fastembed", // 免費,無需 API key
},
options: {
lastMessages: 20, // 保留最近 20 則對話
semanticRecall: {
topK: 5, // 語義搜尋返回最相關 5 則
threshold: 0.7, // 相似度門檻
},
},
});
export const mastra = new Mastra({
agents: { myFirstAgent },
memory, // 掛載記憶體系統
});
在 Agent 中使用記憶體
const agent = mastra.getAgent("myFirstAgent");
// 使用 threadId 維持跨對話的記憶
const response = await agent.generate(
"我喜歡台積電的投資分析",
{
threadId: "user-123-thread-1", // 用戶識別
resourceId: "user-123", // 實體識別
}
);
// 下次對話自動記住
const response2 = await agent.generate(
"上次我問的那支股票怎麼樣了?",
{
threadId: "user-123-thread-1",
resourceId: "user-123",
}
);
🚀 需要雲端主機運行你的 Mastra Agent?
DigitalOcean Droplet 每月 $4 起,支援 Node.js / Docker 部署,台灣開發者常用選擇。
🌊 DigitalOcean 免費 $200 試用額度 📊 DataCamp:TypeScript + LLM 完整課程六、Mastra Cloud 免費部署教學
方式一:Mastra Cloud(最簡單)
# 安裝 Mastra CLI
npm install -g @mastra/cli
# 登入 Mastra Cloud
mastra login
# 部署
mastra deploy
# 部署完成後取得 HTTPS endpoint
# https://your-app.mastra.cloud/api/agents/myFirstAgent/generate
免費方案:每月 10,000 次 agent 呼叫,1GB 記憶體儲存。付費方案從 $29/月起。如果你的 agent 使用量大,建議自架到 DigitalOcean($4-12/月 Droplet,無呼叫限制)。
方式二:Docker 自架(推薦生產環境)
# Dockerfile
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
RUN npm run build
EXPOSE 4111
CMD ["node", "dist/index.js"]
# 部署到 DigitalOcean Droplet
docker build -t my-mastra-agent .
docker run -d -p 4111:4111 \
-e ANTHROPIC_API_KEY=$ANTHROPIC_API_KEY \
my-mastra-agent
方式三:Vercel Edge Functions
// pages/api/agent.ts (Next.js)
import { mastra } from "@/src/mastra";
export const config = { runtime: "edge" };
export default async function handler(req: Request) {
const { message } = await req.json();
const agent = mastra.getAgent("myFirstAgent");
const response = await agent.generate(message);
return Response.json({ text: response.text });
}
七、台灣開發者三大實戰場景
場景一:LINE Bot 客服 Agent(Mastra Harness Channels)
使用 Sep 1 新功能 Harness Channels,讓 Mastra Agent 直接整合 LINE 官方帳號:
// src/channels/line-harness.ts
import { Mastra } from "@mastra/core";
import { LineHarness } from "@mastra/harness-line"; // Sep 1 GA
export const mastra = new Mastra({
agents: { customerServiceAgent },
harnesses: {
line: new LineHarness({
channelAccessToken: process.env.LINE_CHANNEL_ACCESS_TOKEN!,
channelSecret: process.env.LINE_CHANNEL_SECRET!,
}),
},
});
// 自動處理 LINE webhook,Agent 回覆繁體中文
// 無需手動建立 webhook server
一個 Mastra 客服 Agent 可以:同時處理 LINE + WhatsApp + 網站聊天室的客服問題,查詢訂單狀態(Tool 呼叫 ERP),回答商品問題(Semantic Memory 查詢產品知識庫),自動轉接人工(Workflow 條件分支)。
場景二:E-Commerce 庫存查詢 Agent
// src/agents/inventory-agent.ts
export const inventoryAgent = new Agent({
name: "Inventory Assistant",
instructions: "你是倉庫管理 AI 助手,協助查詢庫存和建立補貨建議。",
model: anthropic("claude-haiku-4-5"), // 輕量模型,省成本
tools: {
checkInventory, // 查詢庫存 API
createPurchaseOrder, // 建立採購單
checkSupplierPrice, // 查詢供應商報價
},
memory, // 記住歷史補貨模式
});
// 使用 Workflow 建立自動補貨流程
const restockWorkflow = new Workflow({
name: "Auto Restock",
steps: [
{ id: "check", action: checkInventoryStep },
{
id: "decide",
action: decideRestockStep,
when: { inventory: { lt: 100 } } // 庫存 < 100 才觸發
},
{ id: "order", action: createOrderStep },
],
});
場景三:GitHub PR Review Agent
// 整合 GitHub Actions,自動 Code Review
export const prReviewAgent = new Agent({
name: "PR Reviewer",
instructions: `你是資深 TypeScript 開發者,負責 code review。
重點檢查:型別安全、效能問題、安全漏洞、最佳實踐。
用繁體中文寫評論,語氣友善但直接。`,
model: anthropic("claude-sonnet-4-5"),
tools: {
getFileDiff, // 獲取 PR diff
postComment, // 在 GitHub 貼評論
requestChanges, // 請求修改
approvePR, // 批准 PR
},
});
// GitHub Actions 呼叫此 Agent
// 每次 PR 自動觸發 Review
八、FAQ 常見問題
Q1:Mastra 和 LangChain.js 有什麼實質差別?
LangChain.js 是 Python LangChain 的 JavaScript 移植,功能完整但文件品質和 TypeScript 型別支援不如 Mastra 原生。Mastra 從一開始就為 TypeScript 設計,Zod schema 工具定義、完整 IDE 支援、內建 Memory 都是 LangChain.js 目前追不上的。如果你的專案是 TypeScript 優先,Mastra 幾乎在所有方面都更順手。
Q2:Mastra 支援哪些 LLM?
Mastra 使用 Vercel AI SDK 作為底層,支援所有主流 LLM:Anthropic Claude(Sonnet/Haiku/Opus)、OpenAI GPT 系列、Google Gemini、Groq、Mistral、Ollama(本地模型)。切換模型只需修改一行程式碼。
Q3:Mastra Cloud 和自架哪個比較划算?
月呼叫 <10,000 次:Mastra Cloud 免費方案即可。月呼叫 10,000-100,000 次:Mastra Cloud $29/月 vs DigitalOcean Droplet $6-12/月——自架更划算。月呼叫 >100,000 次:一定自架,並考慮用 Redis 快取常見查詢。
Q4:在 Next.js 專案中使用 Mastra 有什麼注意事項?
Mastra 完全支援 Next.js App Router 和 Pages Router。Edge Runtime 有限制:不支援 LibSQL 本地檔案儲存(改用 Turso 雲端版本)、不支援 fastembed(改用 OpenAI Embeddings)。在 Node.js Runtime(預設)則無限制。
Q5:Mastra 的 Harness Channels 需要額外付費嗎?
Harness Channels(LINE/Slack/WhatsApp/Discord/iMessage)本身是 Mastra 開源功能,免費使用。費用來自各平台的 API 費用(LINE 官方帳號訊息費)和你選擇的 LLM API 費用(Anthropic/OpenAI),以及如果使用 Mastra Cloud 的部署費用。
Q6:Mastra Workflows 適合用來做什麼?
Mastra Workflows 是有向無環圖(DAG),最適合需要條件分支、並行執行或重試邏輯的複雜 Agent 任務。例如:自動化內容發布流程(撰寫→審核→發布→追蹤)、電商訂單處理(庫存查詢→付款→出貨→通知)、資料處理 pipeline(擷取→清理→分析→報告)。
🎓 想系統學習 TypeScript + AI Agent 開發?
DataCamp 提供完整的 TypeScript、LLM API 整合、AI Agent 開發課程,支援中文介面,適合從基礎到進階。
📊 DataCamp 免費試用 7 天 🌊 DigitalOcean 部署 Mastra($200 試用額度) 🤖 Systeme.io:AI 驅動的業務自動化平台總結:Mastra 值得投資嗎?
如果你是 TypeScript 開發者,2026 年評估 AI Agent Framework 的答案很明確:Mastra 是 TypeScript 生態最成熟的選擇,沒有之一。
它不是「最多功能」的框架(LangChain 生態更廣),也不是「最輕量」的框架(直接呼叫 Anthropic SDK 更簡單)。但如果你需要的是在 TypeScript 專案中建立生產級 AI Agent——有型別、有記憶、有工作流、能部署——Mastra 提供了最順滑的開發體驗。
- ✅ TypeScript/React/Next.js 開發者 → 立即嘗試
- ✅ 需要 LINE Bot / WhatsApp Agent → Harness Channels 直接支援
- ✅ 需要 Agent 記憶持久化 → 內建 Memory Gateway
- ⚠️ Python 優先團隊 → 繼續用 LangChain 更省轉換成本
- ⚠️ 超簡單一次性腳本 → 直接呼叫 API 即可,不需要框架
➤ DeepSeek Harness 完整教學:165K★ 插件式 Coding Agent
➤ SandboxAQ Switch:10 分鐘讓 AI Agent 進駐 Slack
➤ Claude Code 完整教學 2026
本文發布日期:2026-09-12 | 資訊以 2026-09-12 為準,框架持續更新,建議查閱 官方文件 確認最新狀態。