mastra-client-sdk
Skill2 starsChanged 29 days agoApache-2.0View on GitHub
Call a running Mastra server from a browser, a frontend framework, or another backend with MastraClient from @mastra/client-js: agents (generate, stream, processDataStream, client tools, tool approval), workflows (createRun, startAsync, stream, resume), memory threads and messages, tools, vectors, logs, traces and feedback, datasets and experiments, the OpenAI-compatible Responses and Conversations APIs, and agent controller sessions. Use this skill whenever the user wants to talk to Mastra over HTTP instead of importing the mastra instance, pass auth headers or cookies, cancel requests, retry, or render streamed chunks in a UI. Triggers on MastraClient, @mastra/client-js, mastraClient.getAgent, getWorkflow, createRun, startAsync, processDataStream, clientTools, approveToolCall, listMemoryThreads, getMemoryThread, client.responses.create, client.conversations, getAgentController, credentials include, MastraClientError. Also triggers when a frontend gets 401 or CORS errors calling Mastra.
- Reads credentials
In this repository46 other files it gives its agents.
- mastra-a2a-acpSkill
- mastra-agent-approval-hitlSkill
- mastra-agentic-uiSkill
- mastra-agent-skillsSkill
- mastra-agentsSkill
- mastra-authSkill
- mastra-browserSkill
- mastra-build-playbookSkill
- mastra-channelsSkill
- mastra-classifierSkill
- mastra-cli-apiSkill
- mastra-datasets-experimentsSkill
- mastra-deploymentSkill
- mastra-evalsSkill
- mastra-file-based-agentsSkill
- mastra-framework-integrationSkill
- mastra-guideSkill
- mastra-harnessSkill
- mastra-knowledgeSkill
- mastra-mcpSkill
- mastra-memorySkill
- mastra-migrationsSkill
- mastra-modelsSkill
- mastra-multi-agentSkill
- mastra-observabilitySkill
- mastra-observational-memorySkill
- mastra-platformSkill
- mastra-processors-guardrailsSkill
- mastra-project-setupSkill
- mastra-ragSkill
- mastra-schedulesSkill
- mastra-semantic-recallSkill
- mastra-serverSkill
- mastra-signalsSkill
- mastra-storageSkill
- mastra-streamingSkill
- mastra-structured-outputSkill
- mastra-studio-editorSkill
- mastra-tool-integrationsSkill
- mastra-toolsSkill
- mastra-troubleshootingSkill
- mastra-vector-storesSkill
- mastra-voiceSkill
- mastra-workflowsSkill
- mastra-workflow-suspend-resumeSkill
- mastra-workspace-sandboxSkill
The file
We split this skill into the rules it gives an agent
5 rules. About 0 are common, 0 are distinctive, and 5 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
5
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 14
Call agents, workflows, memory, and other resources on a Mastra server over HTTP with the type-safe MastraClient.
- Very specific: line 97
Verify the API: If node_modules/@mastra/client-js exists, read its dist/docs/ and type definitions.
- Very specific: line 101
Call resources by ID: Use the agent id or registration key the server knows.
- Very specific: line 102
Choose generate or stream: Use stream() plus processDataStream() for UIs.
- Very specific: line 157
Call sites that pass memory, requestContext, and abortSignal where relevant
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Mastra Client SDK
Call agents, workflows, memory, and other resources on a Mastra server over HTTP with the type-safe MastraClient.
When to use
- A frontend (React, Vue, Svelte, Angular, Electron) calls a separate Mastra server
- A backend service, serverless function, or script calls a deployed Mastra server
- Streaming agent output to a UI with
processDataStream() - Running browser-side tools (
clientTools) that the agent can call - Starting, streaming, resuming, or polling workflow runs remotely
- Managing memory threads and messages, or reading traces and logs from another process
- Using Mastra agents through the OpenAI-compatible Responses API
When NOT to use
- Code that runs in the same process as the
mastrainstance (callmastra.getAgentById()directly, seemastra-agents) useChat()and AI SDK UI rendering (usemastra-agentic-ui)- Defining server routes, middleware, or CORS (use
mastra-server) - Choosing and configuring an auth provider (use
mastra-auth) - Shell calls to the API (use
mastra-cli-api) - Workflow suspend and resume design (use
mastra-workflow-suspend-resume) - Tool approval design on the agent side (use
mastra-agent-approval-hitl)
Required inputs
- The server URL (
MASTRA_API_URL, defaulthttp://localhost:4111) and any custom API prefix - How the caller authenticates: bearer token header, session cookie, or none
- Which resources it calls: agent IDs, workflow IDs, thread and resource IDs
- Whether output is streamed to a UI or awaited as a whole
- Whether the client runs in a browser (CORS, cookies) or on a server
The framework: one client, resource handles
MastraClient wraps the server's REST API. Create one instance per app, then get lightweight handles for each resource. Handles do no network work until you call a method.
// lib/mastra-client.ts
import { MastraClient } from '@mastra/client-js'
export const mastraClient = new MastraClient({
baseUrl: process.env.MASTRA_API_URL || 'http://localhost:4111',
})import { mastraClient } from './lib/mastra-client'
const agent = mastraClient.getAgent('weather-agent')
const response = await agent.generate('What is the weather in London?', {
memory: { thread: 'thread-1', resource: 'user-123' },
})
console.log(response.text)
const stream = await agent.stream('Tell me a story')
await stream.processDataStream({
onChunk: async chunk => {
if (chunk.type === 'text-delta') console.log(chunk.payload.text)
},
})| Handle | Get it with | Main methods |
| Agent | getAgent(id) | details, generate, stream, sendMessage, subscribeToThread, approveToolCall, declineToolCall, resumeStream, listSuspendedRuns |
| Workflow | getWorkflow(id) | details, createRun then start, startAsync, stream, resume, resumeAsync, cancel; runById |
| Memory thread | getMemoryThread({ threadId, agentId }) | get, update, delete, clone, listMessages, deleteMessages |
| Tool | getTool(id) | details, execute({ args }) |
| Vector | getVector(name) | createIndex, upsert, query, getIndexes, delete |
| Responses | client.responses | create, stream, retrieve, delete |
| Agent controller | getAgentController(key).session(id) | create, subscribe, sendMessage, approveTool, state |
Top-level methods cover listing (listAgents, listWorkflows, listTools), memory (listMemoryThreads, createMemoryThread, saveMessageToMemory), logs, traces, scores, feedback, and datasets.
Workflow
- Verify the API. If
node_modules/@mastra/client-jsexists, read itsdist/docs/and type definitions. Otherwise fetchhttps://mastra.ai/docs/server/mastra-client.mdandhttps://mastra.ai/reference/client-js/agents.md. Trust these over memory. - Install
@mastra/client-jsin the calling app (not necessarily the Mastra server project). - Create one client with
baseUrlfrom env. AddapiPrefixonly if the server changed it. - Add auth. Pass
headers: { Authorization: 'Bearer ...' }for tokens, orcredentials: 'include'for session cookies across origins (seemastra-auth). - Call resources by ID. Use the agent
idor registration key the server knows. Confirm withawait mastraClient.listAgents(). - Choose generate or stream. Use
stream()plusprocessDataStream()for UIs. Usegenerate()for jobs and scripts. - Pass request context with
RequestContextfrom@mastra/client-jsor a plain object. - Handle errors and cancellation. Wrap calls in
try/catch. PassabortSignalper call, or cancel the response body reader. - Test against
mastra devon port 4111, then against the deployed URL.
Deep dive: client tools and approvals
Client tools run in the browser. Define them with createTool from @mastra/client-js and pass them per call.
import { createTool } from '@mastra/client-js'
import { z } from 'zod'
const colorChangeTool = createTool({
id: 'changeColor',
description: 'Changes the background color',
inputSchema: z.object({ color: z.string() }),
execute: async inputData => {
document.body.style.backgroundColor = inputData.color
return { success: true }
},
})
const response = await mastraClient
.getAgent('color-agent')
.generate('Change the background to blue', { clientTools: { colorChangeTool } })For tools that need approval, list waiting runs with agent.listSuspendedRuns({ threadId, resourceId }). Resume a streamed run with approveToolCall({ runId, toolCallId }) or declineToolCall({ runId, toolCallId, reason }). Use approveToolCallGenerate() after a generate() call that finished with finishReason === 'suspended'.
Failure patterns
401from the browser after login. Cookies are not sent cross-origin. Setcredentials: 'include'and allow credentials with a concrete origin on the server.- CORS error before the request reaches Mastra. The server's
cors.origindoes not include the frontend origin, or uses'*'with credentials. - Wrong
baseUrlpath.baseUrlis the server origin (http://localhost:4111), not.../api. The client adds the prefix. - Agent not found. The ID does not match the server registry. Check
listAgents(). - Importing
RequestContextfrom@mastra/corein a frontend. Import it from@mastra/client-js, or pass a plain object. - Client tool never runs. It was defined with
@mastra/core/toolsor not passed inclientToolson that call. - Stream looks empty.
processDataStream()was not awaited or noonChunkhandler checkschunk.type. - Stopping the UI does not stop a durable run. Cancelling the body only disconnects. Call
agent.abortRun(runId)or pass a per-callabortSignal. - Sending full chat history with memory enabled. Send only the new message plus
memory.threadandmemory.resource. listWorkflowRunCounts()returns 404. The server predates the endpoint. Handle the error.
Output format
A finished client integration contains:
lib/mastra-client.ts(or similar) exporting one configuredMastraClientMASTRA_API_URLand any token variable in.env.example- Call sites that pass
memory,requestContext, andabortSignalwhere relevant - Error handling around every call
- A manual or automated check against a running server
Reference files
references/api.md- Constructor options and every resource method with parameters.references/examples.md- Streaming chat with memory, workflow run with resume, authenticated server-side call, Responses API.references/checklist.md- Client integration checklist.
Live docs
- https://mastra.ai/docs/server/mastra-client
- https://mastra.ai/reference/client-js/mastra-client
- https://mastra.ai/reference/client-js/agents
- https://mastra.ai/reference/client-js/workflows
- https://mastra.ai/reference/client-js/memory
- https://mastra.ai/reference/client-js/responses
- https://mastra.ai/reference/client-js/agent-controller
- https://mastra.ai/reference/client-js/error-handling
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

