Mastra client SDK
Mastra Client SDK 提供簡潔且型別安全的介面,讓你從用戶端環境與 Mastra 伺服器互動。
前置要求前置要求 的直接連結
開始本機開發前,請準備:
- Node.js
v22.13.0或之後的版本 - TypeScript
v4.7或之後的版本(如使用 TypeScript) - 已啟動的本機 Mastra 伺服器(通常使用連接埠
4111)
Mastra Client SDK 專為瀏覽器環境而設,並使用原生 fetch API 向 Mastra 伺服器發出 HTTP 請求。
安裝安裝 的直接連結
要使用 Mastra Client SDK,請安裝所需依賴套件:
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/client-js@latest
pnpm add @mastra/client-js@latest
yarn add @mastra/client-js@latest
bun add @mastra/client-js@latest
初始化 MastraClientinitialize-the-mastraclient 的直接連結
以 baseUrl 初始化後,MastraClient 會提供型別安全的介面,用於呼叫 Agent、Tool 和 Workflow。
import { MastraClient } from '@mastra/client-js'
export const mastraClient = new MastraClient({
baseUrl: process.env.MASTRA_API_URL || 'http://localhost:4111',
})
核心 API核心 API 的直接連結
Mastra Client SDK 會公開 Mastra 伺服器提供的所有資源。
- Agent:產生回應及串流對話。
- A2A:透過 Agent Card 探索 Agent,並使用以任務為本的 A2A 串流。
- 記憶體:管理對話 Thread 及訊息記錄。
- Tool:執行及管理 Tool。
- Workflow:觸發 Workflow 並追蹤其執行情況。
- 向量:使用向量嵌入進行語義搜尋。
- 回應:透過與 OpenAI 相容、由 Agent 支援的介面,將 Mastra Agent 用作 Responses API。此 API 目前屬實驗性質。
- 對話:處理 Mastra Agent 作為 Responses API 時背後儲存的對話 Thread 及項目記錄。此 API 目前屬實驗性質。
- 日誌:檢視日誌及偵錯系統行為。
- 遙測:檢視應用程式效能及 Trace 活動。
建立及執行動態 Workflow建立及執行動態 Workflow 的直接連結
使用 upsertDynamicWorkflow() 建立或取代持久儲存的 Workflow 定義。成功執行 upsert 後,系統會驗證完整定義、向正在執行的 Mastra 執行個體註冊,並可透過標準 Workflow 執行 API 使用該定義。
以下範例展示 Mapping Workflow 的完整生命週期,涵蓋建立、檢查、執行以至刪除:
import { MastraClient } from '@mastra/client-js'
import type { UpsertDynamicWorkflowParams } from '@mastra/client-js'
const client = new MastraClient({
baseUrl: process.env.MASTRA_API_URL || 'http://localhost:4111',
})
const definition = {
id: 'greeting-workflow',
description: 'Returns a greeting for the supplied name',
inputSchema: {
type: 'object',
properties: { name: { type: 'string' } },
required: ['name'],
},
outputSchema: {
type: 'object',
properties: { message: { type: 'string' } },
required: ['message'],
},
graph: [
{
type: 'mapping',
id: 'create-greeting',
mapConfig: JSON.stringify({
message: { template: 'Hello, ${initData.name}!' },
}),
},
],
} satisfies UpsertDynamicWorkflowParams
await client.upsertDynamicWorkflow(definition)
const dynamicWorkflow = client.getDynamicWorkflow(definition.id)
const dynamicDefinition = await dynamicWorkflow.details()
const workflow = client.getWorkflow(dynamicDefinition.id)
const run = await workflow.createRun()
const result = await run.startAsync({ inputData: { name: 'Ada' } })
console.log(result)
await dynamicWorkflow.delete()
使用 listDynamicWorkflows() 列出持久儲存的定義。再次呼叫 upsertDynamicWorkflow() 並使用相同 id,會取代已儲存的定義及即時 Workflow 註冊。
持久儲存需要已設定並支援 workflowDefinitions Domain 的 Storage Adapter。缺少該 Domain 時,Core 可以在記憶體中註冊 Workflow,但伺服器的 Dynamic Workflow API 無法在重新啟動後保留該 Workflow。
已儲存的定義支援宣告式 Agent、Tool、Mapping、巢狀 Workflow、Parallel、Foreach、Sleep、Sleep-until、Conditional 及 Loop 項目,但不能包含 JavaScript Closure。Conditional 及 Loop 邏輯必須使用宣告式 Predicate 格式,而所參照的 Agent、Tool 及巢狀 Workflow 必須已經註冊。
已驗證身分的伺服器要求定義操作具備 stored-workflows:read 或 stored-workflows:write,而執行 Workflow 則須具備 workflows:execute。
產生回應產生回應 的直接連結
以字串 Prompt 呼叫 .generate():
import { mastraClient } from 'lib/mastra-client'
const testAgent = async () => {
try {
const agent = mastraClient.getAgent('testAgent')
const response = await agent.generate('Hello')
console.log(response.text)
} catch (error) {
return 'Error occurred while generating response'
}
}
你亦可以呼叫 .generate(),並傳入包含 role 及 content 的訊息物件陣列。詳情請參閱 .generate() 參考資料。
串流回應串流回應 的直接連結
以字串 Prompt 使用 .stream() 取得即時回應:
import { mastraClient } from 'lib/mastra-client'
const testAgent = async () => {
try {
const agent = mastraClient.getAgent('testAgent')
const stream = await agent.stream('Hello')
stream.processDataStream({
onTextPart: text => {
console.log(text)
},
})
} catch (error) {
return 'Error occurred while generating response'
}
}
你亦可以呼叫 .stream(),並傳入包含 role 及 content 的訊息物件陣列。詳情請參閱 .stream() 參考資料。
設定選項設定選項 的直接連結
MastraClient 接受 retries、backoffMs 和 headers 等選用參數,以控制請求行為。這些參數有助控制重試行為及加入診斷 Metadata。
import { MastraClient } from '@mastra/client-js'
export const mastraClient = new MastraClient({
retries: 3,
backoffMs: 300,
maxBackoffMs: 5000,
headers: {
'X-Development': 'true',
},
})
如需更多設定選項,請參閱 MastraClient。
憑證及 Session Cookie憑證及 Session Cookie 的直接連結
當你的 UI 與 Mastra API 並非同源,例如使用不同主機、子網域或連接埠(如 Mastra Studio 使用一個連接埠,而自訂伺服器使用另一個),請使用 Session Cookie 驗證 Mastra API 呼叫。加入 credentials: 'include' 至 MastraClient,讓每個請求都帶上用戶登入後已有的 Cookie。如略過此設定,即使已在瀏覽器成功登入,你仍經常會收到 Mastra 傳回的 401 回應。
import { MastraClient } from '@mastra/client-js'
export const mastraClient = new MastraClient({
baseUrl: process.env.MASTRA_API_URL || 'http://localhost:4111',
credentials: 'include',
})
請在伺服器允許帶有憑證的跨來源請求,詳情參閱 CORS:帶有憑證的請求。你需要指定明確的 Access-Control-Allow-Origin(不可使用 *)及 Access-Control-Allow-Credentials: true,否則瀏覽器會在呼叫到達 Mastra 前將其封鎖。
正在使用 @mastra/react? 請以 MastraReactProvider 包裹你的應用程式,設定 baseUrl 及 apiPrefix 以配合伺服器,並沿用預設的 credentials: 'include'。只有當你需要更改 credentials 以使用 same-origin 或 omit 行為時才這樣做。
加入取消請求功能加入取消請求功能 的直接連結
MastraClient 支援使用標準 Node.js AbortSignal API 取消請求。這適用於取消進行中的請求,例如用戶中止操作,或清理已失效的網絡呼叫。
將 AbortSignal 傳遞至 Client Constructor,即可為所有請求啟用取消功能。
import { MastraClient } from '@mastra/client-js'
export const controller = new AbortController()
export const mastraClient = new MastraClient({
baseUrl: process.env.MASTRA_API_URL || 'http://localhost:4111',
abortSignal: controller.signal,
})
使用 AbortControllerusing-the-abortcontroller 的直接連結
呼叫 .abort() 會取消所有與該 Signal 關聯且正在進行的請求。
import { mastraClient, controller } from 'lib/mastra-client'
const handleAbort = () => {
controller.abort()
}
用戶端 Tool用戶端 Tool 的直接連結
使用 createTool() 函數直接在用戶端應用程式中定義 Tool。透過 clientTools 參數,在 .generate() 或 .stream() 呼叫中將其傳遞給 Agent。
這讓 Agent 可以觸發瀏覽器端功能,例如操作 DOM、存取本機儲存空間或其他 Web API,從而在用戶環境而非伺服器上執行 Tool。
import { createTool } from '@mastra/client-js'
import { z } from 'zod'
const handleClientTool = async () => {
try {
const agent = mastraClient.getAgent('colorAgent')
const colorChangeTool = createTool({
id: 'color-change-tool',
description: 'Changes the HTML background color',
inputSchema: z.object({
color: z.string(),
}),
outputSchema: z.object({
success: z.boolean(),
}),
execute: async inputData => {
const { color } = inputData
document.body.style.backgroundColor = color
return { success: true }
},
})
const response = await agent.generate('Change the background to blue', {
clientTools: { colorChangeTool },
})
console.log(response)
} catch (error) {
console.error(error)
}
}
用戶端 Tool Agent用戶端 Tool Agent 的直接連結
這是一個標準 Mastra Agent,已設定為傳回十六進制色彩代碼,並配合上文定義的瀏覽器用戶端 Tool 使用。
import { Agent } from '@mastra/core/agent'
export const colorAgent = new Agent({
id: 'color-agent',
name: 'Color Agent',
instructions: `You are a helpful CSS assistant.
You can change the background color of web pages.
Respond with a hex reference for the color requested by the user`,
model: 'openai/gpt-5.6-sol',
})
在伺服器上使用 MastraClient在伺服器上使用 MastraClient 的直接連結
你亦可以在伺服器端環境中使用 MastraClient,例如 API Route、Serverless Function 或 Action。用法維持不變,但你可能需要為用戶端重新建立回應:
export async function action() {
const agent = mastraClient.getAgent('testAgent')
const stream = await agent.stream('Hello')
return new Response(stream.body)
}