跳到主要内容
非官方简体中文翻译,内容版权归 Mastra 所有,遵循 Apache-2.0 许可。

Mastra client

Mastra Client SDK 提供了一个简洁且类型安全的接口,让你在客户端环境中与 Mastra Server 交互。

前提条件
前提条件的直接链接

开始本地开发之前,请确保具备:

  • Node.js v22.13.0 或更高版本
  • TypeScript v4.7 或更高版本(如果使用 TypeScript)
  • 本地 Mastra 服务器正在运行(通常在端口 4111 上)
备注

Mastra Client SDK 面向浏览器环境设计,使用原生 fetch API 向 Mastra 服务器发起 HTTP 请求。

安装
安装的直接链接

要使用 Mastra Client SDK,请安装所需依赖:

npm install @mastra/client-js@latest

初始化 MastraClient
初始化-mastraclient的直接链接

使用 baseUrl 初始化后,MastraClient 会暴露一个类型安全的接口,用于调用 agent、工具和工作流。

lib/mastra-client.ts
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 Server 提供的所有资源。

  • Agents:生成响应并流式传输对话。
  • A2A:通过 agent card 发现 agent,并使用基于任务的 A2A 流。
  • Memory:管理对话 thread 和消息历史。
  • Tools:已执行和受管理的工具。
  • Workflows:触发工作流并跟踪其执行。
  • Vectors:使用向量 embedding 进行语义搜索。
  • Responses:将 Mastra Agents 作为 Responses API 使用,提供兼容 OpenAI、由 agent 支持的接口。此 API 目前为实验性。
  • Conversations:处理 Mastra Agents 作为 Responses API 背后的已存储对话 thread 和条目历史。此 API 目前为实验性。
  • Logs:查看日志并调试系统行为。
  • Observability:查看应用性能和 trace 活动。

创建并运行动态工作流
创建并运行动态工作流的直接链接

使用 upsertDynamicWorkflow() 创建或替换持久化的工作流定义。成功的 upsert 会验证完整定义并将其注册到正在运行的 Mastra 实例。随后该工作流即可通过标准执行 API 使用。

以下示例展示了映射工作流的完整生命周期,从创建、检查到执行和删除:

lib/dynamic-workflow.ts
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() 列出已持久化的定义。再次以相同 id 调用 upsertDynamicWorkflow() 会替换存储的定义和实时工作流注册。

注意

持久化存储需要配置支持 workflowDefinitions 域的存储适配器。如果没有该域,Core 可以在内存中注册工作流,但服务器的动态工作流 API 无法在重启后保留它。

存储的定义支持声明式 agent、工具、映射、嵌套工作流、并行、foreach、sleep、sleep-until、条件和循环条目。它们不能包含 JavaScript 闭包。条件和循环逻辑必须使用声明式谓词格式,并且引用的 agent、工具和嵌套工作流必须已注册。

启用身份验证的服务器需要 stored-workflows:read 或 stored-workflows:write 权限来操作定义,运行工作流需要 workflows:execute 权限。

生成响应
生成响应的直接链接

使用字符串提示调用 .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'
}
}
备注

你还可以使用包含 role 和 content 的消息对象数组调用 .generate()。更多信息请访问 .generate() 参考。

流式响应
流式响应的直接链接

使用字符串提示时,用 .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'
}
}
备注

你还可以使用包含 role 和 content 的消息对象数组调用 .stream()。更多信息请访问 .stream() 参考。

配置选项
配置选项的直接链接

MastraClient 接受 retries、backoffMs 和 headers 等可选参数来控制请求行为。这些参数适用于控制重试行为和包含诊断元数据。

lib/mastra-client.ts
import { MastraClient } from '@mastra/client-js'

export const mastraClient = new MastraClient({
retries: 3,
backoffMs: 300,
maxBackoffMs: 5000,
headers: {
'X-Development': 'true',
},
})

更多配置选项请访问 MastraClient。

当你的 UI 与 Mastra API 不在同一来源(不同主机、子域或端口,例如 Mastra Studio 在一个端口而自定义服务器在另一个端口)时,使用会话 cookie 对 Mastra API 调用进行身份验证。 在 MastraClient 中添加 credentials: 'include',使每个请求都携带用户登录后已有的 cookie。跳过此设置,即使浏览器中登录成功,你也经常会从 Mastra 收到 401 响应。

lib/mastra-client.ts
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'。仅当你需要 same-origin 或 omit 行为时才更改 credentials。

添加请求取消
添加请求取消的直接链接

MastraClient 使用标准 Node.js AbortSignal API 支持请求取消。适用于取消进行中的请求,例如用户中止操作或清理过期的网络调用。

向客户端构造函数传入 AbortSignal 即可在所有请求中启用取消。

lib/mastra-client.ts
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,
})

使用 AbortController
使用-abortcontroller的直接链接

调用 .abort() 会取消与该信号关联的所有进行中请求。

import { mastraClient, controller } from 'lib/mastra-client'

const handleAbort = () => {
controller.abort()
}

客户端工具
客户端工具的直接链接

使用 createTool() 函数在客户端应用中直接定义工具。通过 .generate() 或 .stream() 调用中的 clientTools 参数将它们传给 agent。

这使 agent 能够触发浏览器端功能,例如 DOM 操作、localStorage 访问或其他 Web API,从而在用户环境中而不是服务器上执行工具。

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)
}
}

客户端工具 agent
客户端工具 agent的直接链接

这是一个标准 Mastra agent,配置为返回十六进制颜色代码,旨在与上面定义的基于浏览器的客户端工具配合使用。

src/mastra/agents/color-agent
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的直接链接

服务器端 API 路由和无服务器函数(包括 actions)也可以使用 MastraClient。用法不变,不过你可能需要为客户端重新创建响应:

export async function action() {
const agent = mastraClient.getAgent('testAgent')

const stream = await agent.stream('Hello')

return new Response(stream.body)
}

最佳实践
最佳实践的直接链接

  1. 错误处理:在开发场景中使用错误处理。
  2. 环境变量:使用环境变量进行配置。
  3. 调试:在需要时启用详细的日志。
  4. 性能:使用可观测性跟踪应用性能和 trace。