@mastra/client-js 1.0.0-beta.9 → 1.0.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 (45) hide show
  1. package/CHANGELOG.md +1638 -0
  2. package/README.md +1 -3
  3. package/dist/_types/@ai-sdk_ui-utils/dist/index.d.ts +820 -0
  4. package/dist/_types/@internal_ai-sdk-v5/dist/index.d.ts +8511 -0
  5. package/dist/client.d.ts +56 -11
  6. package/dist/client.d.ts.map +1 -1
  7. package/dist/docs/README.md +33 -0
  8. package/dist/docs/SKILL.md +34 -0
  9. package/dist/docs/SOURCE_MAP.json +6 -0
  10. package/dist/docs/ai-sdk/01-reference.md +358 -0
  11. package/dist/docs/client-js/01-reference.md +1180 -0
  12. package/dist/docs/server/01-mastra-client.md +256 -0
  13. package/dist/docs/server/02-jwt.md +99 -0
  14. package/dist/docs/server/03-clerk.md +143 -0
  15. package/dist/docs/server/04-supabase.md +128 -0
  16. package/dist/docs/server/05-firebase.md +286 -0
  17. package/dist/docs/server/06-workos.md +201 -0
  18. package/dist/docs/server/07-auth0.md +233 -0
  19. package/dist/index.cjs +1690 -596
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.js +1688 -594
  22. package/dist/index.js.map +1 -1
  23. package/dist/resources/agent-builder.d.ts +10 -26
  24. package/dist/resources/agent-builder.d.ts.map +1 -1
  25. package/dist/resources/agent.d.ts +43 -8
  26. package/dist/resources/agent.d.ts.map +1 -1
  27. package/dist/resources/index.d.ts +1 -0
  28. package/dist/resources/index.d.ts.map +1 -1
  29. package/dist/resources/memory-thread.d.ts +18 -3
  30. package/dist/resources/memory-thread.d.ts.map +1 -1
  31. package/dist/resources/observability.d.ts +58 -15
  32. package/dist/resources/observability.d.ts.map +1 -1
  33. package/dist/resources/processor.d.ts +20 -0
  34. package/dist/resources/processor.d.ts.map +1 -0
  35. package/dist/resources/run.d.ts +210 -0
  36. package/dist/resources/run.d.ts.map +1 -0
  37. package/dist/resources/workflow.d.ts +19 -224
  38. package/dist/resources/workflow.d.ts.map +1 -1
  39. package/dist/tools.d.ts +2 -2
  40. package/dist/tools.d.ts.map +1 -1
  41. package/dist/types.d.ts +141 -36
  42. package/dist/types.d.ts.map +1 -1
  43. package/dist/utils/index.d.ts +26 -0
  44. package/dist/utils/index.d.ts.map +1 -1
  45. package/package.json +13 -12
@@ -0,0 +1,1180 @@
1
+ # Client js API Reference
2
+
3
+ > API reference for client js - 10 entries
4
+
5
+
6
+ ---
7
+
8
+ ## Reference: Agents API
9
+
10
+ > Learn how to interact with Mastra AI agents, including generating responses, streaming interactions, and managing agent tools using the client-js SDK.
11
+
12
+ The Agents API provides methods to interact with Mastra AI agents, including generating responses, streaming interactions, and managing agent tools.
13
+
14
+ ## Getting All Agents
15
+
16
+ Retrieve a list of all available agents:
17
+
18
+ ```typescript
19
+ const agents = await mastraClient.listAgents();
20
+ ```
21
+
22
+ Returns a record of agent IDs to their serialized agent configurations.
23
+
24
+ ## Working with a Specific Agent
25
+
26
+ Get an instance of a specific agent by its ID:
27
+
28
+ ```typescript title="src/mastra/agents/my-agent.ts"
29
+ export const myAgent = new Agent({
30
+ id: "my-agent",
31
+ });
32
+ ```
33
+
34
+ ```typescript
35
+ const agent = mastraClient.getAgent("my-agent");
36
+ ```
37
+
38
+ ## Agent Methods
39
+
40
+ ### details()
41
+
42
+ Retrieve detailed information about an agent:
43
+
44
+ ```typescript
45
+ const details = await agent.details();
46
+ ```
47
+
48
+ ### generate()
49
+
50
+ Generate a response from the agent:
51
+
52
+ ```typescript
53
+ const response = await agent.generate(
54
+ [
55
+ {
56
+ role: "user",
57
+ content: "Hello, how are you?",
58
+ },
59
+ ],
60
+ {
61
+ memory: {
62
+ thread: "thread-abc", // Optional: Thread ID for conversation context
63
+ resource: "user-123", // Optional: Resource ID
64
+ },
65
+ structuredOutput: {} // Optional: Structured Output configuration
66
+ }
67
+ );
68
+ ```
69
+
70
+ You can also use the simplified string format with memory options:
71
+
72
+ ```typescript
73
+ const response = await agent.generate("Hello, how are you?", {
74
+ memory: {
75
+ thread: "thread-1",
76
+ resource: "resource-1",
77
+ },
78
+ });
79
+ ```
80
+
81
+ ### stream()
82
+
83
+ Stream responses from the agent for real-time interactions:
84
+
85
+ ```typescript
86
+ const response = await agent.stream("Tell me a story");
87
+
88
+ // Process data stream with the processDataStream util
89
+ response.processDataStream({
90
+ onChunk: async (chunk) => {
91
+ console.log(chunk);
92
+ },
93
+ });
94
+ ```
95
+
96
+ You can also use the simplified string format with memory options:
97
+
98
+ ```typescript
99
+ const response = await agent.stream("Tell me a story", {
100
+ memory: {
101
+ thread: "thread-1",
102
+ resource: "resource-1",
103
+ },
104
+ clientTools: { colorChangeTool },
105
+ });
106
+
107
+ response.processDataStream({
108
+ onChunk: async (chunk) => {
109
+ if (chunk.type === "text-delta") {
110
+ console.log(chunk.payload.text);
111
+ }
112
+ },
113
+ });
114
+ ```
115
+
116
+ You can also read from response body directly:
117
+
118
+ ```typescript
119
+ const reader = response.body.getReader();
120
+ while (true) {
121
+ const { done, value } = await reader.read();
122
+ if (done) break;
123
+ console.log(new TextDecoder().decode(value));
124
+ }
125
+ ```
126
+
127
+ #### AI SDK compatible format
128
+
129
+ To stream AI SDK-formatted parts on the client from an `agent.stream(...)` response, wrap `response.processDataStream` into a `ReadableStream<ChunkType>` and use `toAISdkStream`:
130
+
131
+ ```typescript title="client-ai-sdk-transform.ts"
132
+ import { createUIMessageStream } from "ai";
133
+ import { toAISdkStream } from "@mastra/ai-sdk";
134
+ import type { ChunkType, MastraModelOutput } from "@mastra/core/stream";
135
+
136
+ const response = await agent.stream("Tell me a story");
137
+
138
+ const chunkStream: ReadableStream<ChunkType> = new ReadableStream<ChunkType>({
139
+ start(controller) {
140
+ response
141
+ .processDataStream({
142
+ onChunk: async (chunk) => controller.enqueue(chunk as ChunkType),
143
+ })
144
+ .finally(() => controller.close());
145
+ },
146
+ });
147
+
148
+ const uiMessageStream = createUIMessageStream({
149
+ execute: async ({ writer }) => {
150
+ for await (const part of toAISdkStream(
151
+ chunkStream as unknown as MastraModelOutput,
152
+ { from: "agent" },
153
+ )) {
154
+ writer.write(part);
155
+ }
156
+ },
157
+ });
158
+
159
+ for await (const part of uiMessageStream) {
160
+ console.log(part);
161
+ }
162
+ ```
163
+
164
+ ### getTool()
165
+
166
+ Retrieve information about a specific tool available to the agent:
167
+
168
+ ```typescript
169
+ const tool = await agent.getTool("tool-id");
170
+ ```
171
+
172
+ ### executeTool()
173
+
174
+ Execute a specific tool for the agent:
175
+
176
+ ```typescript
177
+ const result = await agent.executeTool("tool-id", {
178
+ data: { input: "value" },
179
+ });
180
+ ```
181
+
182
+ ### network()
183
+
184
+ Stream responses from an agent network for multi-agent interactions:
185
+
186
+ ```typescript
187
+ const response = await agent.network("Research this topic and write a summary");
188
+
189
+ response.processDataStream({
190
+ onChunk: async (chunk) => {
191
+ console.log(chunk);
192
+ },
193
+ });
194
+ ```
195
+
196
+ ### approveToolCall()
197
+
198
+ Approve a pending tool call that requires human confirmation:
199
+
200
+ ```typescript
201
+ const response = await agent.approveToolCall({
202
+ runId: "run-123",
203
+ toolCallId: "tool-call-456",
204
+ });
205
+
206
+ response.processDataStream({
207
+ onChunk: async (chunk) => {
208
+ console.log(chunk);
209
+ },
210
+ });
211
+ ```
212
+
213
+ ### declineToolCall()
214
+
215
+ Decline a pending tool call that requires human confirmation:
216
+
217
+ ```typescript
218
+ const response = await agent.declineToolCall({
219
+ runId: "run-123",
220
+ toolCallId: "tool-call-456",
221
+ });
222
+
223
+ response.processDataStream({
224
+ onChunk: async (chunk) => {
225
+ console.log(chunk);
226
+ },
227
+ });
228
+ ```
229
+
230
+ ### approveToolCallGenerate()
231
+
232
+ Approve a pending tool call when using `generate()` (non-streaming). Returns the complete response:
233
+
234
+ ```typescript
235
+ const output = await agent.generate("Find user John", {
236
+ requireToolApproval: true,
237
+ });
238
+
239
+ if (output.finishReason === "suspended") {
240
+ const result = await agent.approveToolCallGenerate({
241
+ runId: output.runId,
242
+ toolCallId: output.suspendPayload.toolCallId,
243
+ });
244
+
245
+ console.log(result.text);
246
+ }
247
+ ```
248
+
249
+ ### declineToolCallGenerate()
250
+
251
+ Decline a pending tool call when using `generate()` (non-streaming). Returns the complete response:
252
+
253
+ ```typescript
254
+ const output = await agent.generate("Find user John", {
255
+ requireToolApproval: true,
256
+ });
257
+
258
+ if (output.finishReason === "suspended") {
259
+ const result = await agent.declineToolCallGenerate({
260
+ runId: output.runId,
261
+ toolCallId: output.suspendPayload.toolCallId,
262
+ });
263
+
264
+ console.log(result.text);
265
+ }
266
+ ```
267
+
268
+ ## Client Tools
269
+
270
+ Client-side tools allow you to execute custom functions on the client side when the agent requests them.
271
+
272
+ ```typescript
273
+ import { createTool } from "@mastra/client-js";
274
+ import { z } from "zod";
275
+
276
+ const colorChangeTool = createTool({
277
+ id: "changeColor",
278
+ description: "Changes the background color",
279
+ inputSchema: z.object({
280
+ color: z.string(),
281
+ }),
282
+ execute: async (inputData) => {
283
+ document.body.style.backgroundColor = inputData.color;
284
+ return { success: true };
285
+ },
286
+ });
287
+
288
+ // Use with generate
289
+ const response = await agent.generate("Change the background to blue", {
290
+ clientTools: { colorChangeTool },
291
+ });
292
+
293
+ // Use with stream
294
+ const response = await agent.stream("Tell me a story", {
295
+ memory: {
296
+ thread: "thread-1",
297
+ resource: "resource-1",
298
+ },
299
+ clientTools: { colorChangeTool },
300
+ });
301
+
302
+ response.processDataStream({
303
+ onChunk: async (chunk) => {
304
+ if (chunk.type === "text-delta") {
305
+ console.log(chunk.payload.text);
306
+ } else if (chunk.type === "tool-call") {
307
+ console.log(
308
+ `calling tool ${chunk.payload.toolName} with args ${JSON.stringify(
309
+ chunk.payload.args,
310
+ null,
311
+ 2
312
+ )}`
313
+ );
314
+ }
315
+ },
316
+ });
317
+ ```
318
+
319
+ ## Stored Agents
320
+
321
+ 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.
322
+
323
+ ### listStoredAgents()
324
+
325
+ Retrieve a paginated list of all stored agents:
326
+
327
+ ```typescript
328
+ const result = await mastraClient.listStoredAgents();
329
+ console.log(result.agents); // Array of stored agents
330
+ console.log(result.total); // Total count
331
+ ```
332
+
333
+ With pagination and ordering:
334
+
335
+ ```typescript
336
+ const result = await mastraClient.listStoredAgents({
337
+ page: 0,
338
+ perPage: 20,
339
+ orderBy: {
340
+ field: "createdAt",
341
+ direction: "DESC",
342
+ },
343
+ });
344
+ ```
345
+
346
+ ### createStoredAgent()
347
+
348
+ Create a new stored agent:
349
+
350
+ ```typescript
351
+ const agent = await mastraClient.createStoredAgent({
352
+ id: "my-agent",
353
+ name: "My Assistant",
354
+ instructions: "You are a helpful assistant.",
355
+ model: {
356
+ provider: "openai",
357
+ name: "gpt-4",
358
+ },
359
+ });
360
+ ```
361
+
362
+ With all options:
363
+
364
+ ```typescript
365
+ const agent = await mastraClient.createStoredAgent({
366
+ id: "full-agent",
367
+ name: "Full Agent",
368
+ description: "A fully configured agent",
369
+ instructions: "You are a helpful assistant.",
370
+ model: {
371
+ provider: "openai",
372
+ name: "gpt-4",
373
+ },
374
+ tools: ["calculator", "weather"],
375
+ workflows: ["data-processing"],
376
+ agents: ["sub-agent-1"],
377
+ memory: "my-memory",
378
+ scorers: {
379
+ "quality-scorer": {
380
+ sampling: { type: "ratio", rate: 0.1 },
381
+ },
382
+ },
383
+ defaultOptions: {
384
+ maxSteps: 10,
385
+ },
386
+ metadata: {
387
+ version: "1.0",
388
+ team: "engineering",
389
+ },
390
+ });
391
+ ```
392
+
393
+ ### getStoredAgent()
394
+
395
+ Get an instance of a specific stored agent:
396
+
397
+ ```typescript
398
+ const storedAgent = mastraClient.getStoredAgent("my-agent");
399
+ ```
400
+
401
+ ## Stored Agent Methods
402
+
403
+ ### details()
404
+
405
+ Retrieve the stored agent configuration:
406
+
407
+ ```typescript
408
+ const details = await storedAgent.details();
409
+ console.log(details.name);
410
+ console.log(details.instructions);
411
+ console.log(details.model);
412
+ ```
413
+
414
+ ### update()
415
+
416
+ Update specific fields of a stored agent. All fields are optional:
417
+
418
+ ```typescript
419
+ const updated = await storedAgent.update({
420
+ name: "Updated Agent Name",
421
+ instructions: "New instructions for the agent.",
422
+ });
423
+ ```
424
+
425
+ ```typescript
426
+ // Update just the tools
427
+ await storedAgent.update({
428
+ tools: ["new-tool-1", "new-tool-2"],
429
+ });
430
+
431
+ // Update metadata
432
+ await storedAgent.update({
433
+ metadata: {
434
+ version: "2.0",
435
+ lastModifiedBy: "admin",
436
+ },
437
+ });
438
+ ```
439
+
440
+ ### delete()
441
+
442
+ Delete a stored agent:
443
+
444
+ ```typescript
445
+ const result = await storedAgent.delete();
446
+ console.log(result.success); // true
447
+ ```
448
+
449
+ ---
450
+
451
+ ## Reference: Error Handling
452
+
453
+ > Learn about the built-in retry mechanism and error handling capabilities in the Mastra client-js SDK.
454
+
455
+ The Mastra Client SDK includes built-in retry mechanism and error handling capabilities.
456
+
457
+ ## Error Handling
458
+
459
+ All API methods can throw errors that you can catch and handle:
460
+
461
+ ```typescript
462
+ try {
463
+ const agent = mastraClient.getAgent("agent-id");
464
+ const response = await agent.generate("Hello");
465
+ } catch (error) {
466
+ console.error("An error occurred:", error.message);
467
+ }
468
+ ```
469
+
470
+ ---
471
+
472
+ ## Reference: Logs API
473
+
474
+ > Learn how to access and query system logs and debugging information in Mastra using the client-js SDK.
475
+
476
+ The Logs API provides methods to access and query system logs and debugging information in Mastra.
477
+
478
+ ## Getting Logs
479
+
480
+ Retrieve system logs with optional filtering:
481
+
482
+ ```typescript
483
+ const logs = await mastraClient.listLogs({
484
+ transportId: "transport-1",
485
+ });
486
+ ```
487
+
488
+ ## Getting Logs for a Specific Run
489
+
490
+ Retrieve logs for a specific execution run:
491
+
492
+ ```typescript
493
+ const runLogs = await mastraClient.getLogForRun({
494
+ runId: "run-1",
495
+ transportId: "transport-1",
496
+ });
497
+ ```
498
+
499
+ ---
500
+
501
+ ## Reference: Mastra Client SDK
502
+
503
+ > Learn how to interact with Mastra using the client-js SDK.
504
+
505
+ The Mastra Client SDK provides a simple and type-safe interface for interacting with your [Mastra Server](https://mastra.ai/docs/v1/deployment/mastra-server) from your client environment.
506
+
507
+ ## Usage example
508
+
509
+ ```typescript title="lib/mastra/mastra-client.ts"
510
+ import { MastraClient } from "@mastra/client-js";
511
+
512
+ export const mastraClient = new MastraClient({
513
+ baseUrl: "http://localhost:4111/",
514
+ });
515
+ ```
516
+
517
+ ## Parameters
518
+
519
+ ## Methods
520
+
521
+ ---
522
+
523
+ ## Reference: Memory API
524
+
525
+ > Learn how to manage conversation threads and message history in Mastra using the client-js SDK.
526
+
527
+ The Memory API provides methods to manage conversation threads and message history in Mastra.
528
+
529
+ ### Get All Threads
530
+
531
+ Retrieve all memory threads for a specific resource:
532
+
533
+ ```typescript
534
+ const threads = await mastraClient.getMemoryThreads({
535
+ resourceId: "resource-1",
536
+ agentId: "agent-1", // Optional - can be omitted if storage is configured
537
+ });
538
+ ```
539
+
540
+ When `agentId` is omitted and storage is configured on the server, threads will be retrieved using storage directly. This is useful when multiple agents share the same threads (e.g., in workflows with multiple agent steps).
541
+
542
+ ### Create a New Thread
543
+
544
+ Create a new memory thread:
545
+
546
+ ```typescript
547
+ const thread = await mastraClient.createMemoryThread({
548
+ title: "New Conversation",
549
+ metadata: { category: "support" },
550
+ resourceId: "resource-1",
551
+ agentId: "agent-1",
552
+ });
553
+ ```
554
+
555
+ ### Working with a Specific Thread
556
+
557
+ Get an instance of a specific memory thread:
558
+
559
+ ```typescript
560
+ const thread = mastraClient.getMemoryThread({ threadId: "thread-id", agentId: "agent-id" });
561
+ ```
562
+
563
+ ## Thread Methods
564
+
565
+ ### Get Thread Details
566
+
567
+ Retrieve details about a specific thread:
568
+
569
+ ```typescript
570
+ const details = await thread.get();
571
+ ```
572
+
573
+ ### Update Thread
574
+
575
+ Update thread properties:
576
+
577
+ ```typescript
578
+ const updated = await thread.update({
579
+ title: "Updated Title",
580
+ metadata: { status: "resolved" },
581
+ resourceId: "resource-1",
582
+ });
583
+ ```
584
+
585
+ ### Delete Thread
586
+
587
+ Delete a thread and its messages:
588
+
589
+ ```typescript
590
+ await thread.delete();
591
+ ```
592
+
593
+ ### Clone Thread
594
+
595
+ Create a copy of a thread with all its messages:
596
+
597
+ ```typescript
598
+ const { thread: clonedThread, clonedMessages } = await thread.clone();
599
+ ```
600
+
601
+ Clone with options:
602
+
603
+ ```typescript
604
+ const { thread: clonedThread, clonedMessages } = await thread.clone({
605
+ newThreadId: "custom-clone-id",
606
+ title: "Cloned Conversation",
607
+ metadata: { branch: "experiment-1" },
608
+ options: {
609
+ messageLimit: 10, // Only clone last 10 messages
610
+ },
611
+ });
612
+ ```
613
+
614
+ Clone with message filtering:
615
+
616
+ ```typescript
617
+ const { thread: clonedThread } = await thread.clone({
618
+ options: {
619
+ messageFilter: {
620
+ startDate: new Date("2024-01-01"),
621
+ endDate: new Date("2024-01-31"),
622
+ },
623
+ },
624
+ });
625
+ ```
626
+
627
+ The clone response includes:
628
+ - `thread`: The newly created cloned thread with clone metadata
629
+ - `clonedMessages`: Array of the cloned messages with new IDs
630
+
631
+ ## Message Operations
632
+
633
+ ### Save Messages
634
+
635
+ Save messages to memory:
636
+
637
+ ```typescript
638
+ const result = await mastraClient.saveMessageToMemory({
639
+ messages: [
640
+ {
641
+ role: "user",
642
+ content: "Hello!",
643
+ id: "1",
644
+ threadId: "thread-1",
645
+ resourceId: "resource-1",
646
+ createdAt: new Date(),
647
+ format: 2,
648
+ },
649
+ ],
650
+ agentId: "agent-1",
651
+ });
652
+
653
+ // result.messages contains the saved messages
654
+ console.log(result.messages);
655
+ ```
656
+
657
+ ### Retrieve Thread Messages
658
+
659
+ Get messages associated with a memory thread:
660
+
661
+ ```typescript
662
+ // Get all messages in the thread (paginated)
663
+ const result = await thread.listMessages();
664
+ console.log(result.messages); // Array of messages
665
+ console.log(result.total); // Total count
666
+ console.log(result.hasMore); // Whether more pages exist
667
+
668
+ // Get messages with pagination
669
+ const result = await thread.listMessages({
670
+ page: 0,
671
+ perPage: 20
672
+ });
673
+
674
+ // Get messages with ordering
675
+ const result = await thread.listMessages({
676
+ orderBy: { field: 'createdAt', direction: 'ASC' }
677
+ });
678
+ ```
679
+
680
+ ### Delete Messages
681
+
682
+ Delete one or more messages from a thread:
683
+
684
+ ```typescript
685
+ // Delete a single message
686
+ const result = await thread.deleteMessages("message-id");
687
+
688
+ // Delete multiple messages
689
+ const result = await thread.deleteMessages([
690
+ "message-1",
691
+ "message-2",
692
+ "message-3",
693
+ ]);
694
+
695
+ // Returns: { success: true, message: "Message deleted successfully" }
696
+ ```
697
+
698
+ ## Working Memory
699
+
700
+ Working memory allows agents to maintain persistent information about users across interactions. It can be scoped to either a specific thread or across all threads for a resource (user).
701
+
702
+ ### Get Working Memory
703
+
704
+ Retrieve the current working memory for a thread:
705
+
706
+ ```typescript
707
+ const workingMemory = await mastraClient.getWorkingMemory({
708
+ agentId: "agent-1",
709
+ threadId: "thread-1",
710
+ resourceId: "user-123", // Optional, required for resource-scoped memory
711
+ });
712
+ ```
713
+
714
+ The response includes:
715
+ - `workingMemory`: The current working memory content (string or null)
716
+ - `source`: Whether the memory is from `"thread"` or `"resource"` scope
717
+ - `workingMemoryTemplate`: The template used for working memory (if configured)
718
+ - `threadExists`: Whether the thread exists
719
+
720
+ ### Update Working Memory
721
+
722
+ Update the working memory content for a thread:
723
+
724
+ ```typescript
725
+ await mastraClient.updateWorkingMemory({
726
+ agentId: "agent-1",
727
+ threadId: "thread-1",
728
+ workingMemory: `# User Profile
729
+ - Name: John Doe
730
+ - Location: New York
731
+ - Preferences: Prefers formal communication
732
+ `,
733
+ resourceId: "user-123", // Optional, required for resource-scoped memory
734
+ });
735
+
736
+ // Returns: { success: true }
737
+ ```
738
+
739
+ **Note:** For resource-scoped working memory, you must provide the `resourceId` parameter. This allows the memory to persist across all conversation threads for that user.
740
+
741
+ ### Get Memory Status
742
+
743
+ Check the status of the memory system:
744
+
745
+ ```typescript
746
+ const status = await mastraClient.getMemoryStatus("agent-id");
747
+ ```
748
+
749
+ ---
750
+
751
+ ## Reference: Observability API
752
+
753
+ > Learn how to retrieve traces, monitor application performance, and score traces using the client-js SDK.
754
+
755
+ The Observability API provides methods to retrieve traces, monitor your application's performance, and score traces for evaluation. This helps you understand how your AI agents and workflows are performing.
756
+
757
+ ## Getting a Specific Trace
758
+
759
+ Retrieve a specific trace by its ID, including all its spans and details:
760
+
761
+ ```typescript
762
+ const trace = await mastraClient.getTrace("trace-id-123");
763
+ ```
764
+
765
+ ## Getting Traces with Filtering
766
+
767
+ Retrieve a paginated list of trace root spans with optional filtering:
768
+
769
+ ```typescript
770
+ const traces = await mastraClient.getTraces({
771
+ pagination: {
772
+ page: 1,
773
+ perPage: 20,
774
+ dateRange: {
775
+ start: new Date("2024-01-01"),
776
+ end: new Date("2024-01-31"),
777
+ },
778
+ },
779
+ filters: {
780
+ name: "weather-agent", // Filter by trace name
781
+ spanType: "agent", // Filter by span type
782
+ entityId: "weather-agent-id", // Filter by entity ID
783
+ entityType: "agent", // Filter by entity type
784
+ },
785
+ });
786
+
787
+ console.log(`Found ${traces.spans.length} root spans`);
788
+ console.log(`Total pages: ${traces.pagination.totalPages}`);
789
+
790
+ // To get the complete trace with all spans, use getTrace
791
+ const completeTrace = await mastraClient.getTrace(traces.spans[0].traceId);
792
+ ```
793
+
794
+ ## Scoring Traces
795
+
796
+ Score specific traces using registered scorers for evaluation:
797
+
798
+ ```typescript
799
+ const result = await mastraClient.score({
800
+ scorerName: "answer-relevancy",
801
+ targets: [
802
+ { traceId: "trace-1", spanId: "span-1" }, // Score specific span
803
+ { traceId: "trace-2" }, // Score specific span which defaults to the parent span
804
+ ],
805
+ });
806
+ ```
807
+
808
+ ## Getting Scores by Span
809
+
810
+ Retrieve scores for a specific span within a trace:
811
+
812
+ ```typescript
813
+ const scores = await mastraClient.listScoresBySpan({
814
+ traceId: "trace-123",
815
+ spanId: "span-456",
816
+ page: 1,
817
+ perPage: 20,
818
+ });
819
+ ```
820
+
821
+ ## Related
822
+
823
+ - [Agents API](./agents) - Learn about agent interactions that generate traces
824
+ - [Workflows API](./workflows) - Understand workflow execution monitoring
825
+
826
+ ---
827
+
828
+ ## Reference: Telemetry API
829
+
830
+ > Learn how to retrieve and analyze traces from your Mastra application for monitoring and debugging using the client-js SDK.
831
+
832
+ The Telemetry API provides methods to retrieve and analyze traces from your Mastra application. This helps you monitor and debug your application's behavior and performance.
833
+
834
+ ## Getting Traces
835
+
836
+ Retrieve traces with optional filtering and pagination:
837
+
838
+ ```typescript
839
+ const telemetry = await mastraClient.getTelemetry({
840
+ name: "trace-name", // Optional: Filter by trace name
841
+ scope: "scope-name", // Optional: Filter by scope
842
+ page: 1, // Optional: Page number for pagination
843
+ perPage: 10, // Optional: Number of items per page
844
+ attribute: {
845
+ // Optional: Filter by custom attributes
846
+ key: "value",
847
+ },
848
+ });
849
+ ```
850
+
851
+ ---
852
+
853
+ ## Reference: Tools API
854
+
855
+ > Learn how to interact with and execute tools available in the Mastra platform using the client-js SDK.
856
+
857
+ The Tools API provides methods to interact with and execute tools available in the Mastra platform.
858
+
859
+ ## Getting All Tools
860
+
861
+ Retrieve a list of all available tools:
862
+
863
+ ```typescript
864
+ const tools = await mastraClient.listTools();
865
+ ```
866
+
867
+ ## Working with a Specific Tool
868
+
869
+ Get an instance of a specific tool:
870
+
871
+ ```typescript
872
+ const tool = mastraClient.getTool("tool-id");
873
+ ```
874
+
875
+ ## Tool Methods
876
+
877
+ ### Get Tool Details
878
+
879
+ Retrieve detailed information about a tool:
880
+
881
+ ```typescript
882
+ const details = await tool.details();
883
+ ```
884
+
885
+ ### Execute Tool
886
+
887
+ Execute a tool with specific arguments:
888
+
889
+ ```typescript
890
+ const result = await tool.execute({
891
+ args: {
892
+ param1: "value1",
893
+ param2: "value2",
894
+ },
895
+ threadId: "thread-1", // Optional: Thread context
896
+ resourceId: "resource-1", // Optional: Resource identifier
897
+ });
898
+ ```
899
+
900
+ ---
901
+
902
+ ## Reference: Vectors API
903
+
904
+ > Learn how to work with vector embeddings for semantic search and similarity matching in Mastra using the client-js SDK.
905
+
906
+ The Vectors API provides methods to work with vector embeddings for semantic search and similarity matching in Mastra.
907
+
908
+ ## Working with Vectors
909
+
910
+ Get an instance of a vector store:
911
+
912
+ ```typescript
913
+ const vector = mastraClient.getVector("vector-name");
914
+ ```
915
+
916
+ ## Vector Methods
917
+
918
+ ### Get Vector Index Details
919
+
920
+ Retrieve information about a specific vector index:
921
+
922
+ ```typescript
923
+ const details = await vector.details("index-name");
924
+ ```
925
+
926
+ ### Create Vector Index
927
+
928
+ Create a new vector index:
929
+
930
+ ```typescript
931
+ const result = await vector.createIndex({
932
+ indexName: "new-index",
933
+ dimension: 128,
934
+ metric: "cosine", // 'cosine', 'euclidean', or 'dotproduct'
935
+ });
936
+ ```
937
+
938
+ ### Upsert Vectors
939
+
940
+ Add or update vectors in an index:
941
+
942
+ ```typescript
943
+ const ids = await vector.upsert({
944
+ indexName: "my-index",
945
+ vectors: [
946
+ [0.1, 0.2, 0.3], // First vector
947
+ [0.4, 0.5, 0.6], // Second vector
948
+ ],
949
+ metadata: [{ label: "first" }, { label: "second" }],
950
+ ids: ["id1", "id2"], // Optional: Custom IDs
951
+ });
952
+ ```
953
+
954
+ ### Query Vectors
955
+
956
+ Search for similar vectors:
957
+
958
+ ```typescript
959
+ const results = await vector.query({
960
+ indexName: "my-index",
961
+ queryVector: [0.1, 0.2, 0.3],
962
+ topK: 10,
963
+ filter: { label: "first" }, // Optional: Metadata filter
964
+ includeVector: true, // Optional: Include vectors in results
965
+ });
966
+ ```
967
+
968
+ ### Get All Indexes
969
+
970
+ List all available indexes:
971
+
972
+ ```typescript
973
+ const indexes = await vector.getIndexes();
974
+ ```
975
+
976
+ ### Delete Index
977
+
978
+ Delete a vector index:
979
+
980
+ ```typescript
981
+ const result = await vector.delete("index-name");
982
+ ```
983
+
984
+ ---
985
+
986
+ ## Reference: Workflows API
987
+
988
+ > Learn how to interact with and execute automated workflows in Mastra using the client-js SDK.
989
+
990
+ The Workflows API provides methods to interact with and execute automated workflows in Mastra.
991
+
992
+ ## Getting All Workflows
993
+
994
+ Retrieve a list of all available workflows:
995
+
996
+ ```typescript
997
+ const workflows = await mastraClient.listWorkflows();
998
+ ```
999
+
1000
+ ## Working with a Specific Workflow
1001
+
1002
+ Get an instance of a specific workflow by its ID:
1003
+
1004
+ ```typescript title="src/mastra/workflows/test-workflow.ts"
1005
+ export const testWorkflow = createWorkflow({
1006
+ id: "city-workflow",
1007
+ });
1008
+ ```
1009
+
1010
+ ```typescript
1011
+ const workflow = mastraClient.getWorkflow("city-workflow");
1012
+ ```
1013
+
1014
+ ## Workflow Methods
1015
+
1016
+ ### details()
1017
+
1018
+ Retrieve detailed information about a workflow:
1019
+
1020
+ ```typescript
1021
+ const details = await workflow.details();
1022
+ ```
1023
+
1024
+ ### createRun()
1025
+
1026
+ Create a new workflow run instance:
1027
+
1028
+ ```typescript
1029
+ const run = await workflow.createRun();
1030
+
1031
+ // Or with an existing runId
1032
+ const run = await workflow.createRun({ runId: "existing-run-id" });
1033
+
1034
+ // Or with a resourceId to associate the run with a specific resource
1035
+ const run = await workflow.createRun({
1036
+ runId: "my-run-id",
1037
+ resourceId: "user-123"
1038
+ });
1039
+ ```
1040
+
1041
+ The `resourceId` parameter associates the workflow run with a specific resource (e.g., user ID, tenant ID). This value is persisted with the run and can be used for filtering and querying runs later.
1042
+
1043
+ ### startAsync()
1044
+
1045
+ Start a workflow run and await the full result:
1046
+
1047
+ ```typescript
1048
+ const run = await workflow.createRun();
1049
+
1050
+ const result = await run.startAsync({
1051
+ inputData: {
1052
+ city: "New York",
1053
+ },
1054
+ });
1055
+ ```
1056
+
1057
+ You can also pass `initialState` to set the starting values for the workflow's state:
1058
+
1059
+ ```typescript
1060
+ const result = await run.startAsync({
1061
+ inputData: {
1062
+ city: "New York",
1063
+ },
1064
+ initialState: {
1065
+ count: 0,
1066
+ items: [],
1067
+ },
1068
+ });
1069
+ ```
1070
+
1071
+ The `initialState` object should match the structure defined in the workflow's `stateSchema`. See [Workflow State](https://mastra.ai/docs/v1/workflows/workflow-state) for more details.
1072
+
1073
+ To associate a run with a specific resource, pass `resourceId` to `createRun()`:
1074
+
1075
+ ```typescript
1076
+ const run = await workflow.createRun({ resourceId: "user-123" });
1077
+
1078
+ const result = await run.startAsync({
1079
+ inputData: {
1080
+ city: "New York",
1081
+ },
1082
+ });
1083
+ ```
1084
+
1085
+ ### start()
1086
+
1087
+ Start a workflow run without waiting for completion:
1088
+
1089
+ ```typescript
1090
+ const run = await workflow.createRun();
1091
+
1092
+ await run.start({
1093
+ inputData: {
1094
+ city: "New York",
1095
+ },
1096
+ });
1097
+
1098
+ // Poll for results later
1099
+ const result = await workflow.runById(run.runId);
1100
+ ```
1101
+
1102
+ This is useful for long-running workflows where you want to start execution and check results later.
1103
+
1104
+ ### resumeAsync()
1105
+
1106
+ Resume a suspended workflow step and await the full result:
1107
+
1108
+ ```typescript
1109
+ const run = await workflow.createRun({ runId: prevRunId });
1110
+
1111
+ const result = await run.resumeAsync({
1112
+ step: "step-id",
1113
+ resumeData: { key: "value" },
1114
+ });
1115
+ ```
1116
+
1117
+ ### resume()
1118
+
1119
+ Resume a suspended workflow step without waiting for completion:
1120
+
1121
+ ```typescript
1122
+ const run = await workflow.createRun({ runId: prevRunId });
1123
+
1124
+ await run.resume({
1125
+ step: "step-id",
1126
+ resumeData: { key: "value" },
1127
+ });
1128
+ ```
1129
+
1130
+ ### cancel()
1131
+
1132
+ Cancel a running workflow:
1133
+
1134
+ ```typescript
1135
+ const run = await workflow.createRun({ runId: existingRunId });
1136
+
1137
+ const result = await run.cancel();
1138
+ // Returns: { message: 'Workflow run canceled' }
1139
+ ```
1140
+
1141
+ This method stops any running steps and prevents subsequent steps from executing. Steps that check the `abortSignal` parameter can respond to cancellation by cleaning up resources (timeouts, network requests, etc.).
1142
+
1143
+ See the [Run.cancel()](https://mastra.ai/reference/v1/workflows/run-methods/cancel) reference for detailed information about how cancellation works and how to write steps that respond to cancellation.
1144
+
1145
+ ### stream()
1146
+
1147
+ Stream workflow execution for real-time updates:
1148
+
1149
+ ```typescript
1150
+ const run = await workflow.createRun();
1151
+
1152
+ const stream = await run.stream({
1153
+ inputData: {
1154
+ city: "New York",
1155
+ },
1156
+ });
1157
+
1158
+ for await (const chunk of stream) {
1159
+ console.log(JSON.stringify(chunk, null, 2));
1160
+ }
1161
+ ```
1162
+
1163
+ ### runById()
1164
+
1165
+ Get the execution result for a workflow run:
1166
+
1167
+ ```typescript
1168
+ const result = await workflow.runById(runId);
1169
+
1170
+ // Or with options for performance optimization:
1171
+ const result = await workflow.runById(runId, {
1172
+ fields: ['status', 'result'], // Only fetch specific fields
1173
+ withNestedWorkflows: false, // Skip expensive nested workflow data
1174
+ requestContext: { userId: 'user-123' }, // Optional request context
1175
+ });
1176
+ ```
1177
+
1178
+ <h3>Run result format</h3>
1179
+
1180
+ A workflow run result yields the following: