Mastra 客户端 SDK
🌐 Mastra Client SDK
Mastra 客户端 SDK 提供了一个简单且类型安全的接口,用于从你的客户端环境与你的 Mastra 服务器 进行交互。
🌐 The Mastra Client SDK provides a simple and type-safe interface for interacting with your Mastra Server from your client environment.
先决条件Direct link to 先决条件
🌐 Prerequisites
为确保本地开发顺利,请确保你拥有:
🌐 To ensure smooth local development, make sure you have:
- Node.js
v22.13.0或更高版本 - TypeScript
v4.7或更高版本(如果使用 TypeScript) - 你本地的 Mastra 服务器正在运行(通常端口为
4111)
用法Direct link to 用法
🌐 Usage
Mastra 客户端 SDK 设计用于浏览器环境,并使用本地 fetch API 向你的 Mastra 服务器发起 HTTP 请求。
🌐 The Mastra Client SDK is designed for browser environments and uses the native fetch API for making HTTP requests to your Mastra server.
安装Direct link to 安装
🌐 Installation
要使用 Mastra 客户端 SDK,请安装所需的依赖:
🌐 To use the Mastra Client SDK, install the required dependencies:
- 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
初始化 MastraClientDirect link to initialize-the-mastraclient
🌐 Initialize the MastraClient
一旦使用 baseUrl 初始化,MastraClient 就会提供一个类型安全的接口,用于调用代理、工具和工作流。
🌐 Once initialized with a baseUrl, MastraClient exposes a type-safe interface for calling agents, tools, and workflows.
import { MastraClient } from "@mastra/client-js";
export const mastraClient = new MastraClient({
baseUrl: process.env.MASTRA_API_URL || "http://localhost:4111",
});
核心 APIDirect link to 核心 API
🌐 Core APIs
Mastra 客户端 SDK 提供 Mastra 服务器提供的所有资源
🌐 The Mastra Client SDK exposes all resources served by the Mastra Server
- 代理:生成回复并实时传输对话。
- 内存:管理对话线程和消息历史。
- 工具:执行和管理工具。
- 工作流程:触发工作流程并跟踪其执行情况。
- 向量:使用向量嵌入进行语义搜索。
- 日志:查看日志并调试系统行为。
- 遥测:监控应用性能并追踪活动。
生成回应Direct link to 生成回应
🌐 Generating responses
使用字符串提示调用 .generate():
🌐 Call .generate() with a string prompt:
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() 参考。
🌐 You can also call .generate() with an array of message objects that include role and content. Visit the .generate() reference for more information.
流式响应Direct link to 流式响应
🌐 Streaming responses
使用 .stream() 来对字符串提示进行实时响应:
🌐 Use .stream() for real-time responses with a string prompt:
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() 参考。
🌐 You can also call .stream() with an array of message objects that include role and content. Visit the .stream() reference for more information.
配置选项Direct link to 配置选项
🌐 Configuration options
MastraClient 接受可选参数,如 retries、backoffMs 和 headers,用于控制请求行为。这些参数对于控制重试行为和包含诊断元数据非常有用。
import { MastraClient } from "@mastra/client-js";
export const mastraClient = new MastraClient({
retries: 3,
backoffMs: 300,
maxBackoffMs: 5000,
headers: {
"X-Development": "true",
},
});
访问 MastraClient 以获取更多配置选项。
🌐 Visit MastraClient for more configuration options.
添加请求取消Direct link to 添加请求取消
🌐 Adding request cancelling
MastraClient 支持使用标准 Node.js AbortSignal API 取消请求。这对于取消正在进行的请求非常有用,例如当用户中止操作或清理过期的网络调用时。
向客户端构造函数传递 AbortSignal 以启用跨所有请求的取消操作。
🌐 Pass an AbortSignal to the client constructor to enable cancellation across all requests.
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,
});
使用 AbortControllerDirect link to using-the-abortcontroller
🌐 Using the AbortController
调用 .abort() 将取消与该信号关联的任何正在进行的请求。
🌐 Calling .abort() will cancel any ongoing requests tied to that signal.
import { mastraClient, controller } from "lib/mastra-client";
const handleAbort = () => {
controller.abort();
};
客户端工具Direct link to 客户端工具
🌐 Client tools
在客户端应用中使用 createTool() 函数直接定义工具。通过 .generate() 或 .stream() 调用中的 clientTools 参数将它们传递给代理。
🌐 Define tools directly in client-side applications using the createTool() function. Pass them to agents via the clientTools parameter in .generate() or .stream() calls.
这使得代理可以触发浏览器端功能,例如 DOM 操作、本地存储访问或其他 Web API,从而在用户的环境中执行工具,而不是在服务器上执行。
🌐 This lets agents trigger browser-side functionality such as DOM manipulation, local storage access, or other Web APIs, enabling tool execution in the user's environment rather than on the server.
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);
}
};
客户端工具的代理Direct link to 客户端工具的代理
🌐 Client tool's agent
这是一个标准的 Mastra 代理,配置为返回十六进制颜色代码,旨在与上述定义的基于浏览器的客户端工具配合使用。
🌐 This is a standard Mastra agent configured to return hex color codes, intended to work with the browser-based client tool defined above.
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.1",
});
服务器端环境Direct link to 服务器端环境
🌐 Server-side environments
你也可以在服务器端环境中使用 MastraClient,例如 API 路由、无服务器函数或操作。用法大致相同,但你可能需要重新生成发送给客户端的响应:
🌐 You can also use MastraClient in server-side environments such as API routes, serverless functions or actions. The usage will broadly remain the same but you may need to recreate the response to your client:
export async function action() {
const agent = mastraClient.getAgent("testAgent");
const stream = await agent.stream("Hello");
return new Response(stream.body);
}
最佳实践Direct link to 最佳实践
🌐 Best practices