@mastra/client-js 1.2.0 → 1.2.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/_types/@internal_ai-sdk-v5/dist/index.d.ts +10 -7
  3. package/dist/client.d.ts +11 -1
  4. package/dist/client.d.ts.map +1 -1
  5. package/dist/docs/SKILL.md +32 -22
  6. package/dist/docs/{SOURCE_MAP.json → assets/SOURCE_MAP.json} +1 -1
  7. package/dist/docs/{server/07-auth0.md → references/docs-server-auth-auth0.md} +68 -79
  8. package/dist/docs/{server/03-clerk.md → references/docs-server-auth-clerk.md} +41 -52
  9. package/dist/docs/{server/05-firebase.md → references/docs-server-auth-firebase.md} +83 -97
  10. package/dist/docs/{server/02-jwt.md → references/docs-server-auth-jwt.md} +46 -35
  11. package/dist/docs/{server/04-supabase.md → references/docs-server-auth-supabase.md} +33 -44
  12. package/dist/docs/{server/06-workos.md → references/docs-server-auth-workos.md} +45 -56
  13. package/dist/docs/{server/01-mastra-client.md → references/docs-server-mastra-client.md} +32 -20
  14. package/dist/docs/{ai-sdk/01-reference.md → references/reference-ai-sdk-to-ai-sdk-stream.md} +27 -153
  15. package/dist/docs/references/reference-ai-sdk-to-ai-sdk-v4-messages.md +79 -0
  16. package/dist/docs/references/reference-ai-sdk-to-ai-sdk-v5-messages.md +73 -0
  17. package/dist/docs/references/reference-client-js-agents.md +438 -0
  18. package/dist/docs/references/reference-client-js-error-handling.md +16 -0
  19. package/dist/docs/references/reference-client-js-logs.md +24 -0
  20. package/dist/docs/references/reference-client-js-mastra-client.md +63 -0
  21. package/dist/docs/references/reference-client-js-memory.md +225 -0
  22. package/dist/docs/references/reference-client-js-observability.md +72 -0
  23. package/dist/docs/references/reference-client-js-telemetry.md +20 -0
  24. package/dist/docs/references/reference-client-js-tools.md +44 -0
  25. package/dist/docs/references/reference-client-js-vectors.md +79 -0
  26. package/dist/docs/references/reference-client-js-workflows.md +199 -0
  27. package/dist/index.cjs +18 -1
  28. package/dist/index.cjs.map +1 -1
  29. package/dist/index.js +18 -1
  30. package/dist/index.js.map +1 -1
  31. package/dist/types.d.ts +158 -27
  32. package/dist/types.d.ts.map +1 -1
  33. package/package.json +7 -7
  34. package/dist/docs/README.md +0 -33
  35. package/dist/docs/client-js/01-reference.md +0 -1180
@@ -0,0 +1,73 @@
1
+ # toAISdkV5Messages()
2
+
3
+ Converts messages from various input formats to AI SDK V5 (and later) UI message format. This function accepts messages in multiple formats (strings, AI SDK V4/V5 messages, Mastra DB messages, etc.) and normalizes them to the AI SDK V5+ `UIMessage` format, which is suitable for use with AI SDK UI components like `useChat()`.
4
+
5
+ ## Usage example
6
+
7
+ ```typescript
8
+ import { toAISdkV5Messages } from "@mastra/ai-sdk/ui";
9
+ import { useChat } from "ai/react";
10
+
11
+ // Stored messages from your database, memory or API
12
+ const storedMessages = [
13
+ { id: "1", role: "user", content: "Hello", parts: [{ type: "text", text: "Hello" }] },
14
+ { id: "2", role: "assistant", content: "Hi there!", parts: [{ type: "text", text: "Hi there!" }] }
15
+ ];
16
+
17
+ export default function Chat() {
18
+ const { messages } = useChat({
19
+ initialMessages: toAISdkV5Messages(storedMessages)
20
+ });
21
+
22
+ return (
23
+ <div>
24
+ {messages.map((message) => (
25
+ <div key={message.id}>
26
+ {message.role}: {message.parts.map(part =>
27
+ part.type === "text" ? part.text : null
28
+ )}
29
+ </div>
30
+ ))}
31
+ </div>
32
+ );
33
+ }
34
+ ```
35
+
36
+ ## Parameters
37
+
38
+ **messages:** (`MessageListInput`): Messages to convert. Can be a string, array of strings, a single message object, or an array of message objects in any supported format.
39
+
40
+ ## Returns
41
+
42
+ Returns an array of AI SDK V5+ `UIMessage` objects with the following structure:
43
+
44
+ **id:** (`string`): Unique message identifier.
45
+
46
+ **role:** (`'user' | 'assistant' | 'system'`): The role of the message sender.
47
+
48
+ **parts:** (`UIMessagePart[]`): Array of UI parts including text, tool results, files, reasoning, sources, and step markers.
49
+
50
+ **metadata?:** (`Record<string, unknown>`): Optional metadata including createdAt, threadId, resourceId, and custom fields.
51
+
52
+ ## Examples
53
+
54
+ ### Converting simple text messages
55
+
56
+ ```typescript
57
+ import { toAISdkV5Messages } from "@mastra/ai-sdk/ui";
58
+
59
+ const messages = toAISdkV5Messages(["Hello", "How can I help you today?"]);
60
+ // Returns array of UIMessage objects with user role
61
+ ```
62
+
63
+ ### Loading messages with Mastra client
64
+
65
+ ```typescript
66
+ import { MastraClient } from "@mastra/client-js";
67
+ import { toAISdkV5Messages } from "@mastra/ai-sdk/ui";
68
+
69
+ const client = new MastraClient();
70
+
71
+ const { messages } = await client.listThreadMessages("thread-id", { agentId: "myAgent" });
72
+ const uiMessages = toAISdkV5Messages(messages);
73
+ ```
@@ -0,0 +1,438 @@
1
+ # Agents API
2
+
3
+ The Agents API provides methods to interact with Mastra AI agents, including generating responses, streaming interactions, and managing agent tools.
4
+
5
+ ## Getting All Agents
6
+
7
+ Retrieve a list of all available agents:
8
+
9
+ ```typescript
10
+ const agents = await mastraClient.listAgents();
11
+ ```
12
+
13
+ Returns a record of agent IDs to their serialized agent configurations.
14
+
15
+ ## Working with a Specific Agent
16
+
17
+ Get an instance of a specific agent by its ID:
18
+
19
+ ```typescript
20
+ export const myAgent = new Agent({
21
+ id: "my-agent",
22
+ });
23
+ ```
24
+
25
+ ```typescript
26
+ const agent = mastraClient.getAgent("my-agent");
27
+ ```
28
+
29
+ ## Agent Methods
30
+
31
+ ### details()
32
+
33
+ Retrieve detailed information about an agent:
34
+
35
+ ```typescript
36
+ const details = await agent.details();
37
+ ```
38
+
39
+ ### generate()
40
+
41
+ Generate a response from the agent:
42
+
43
+ ```typescript
44
+ const response = await agent.generate(
45
+ [
46
+ {
47
+ role: "user",
48
+ content: "Hello, how are you?",
49
+ },
50
+ ],
51
+ {
52
+ memory: {
53
+ thread: "thread-abc", // Optional: Thread ID for conversation context
54
+ resource: "user-123", // Optional: Resource ID
55
+ },
56
+ structuredOutput: {} // Optional: Structured Output configuration
57
+ }
58
+ );
59
+ ```
60
+
61
+ You can also use the simplified string format with memory options:
62
+
63
+ ```typescript
64
+ const response = await agent.generate("Hello, how are you?", {
65
+ memory: {
66
+ thread: "thread-1",
67
+ resource: "resource-1",
68
+ },
69
+ });
70
+ ```
71
+
72
+ ### stream()
73
+
74
+ Stream responses from the agent for real-time interactions:
75
+
76
+ ```typescript
77
+ const response = await agent.stream("Tell me a story");
78
+
79
+ // Process data stream with the processDataStream util
80
+ response.processDataStream({
81
+ onChunk: async (chunk) => {
82
+ console.log(chunk);
83
+ },
84
+ });
85
+ ```
86
+
87
+ You can also use the simplified string format with memory options:
88
+
89
+ ```typescript
90
+ const response = await agent.stream("Tell me a story", {
91
+ memory: {
92
+ thread: "thread-1",
93
+ resource: "resource-1",
94
+ },
95
+ clientTools: { colorChangeTool },
96
+ });
97
+
98
+ response.processDataStream({
99
+ onChunk: async (chunk) => {
100
+ if (chunk.type === "text-delta") {
101
+ console.log(chunk.payload.text);
102
+ }
103
+ },
104
+ });
105
+ ```
106
+
107
+ You can also read from response body directly:
108
+
109
+ ```typescript
110
+ const reader = response.body.getReader();
111
+ while (true) {
112
+ const { done, value } = await reader.read();
113
+ if (done) break;
114
+ console.log(new TextDecoder().decode(value));
115
+ }
116
+ ```
117
+
118
+ #### AI SDK compatible format
119
+
120
+ To stream AI SDK-formatted parts on the client from an `agent.stream(...)` response, wrap `response.processDataStream` into a `ReadableStream<ChunkType>` and use `toAISdkStream`:
121
+
122
+ ```typescript
123
+ import { createUIMessageStream } from "ai";
124
+ import { toAISdkStream } from "@mastra/ai-sdk";
125
+ import type { ChunkType, MastraModelOutput } from "@mastra/core/stream";
126
+
127
+ const response = await agent.stream("Tell me a story");
128
+
129
+ const chunkStream: ReadableStream<ChunkType> = new ReadableStream<ChunkType>({
130
+ start(controller) {
131
+ response
132
+ .processDataStream({
133
+ onChunk: async (chunk) => controller.enqueue(chunk as ChunkType),
134
+ })
135
+ .finally(() => controller.close());
136
+ },
137
+ });
138
+
139
+ const uiMessageStream = createUIMessageStream({
140
+ execute: async ({ writer }) => {
141
+ for await (const part of toAISdkStream(
142
+ chunkStream as unknown as MastraModelOutput,
143
+ { from: "agent" },
144
+ )) {
145
+ writer.write(part);
146
+ }
147
+ },
148
+ });
149
+
150
+ for await (const part of uiMessageStream) {
151
+ console.log(part);
152
+ }
153
+ ```
154
+
155
+ ### getTool()
156
+
157
+ Retrieve information about a specific tool available to the agent:
158
+
159
+ ```typescript
160
+ const tool = await agent.getTool("tool-id");
161
+ ```
162
+
163
+ ### executeTool()
164
+
165
+ Execute a specific tool for the agent:
166
+
167
+ ```typescript
168
+ const result = await agent.executeTool("tool-id", {
169
+ data: { input: "value" },
170
+ });
171
+ ```
172
+
173
+ ### network()
174
+
175
+ Stream responses from an agent network for multi-agent interactions:
176
+
177
+ ```typescript
178
+ const response = await agent.network("Research this topic and write a summary");
179
+
180
+ response.processDataStream({
181
+ onChunk: async (chunk) => {
182
+ console.log(chunk);
183
+ },
184
+ });
185
+ ```
186
+
187
+ ### approveToolCall()
188
+
189
+ Approve a pending tool call that requires human confirmation:
190
+
191
+ ```typescript
192
+ const response = await agent.approveToolCall({
193
+ runId: "run-123",
194
+ toolCallId: "tool-call-456",
195
+ });
196
+
197
+ response.processDataStream({
198
+ onChunk: async (chunk) => {
199
+ console.log(chunk);
200
+ },
201
+ });
202
+ ```
203
+
204
+ ### declineToolCall()
205
+
206
+ Decline a pending tool call that requires human confirmation:
207
+
208
+ ```typescript
209
+ const response = await agent.declineToolCall({
210
+ runId: "run-123",
211
+ toolCallId: "tool-call-456",
212
+ });
213
+
214
+ response.processDataStream({
215
+ onChunk: async (chunk) => {
216
+ console.log(chunk);
217
+ },
218
+ });
219
+ ```
220
+
221
+ ### approveToolCallGenerate()
222
+
223
+ Approve a pending tool call when using `generate()` (non-streaming). Returns the complete response:
224
+
225
+ ```typescript
226
+ const output = await agent.generate("Find user John", {
227
+ requireToolApproval: true,
228
+ });
229
+
230
+ if (output.finishReason === "suspended") {
231
+ const result = await agent.approveToolCallGenerate({
232
+ runId: output.runId,
233
+ toolCallId: output.suspendPayload.toolCallId,
234
+ });
235
+
236
+ console.log(result.text);
237
+ }
238
+ ```
239
+
240
+ ### declineToolCallGenerate()
241
+
242
+ Decline a pending tool call when using `generate()` (non-streaming). Returns the complete response:
243
+
244
+ ```typescript
245
+ const output = await agent.generate("Find user John", {
246
+ requireToolApproval: true,
247
+ });
248
+
249
+ if (output.finishReason === "suspended") {
250
+ const result = await agent.declineToolCallGenerate({
251
+ runId: output.runId,
252
+ toolCallId: output.suspendPayload.toolCallId,
253
+ });
254
+
255
+ console.log(result.text);
256
+ }
257
+ ```
258
+
259
+ ## Client Tools
260
+
261
+ Client-side tools allow you to execute custom functions on the client side when the agent requests them.
262
+
263
+ ```typescript
264
+ import { createTool } from "@mastra/client-js";
265
+ import { z } from "zod";
266
+
267
+ const colorChangeTool = createTool({
268
+ id: "changeColor",
269
+ description: "Changes the background color",
270
+ inputSchema: z.object({
271
+ color: z.string(),
272
+ }),
273
+ execute: async (inputData) => {
274
+ document.body.style.backgroundColor = inputData.color;
275
+ return { success: true };
276
+ },
277
+ });
278
+
279
+ // Use with generate
280
+ const response = await agent.generate("Change the background to blue", {
281
+ clientTools: { colorChangeTool },
282
+ });
283
+
284
+ // Use with stream
285
+ const response = await agent.stream("Tell me a story", {
286
+ memory: {
287
+ thread: "thread-1",
288
+ resource: "resource-1",
289
+ },
290
+ clientTools: { colorChangeTool },
291
+ });
292
+
293
+ response.processDataStream({
294
+ onChunk: async (chunk) => {
295
+ if (chunk.type === "text-delta") {
296
+ console.log(chunk.payload.text);
297
+ } else if (chunk.type === "tool-call") {
298
+ console.log(
299
+ `calling tool ${chunk.payload.toolName} with args ${JSON.stringify(
300
+ chunk.payload.args,
301
+ null,
302
+ 2
303
+ )}`
304
+ );
305
+ }
306
+ },
307
+ });
308
+ ```
309
+
310
+ ## Stored Agents
311
+
312
+ Stored agents are agent configurations stored in a database that can be created, updated, and deleted at runtime. They reference primitives (tools, workflows, other agents, memory, scorers) by key, which are resolved from the Mastra registry when the agent is instantiated.
313
+
314
+ ### listStoredAgents()
315
+
316
+ Retrieve a paginated list of all stored agents:
317
+
318
+ ```typescript
319
+ const result = await mastraClient.listStoredAgents();
320
+ console.log(result.agents); // Array of stored agents
321
+ console.log(result.total); // Total count
322
+ ```
323
+
324
+ With pagination and ordering:
325
+
326
+ ```typescript
327
+ const result = await mastraClient.listStoredAgents({
328
+ page: 0,
329
+ perPage: 20,
330
+ orderBy: {
331
+ field: "createdAt",
332
+ direction: "DESC",
333
+ },
334
+ });
335
+ ```
336
+
337
+ ### createStoredAgent()
338
+
339
+ Create a new stored agent:
340
+
341
+ ```typescript
342
+ const agent = await mastraClient.createStoredAgent({
343
+ id: "my-agent",
344
+ name: "My Assistant",
345
+ instructions: "You are a helpful assistant.",
346
+ model: {
347
+ provider: "openai",
348
+ name: "gpt-4",
349
+ },
350
+ });
351
+ ```
352
+
353
+ With all options:
354
+
355
+ ```typescript
356
+ const agent = await mastraClient.createStoredAgent({
357
+ id: "full-agent",
358
+ name: "Full Agent",
359
+ description: "A fully configured agent",
360
+ instructions: "You are a helpful assistant.",
361
+ model: {
362
+ provider: "openai",
363
+ name: "gpt-4",
364
+ },
365
+ tools: ["calculator", "weather"],
366
+ workflows: ["data-processing"],
367
+ agents: ["sub-agent-1"],
368
+ memory: "my-memory",
369
+ scorers: {
370
+ "quality-scorer": {
371
+ sampling: { type: "ratio", rate: 0.1 },
372
+ },
373
+ },
374
+ defaultOptions: {
375
+ maxSteps: 10,
376
+ },
377
+ metadata: {
378
+ version: "1.0",
379
+ team: "engineering",
380
+ },
381
+ });
382
+ ```
383
+
384
+ ### getStoredAgent()
385
+
386
+ Get an instance of a specific stored agent:
387
+
388
+ ```typescript
389
+ const storedAgent = mastraClient.getStoredAgent("my-agent");
390
+ ```
391
+
392
+ ## Stored Agent Methods
393
+
394
+ ### details()
395
+
396
+ Retrieve the stored agent configuration:
397
+
398
+ ```typescript
399
+ const details = await storedAgent.details();
400
+ console.log(details.name);
401
+ console.log(details.instructions);
402
+ console.log(details.model);
403
+ ```
404
+
405
+ ### update()
406
+
407
+ Update specific fields of a stored agent. All fields are optional:
408
+
409
+ ```typescript
410
+ const updated = await storedAgent.update({
411
+ name: "Updated Agent Name",
412
+ instructions: "New instructions for the agent.",
413
+ });
414
+ ```
415
+
416
+ ```typescript
417
+ // Update just the tools
418
+ await storedAgent.update({
419
+ tools: ["new-tool-1", "new-tool-2"],
420
+ });
421
+
422
+ // Update metadata
423
+ await storedAgent.update({
424
+ metadata: {
425
+ version: "2.0",
426
+ lastModifiedBy: "admin",
427
+ },
428
+ });
429
+ ```
430
+
431
+ ### delete()
432
+
433
+ Delete a stored agent:
434
+
435
+ ```typescript
436
+ const result = await storedAgent.delete();
437
+ console.log(result.success); // true
438
+ ```
@@ -0,0 +1,16 @@
1
+ # Error Handling
2
+
3
+ The Mastra Client SDK includes built-in retry mechanism and error handling capabilities.
4
+
5
+ ## Error Handling
6
+
7
+ All API methods can throw errors that you can catch and handle:
8
+
9
+ ```typescript
10
+ try {
11
+ const agent = mastraClient.getAgent("agent-id");
12
+ const response = await agent.generate("Hello");
13
+ } catch (error) {
14
+ console.error("An error occurred:", error.message);
15
+ }
16
+ ```
@@ -0,0 +1,24 @@
1
+ # Logs API
2
+
3
+ The Logs API provides methods to access and query system logs and debugging information in Mastra.
4
+
5
+ ## Getting Logs
6
+
7
+ Retrieve system logs with optional filtering:
8
+
9
+ ```typescript
10
+ const logs = await mastraClient.listLogs({
11
+ transportId: "transport-1",
12
+ });
13
+ ```
14
+
15
+ ## Getting Logs for a Specific Run
16
+
17
+ Retrieve logs for a specific execution run:
18
+
19
+ ```typescript
20
+ const runLogs = await mastraClient.getLogForRun({
21
+ runId: "run-1",
22
+ transportId: "transport-1",
23
+ });
24
+ ```
@@ -0,0 +1,63 @@
1
+ # Mastra Client SDK
2
+
3
+ The Mastra Client SDK provides a simple and type-safe interface for interacting with your [Mastra Server](https://mastra.ai/docs/deployment/mastra-server) from your client environment.
4
+
5
+ ## Usage example
6
+
7
+ ```typescript
8
+ import { MastraClient } from "@mastra/client-js";
9
+
10
+ export const mastraClient = new MastraClient({
11
+ baseUrl: "http://localhost:4111/",
12
+ });
13
+ ```
14
+
15
+ ## Parameters
16
+
17
+ **baseUrl:** (`string`): The base URL for the Mastra API. All requests will be sent relative to this URL.
18
+
19
+ **retries?:** (`number`): The number of times a request will be retried on failure before throwing an error. (Default: `3`)
20
+
21
+ **backoffMs?:** (`number`): The initial delay in milliseconds before retrying a failed request. This value is doubled with each retry (exponential backoff). (Default: `300`)
22
+
23
+ **maxBackoffMs?:** (`number`): The maximum backoff time in milliseconds. Prevents retries from waiting too long between attempts. (Default: `5000`)
24
+
25
+ **headers?:** (`Record<string, string>`): An object containing custom HTTP headers to include with every request.
26
+
27
+ **credentials?:** (`"omit" | "same-origin" | "include"`): Credentials mode for requests. See https\://developer.mozilla.org/en-US/docs/Web/API/Request/credentials for more info.
28
+
29
+ ## Methods
30
+
31
+ **listAgents():** (`Promise<Record<string, GetAgentResponse>>`): Returns all available agent instances.
32
+
33
+ **getAgent(agentId):** (`Agent`): Retrieves a specific agent instance by ID.
34
+
35
+ **getMemoryThreads(params):** (`Promise<StorageThreadType[]>`): Retrieves memory threads for the specified resource and agent. Requires a \`resourceId\` and an \`agentId\`.
36
+
37
+ **createMemoryThread(params):** (`Promise<MemoryThread>`): Creates a new memory thread with the given parameters.
38
+
39
+ **getMemoryThread({ threadId, agentId }):** (`MemoryThread`): Fetches a specific memory thread by ID.
40
+
41
+ **saveMessageToMemory(params):** (`Promise<{ messages: (MastraMessageV1 | MastraDBMessage)[] }>`): Saves one or more messages to the memory system. Returns the saved messages.
42
+
43
+ **getMemoryStatus():** (`Promise<MemoryStatus>`): Returns the current status of the memory system.
44
+
45
+ **listTools():** (`Record<string, Tool>`): Returns all available tools.
46
+
47
+ **getTool(toolId):** (`Tool`): Retrieves a specific tool instance by ID.
48
+
49
+ **listWorkflows():** (`Record<string, Workflow>`): Returns all available workflow instances.
50
+
51
+ **getWorkflow(workflowId):** (`Workflow`): Retrieves a specific workflow instance by ID.
52
+
53
+ **getVector(vectorName):** (`MastraVector`): Returns a vector store instance by name.
54
+
55
+ **listLogs(params):** (`Promise<LogEntry[]>`): Fetches system logs matching the provided filters.
56
+
57
+ **getLog(params):** (`Promise<LogEntry>`): Retrieves a specific log entry by ID or filter.
58
+
59
+ **listLogTransports():** (`string[]`): Returns the list of configured log transport types.
60
+
61
+ **getTrace(traceId):** (`Promise<TraceRecord>`): Retrieves a specific trace by ID, including all its spans and details.
62
+
63
+ **getTraces(params):** (`Promise<GetTracesResponse>`): Retrieves paginated list of trace root spans with optional filtering. Use getTrace() to get complete traces with all spans.