Mastra Client SDK

Trust: ★★★☆☆ (0.90) · 0 validations · developer_reference

Published: 2026-05-10 · Source: crawler_authoritative

Tình huống

Guide for using the Mastra Client SDK to interact with Mastra Server from client environments, targeting TypeScript/JavaScript developers building applications with Mastra agents, tools, and workflows.

Insight

The Mastra Client SDK (@mastra/client-js) provides a type-safe interface for communicating with Mastra Server. It requires Node.js v22.13.0 or later and TypeScript v4.7+. The SDK is designed for browser environments using the native fetch API. Installation is via npm, pnpm, yarn, or bun using the @mastra/client-js@latest package. Initialize MastraClient with a baseUrl pointing to your Mastra server (default: http://localhost:4111). The SDK exposes core APIs for: Agents (generate responses and stream conversations), Memory (conversation threads and message history), Tools (execution and management), Workflows (trigger and track execution), Vectors (semantic search with embeddings), Responses (OpenAI-compatible agent-backed interface - experimental), Conversations (stored threads for Responses API - experimental), Logs, and Telemetry. Configuration options include retries, backoffMs, maxBackoffMs, and headers for controlling request behavior. The credentials: ‘include’ option is required for cross-origin requests when UI and Mastra API are on different origins to avoid 401 responses. The SDK supports request cancellation via the AbortSignal API passed to the constructor with an AbortController. Client tools can be defined using createTool() with inputSchema/outputSchema using Zod, enabling browser-side tool execution for DOM manipulation, localStorage access, or Web APIs.

Hành động

Install the SDK using npm install @mastra/client-js@latest (or pnpm/yarn/bun equivalent). Initialize MastraClient with your server base URL: new MastraClient({ baseUrl: process.env.MASTRA_API_URL || ‘http://localhost:4111’ }). For cross-origin requests, include credentials: ‘include’. Get an agent instance with mastraClient.getAgent(‘agentName’). Call generate() with a string prompt or message array to get responses: const response = await agent.generate(‘Hello’). For streaming, use agent.stream() with processDataStream() handling onTextPart callbacks. For request cancellation, create an AbortController and pass controller.signal to MastraClient constructor, then call controller.abort() to cancel ongoing requests. For client-side tools, use createTool() with id, description, inputSchema/outputSchema (Zod), and an execute function, then pass tools via clientTools parameter in generate() or stream() calls.

Kết quả

Returns type-safe responses from Mastra agents via generate() or streaming responses via stream(). Client tools execute in the browser environment, enabling DOM manipulation and Web API access. Request cancellation terminates in-flight requests. Cross-origin credential handling enables authenticated API calls across different origins.

Điều kiện áp dụng

Requires Node.js v22.13.0 or later; TypeScript v4.7+ recommended for type safety. Browser-native fetch API is used for HTTP requests.


Nội dung gốc (Original)

Mastra client SDK

The Mastra Client SDK provides a concise and type-safe interface for interacting with your Mastra Server from your client environment.

Prerequisites

Before you start local development, have:

  • Node.js v22.13.0 or later
  • TypeScript v4.7 or higher (if using TypeScript)
  • Your local Mastra server running (typically on port 4111)

Note: The Mastra Client SDK is designed for browser environments and uses the native fetch API for making HTTP requests to your Mastra server.

Installation

To use the Mastra Client SDK, install the required dependencies:

npm:

npm install @mastra/client-js@latest

pnpm:

pnpm add @mastra/client-js@latest

Yarn:

yarn add @mastra/client-js@latest

Bun:

bun add @mastra/client-js@latest

Initialize the 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',
})

Core APIs

The Mastra Client SDK exposes all resources served by the Mastra Server.

  • Agents: Generate responses and stream conversations.
  • Memory: Manage conversation threads and message history.
  • Tools: Executed and managed tools.
  • Workflows: Trigger workflows and track their execution.
  • Vectors: Use vector embeddings for semantic search.
  • Responses: Use Mastra Agents as a Responses API with an OpenAI-compatible, agent-backed interface. This API is currently experimental.
  • Conversations: Work with the stored conversation threads and item history behind Mastra Agents as a Responses API. This API is currently experimental.
  • Logs: View logs and debug system behavior.
  • Telemetry: View app performance and trace activity.

Generating responses

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

Info: You can also call .generate() with an array of message objects that include role and content. Visit the .generate() reference for more information.

Streaming responses

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

Info: You can also call .stream() with an array of message objects that include role and content. Visit the .stream() reference for more information.

Configuration options

MastraClient accepts optional parameters like retries, backoffMs, and headers to control request behavior. These parameters are useful for controlling retry behavior and including diagnostic metadata.

import { MastraClient } from '@mastra/client-js'
 
export const mastraClient = new MastraClient({
  retries: 3,
  backoffMs: 300,
  maxBackoffMs: 5000,
  headers: {
    'X-Development': 'true',
  },
})

Info: Visit MastraClient for more configuration options.

Credentials and session cookies

Authenticate Mastra API calls with session cookies when your UI and Mastra API aren’t on the same origin—different host, subdomain, or port (for example Mastra Studio on one port and a custom server on another). Add credentials: 'include' to MastraClient so each request carries the cookies the user already has after sign-in. Skip this and you will often get 401 responses from Mastra even though login succeeded in the browser.

import { MastraClient } from '@mastra/client-js'
 
export const mastraClient = new MastraClient({
  baseUrl: process.env.MASTRA_API_URL || 'http://localhost:4111',
  credentials: 'include',
})

Allow credentialed cross-origin requests on your server—see CORS: requests with credentials. You need a concrete Access-Control-Allow-Origin (not *) and Access-Control-Allow-Credentials: true, or the browser will block the call before it reaches Mastra.

Using @mastra/react? Wrap your app with MastraReactProvider, set baseUrl and apiPrefix to match your server, and rely on the default credentials: 'include'. Change credentials only when you want same-origin or omit behavior.

Adding request cancelling

MastraClient supports request cancellation using the standard Node.js AbortSignal API. Useful for canceling in-flight requests, such as when users abort an operation or to clean up stale network calls.

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

Using the AbortController

Calling .abort() will cancel any ongoing requests tied to that signal.

import { mastraClient, controller } from 'lib/mastra-client'
 
const handleAbort = () => {
  controller.abort()
}

Client tools

Define tools directly in client-side applications using the createTool() function. Pass them to agents via the clientTools parameter in .generate() or .stream() calls.

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

Client tool agent

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.4',
})

Use MastraClient on the server

You can also use MastraClient in server-side environments such as API routes, serverless functions, or actions. The usage remains the same, but you may need to recreate the response for your client:

export async function action() {
  const agent = mastraClient.getAgent('testAgent')
 
  const stream = await agent.stream('Hello')
 
  return new Response(stream.body)
}

Best practices

  1. Error Handling: Use error handling for development scenarios.
  2. Environment Variables: Use environment variables for configuration.
  3. Debugging: Enable detailed logging when needed.
  4. Performance: Track application performance, telemetry, and traces.

Liên kết

Xem thêm: