@mastra/client-js 0.0.0-error-handler-fix-20251020202607 → 0.0.0-execa-dynamic-import-20260304221256

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 (86) hide show
  1. package/CHANGELOG.md +3375 -3
  2. package/LICENSE.md +15 -0
  3. package/README.md +11 -13
  4. package/dist/_types/@ai-sdk_ui-utils/dist/index.d.ts +820 -0
  5. package/dist/_types/@internal_ai-sdk-v5/dist/index.d.ts +10345 -0
  6. package/dist/client.d.ts +397 -75
  7. package/dist/client.d.ts.map +1 -1
  8. package/dist/docs/SKILL.md +44 -0
  9. package/dist/docs/assets/SOURCE_MAP.json +6 -0
  10. package/dist/docs/references/docs-server-auth-auth0.md +220 -0
  11. package/dist/docs/references/docs-server-auth-clerk.md +132 -0
  12. package/dist/docs/references/docs-server-auth-firebase.md +272 -0
  13. package/dist/docs/references/docs-server-auth-jwt.md +110 -0
  14. package/dist/docs/references/docs-server-auth-supabase.md +117 -0
  15. package/dist/docs/references/docs-server-auth-workos.md +186 -0
  16. package/dist/docs/references/docs-server-mastra-client.md +243 -0
  17. package/dist/docs/references/reference-ai-sdk-to-ai-sdk-stream.md +231 -0
  18. package/dist/docs/references/reference-ai-sdk-to-ai-sdk-v4-messages.md +79 -0
  19. package/dist/docs/references/reference-ai-sdk-to-ai-sdk-v5-messages.md +76 -0
  20. package/dist/docs/references/reference-client-js-agents.md +437 -0
  21. package/dist/docs/references/reference-client-js-error-handling.md +16 -0
  22. package/dist/docs/references/reference-client-js-logs.md +24 -0
  23. package/dist/docs/references/reference-client-js-mastra-client.md +63 -0
  24. package/dist/docs/references/reference-client-js-memory.md +221 -0
  25. package/dist/docs/references/reference-client-js-observability.md +72 -0
  26. package/dist/docs/references/reference-client-js-telemetry.md +20 -0
  27. package/dist/docs/references/reference-client-js-tools.md +44 -0
  28. package/dist/docs/references/reference-client-js-vectors.md +79 -0
  29. package/dist/docs/references/reference-client-js-workflows.md +199 -0
  30. package/dist/index.cjs +4575 -1896
  31. package/dist/index.cjs.map +1 -1
  32. package/dist/index.js +4875 -2193
  33. package/dist/index.js.map +1 -1
  34. package/dist/resources/a2a.d.ts.map +1 -1
  35. package/dist/resources/agent-builder.d.ts +55 -62
  36. package/dist/resources/agent-builder.d.ts.map +1 -1
  37. package/dist/resources/agent.d.ts +89 -51
  38. package/dist/resources/agent.d.ts.map +1 -1
  39. package/dist/resources/base.d.ts +2 -1
  40. package/dist/resources/base.d.ts.map +1 -1
  41. package/dist/resources/index.d.ts +9 -0
  42. package/dist/resources/index.d.ts.map +1 -1
  43. package/dist/resources/mcp-tool.d.ts +5 -5
  44. package/dist/resources/mcp-tool.d.ts.map +1 -1
  45. package/dist/resources/memory-thread.d.ts +31 -16
  46. package/dist/resources/memory-thread.d.ts.map +1 -1
  47. package/dist/resources/observability.d.ts +62 -19
  48. package/dist/resources/observability.d.ts.map +1 -1
  49. package/dist/resources/processor-provider.d.ts +15 -0
  50. package/dist/resources/processor-provider.d.ts.map +1 -0
  51. package/dist/resources/processor.d.ts +20 -0
  52. package/dist/resources/processor.d.ts.map +1 -0
  53. package/dist/resources/run.d.ts +210 -0
  54. package/dist/resources/run.d.ts.map +1 -0
  55. package/dist/resources/stored-agent.d.ts +83 -0
  56. package/dist/resources/stored-agent.d.ts.map +1 -0
  57. package/dist/resources/stored-mcp-client.d.ts +30 -0
  58. package/dist/resources/stored-mcp-client.d.ts.map +1 -0
  59. package/dist/resources/stored-prompt-block.d.ts +83 -0
  60. package/dist/resources/stored-prompt-block.d.ts.map +1 -0
  61. package/dist/resources/stored-scorer.d.ts +83 -0
  62. package/dist/resources/stored-scorer.d.ts.map +1 -0
  63. package/dist/resources/stored-skill.d.ts +30 -0
  64. package/dist/resources/stored-skill.d.ts.map +1 -0
  65. package/dist/resources/tool-provider.d.ts +27 -0
  66. package/dist/resources/tool-provider.d.ts.map +1 -0
  67. package/dist/resources/tool.d.ts +4 -4
  68. package/dist/resources/vector.d.ts +5 -5
  69. package/dist/resources/vector.d.ts.map +1 -1
  70. package/dist/resources/workflow.d.ts +32 -231
  71. package/dist/resources/workflow.d.ts.map +1 -1
  72. package/dist/resources/workspace.d.ts +125 -0
  73. package/dist/resources/workspace.d.ts.map +1 -0
  74. package/dist/tools.d.ts +2 -2
  75. package/dist/tools.d.ts.map +1 -1
  76. package/dist/types.d.ts +1673 -146
  77. package/dist/types.d.ts.map +1 -1
  78. package/dist/utils/index.d.ts +56 -4
  79. package/dist/utils/index.d.ts.map +1 -1
  80. package/dist/utils/process-mastra-stream.d.ts +1 -1
  81. package/dist/utils/process-mastra-stream.d.ts.map +1 -1
  82. package/dist/utils/zod-to-json-schema.d.ts +9 -1
  83. package/dist/utils/zod-to-json-schema.d.ts.map +1 -1
  84. package/package.json +20 -18
  85. package/dist/resources/network-memory-thread.d.ts +0 -47
  86. package/dist/resources/network-memory-thread.d.ts.map +0 -1
@@ -0,0 +1,110 @@
1
+ # MastraJwtAuth Class
2
+
3
+ The `MastraJwtAuth` class provides a lightweight authentication mechanism for Mastra using JSON Web Tokens (JWTs). It verifies incoming requests based on a shared secret and integrates with the Mastra server using the `auth` option.
4
+
5
+ ## Installation
6
+
7
+ Before you can use the `MastraJwtAuth` class you have to install the `@mastra/auth` package.
8
+
9
+ **npm**:
10
+
11
+ ```bash
12
+ npm install @mastra/auth@latest
13
+ ```
14
+
15
+ **pnpm**:
16
+
17
+ ```bash
18
+ pnpm add @mastra/auth@latest
19
+ ```
20
+
21
+ **Yarn**:
22
+
23
+ ```bash
24
+ yarn add @mastra/auth@latest
25
+ ```
26
+
27
+ **Bun**:
28
+
29
+ ```bash
30
+ bun add @mastra/auth@latest
31
+ ```
32
+
33
+ ## Usage example
34
+
35
+ ```typescript
36
+ import { Mastra } from '@mastra/core'
37
+ import { MastraJwtAuth } from '@mastra/auth'
38
+
39
+ export const mastra = new Mastra({
40
+ server: {
41
+ auth: new MastraJwtAuth({
42
+ secret: process.env.MASTRA_JWT_SECRET,
43
+ }),
44
+ },
45
+ })
46
+ ```
47
+
48
+ > **Info:** Visit [MastraJwtAuth](https://mastra.ai/reference/auth/jwt) for all available configuration options.
49
+
50
+ ## Configuring `MastraClient`
51
+
52
+ When `auth` is enabled, all requests made with `MastraClient` must include a valid JWT in the `Authorization` header:
53
+
54
+ ```typescript
55
+ import { MastraClient } from '@mastra/client-js'
56
+
57
+ export const mastraClient = new MastraClient({
58
+ baseUrl: 'https://<mastra-api-url>',
59
+ headers: {
60
+ Authorization: `Bearer ${process.env.MASTRA_JWT_TOKEN}`,
61
+ },
62
+ })
63
+ ```
64
+
65
+ > **Info:** Visit [Mastra Client SDK](https://mastra.ai/docs/server/mastra-client) for more configuration options.
66
+
67
+ ### Making authenticated requests
68
+
69
+ Once `MastraClient` is configured, you can send authenticated requests from your frontend application, or use `curl` for quick local testing:
70
+
71
+ **React**:
72
+
73
+ ```tsx
74
+ import { mastraClient } from '../../lib/mastra-client'
75
+
76
+ export const TestAgent = () => {
77
+ async function handleClick() {
78
+ const agent = mastraClient.getAgent('weatherAgent')
79
+
80
+ const response = await agent.generate('Weather in London')
81
+
82
+ console.log(response)
83
+ }
84
+
85
+ return <button onClick={handleClick}>Test Agent</button>
86
+ }
87
+ ```
88
+
89
+ **cURL**:
90
+
91
+ ```bash
92
+ curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \
93
+ -H "Content-Type: application/json" \
94
+ -H "Authorization: Bearer <your-jwt>" \
95
+ -d '{
96
+ "messages": "Weather in London"
97
+ }'
98
+ ```
99
+
100
+ ## Creating a JWT
101
+
102
+ To authenticate requests to your Mastra server, you'll need a valid JSON Web Token (JWT) signed with your `MASTRA_JWT_SECRET`.
103
+
104
+ The easiest way to generate one is using [jwt.io](https://www.jwt.io/):
105
+
106
+ 1. Select **JWT Encoder**.
107
+ 2. Scroll down to the **Sign JWT: Secret** section.
108
+ 3. Enter your secret (for example: `supersecretdevkeythatishs256safe!`).
109
+ 4. Click **Generate example** to create a valid JWT.
110
+ 5. Copy the generated token and set it as `MASTRA_JWT_TOKEN` in your `.env` file.
@@ -0,0 +1,117 @@
1
+ # MastraAuthSupabase Class
2
+
3
+ The `MastraAuthSupabase` class provides authentication for Mastra using Supabase Auth. It verifies incoming requests using Supabase's authentication system and integrates with the Mastra server using the `auth` option.
4
+
5
+ ## Prerequisites
6
+
7
+ This example uses Supabase Auth. Make sure to add your Supabase credentials to your `.env` file and ensure your Supabase project is properly configured.
8
+
9
+ ```env
10
+ SUPABASE_URL=https://your-project.supabase.co
11
+ SUPABASE_ANON_KEY=your-anon-key
12
+ ```
13
+
14
+ > **Note:** Review your Supabase Row Level Security (RLS) settings to ensure proper data access controls.
15
+
16
+ ## Installation
17
+
18
+ Before you can use the `MastraAuthSupabase` class you have to install the `@mastra/auth-supabase` package.
19
+
20
+ ```bash
21
+ npm install @mastra/auth-supabase@latest
22
+ ```
23
+
24
+ ## Usage example
25
+
26
+ ```typescript
27
+ import { Mastra } from '@mastra/core'
28
+ import { MastraAuthSupabase } from '@mastra/auth-supabase'
29
+
30
+ export const mastra = new Mastra({
31
+ server: {
32
+ auth: new MastraAuthSupabase({
33
+ url: process.env.SUPABASE_URL,
34
+ anonKey: process.env.SUPABASE_ANON_KEY,
35
+ }),
36
+ },
37
+ })
38
+ ```
39
+
40
+ > **Info:** The default `authorizeUser` method checks the `isAdmin` column in the `users` table in the `public` schema. To customize user authorization, provide a custom `authorizeUser` function when constructing the provider.
41
+ >
42
+ > Visit [MastraAuthSupabase](https://mastra.ai/reference/auth/supabase) for all available configuration options.
43
+
44
+ ## Client-side setup
45
+
46
+ When using Supabase auth, you'll need to retrieve the access token from Supabase on the client side and pass it to your Mastra requests.
47
+
48
+ ### Retrieving the access token
49
+
50
+ Use the Supabase client to authenticate users and retrieve their access token:
51
+
52
+ ```typescript
53
+ import { createClient } from '@supabase/supabase-js'
54
+
55
+ const supabase = createClient('<supabase-url>', '<supabase-key>')
56
+
57
+ const authTokenResponse = await supabase.auth.signInWithPassword({
58
+ email: "<user's email>",
59
+ password: "<user's password>",
60
+ })
61
+
62
+ const accessToken = authTokenResponse.data?.session?.access_token
63
+ ```
64
+
65
+ > **Note:** Refer to the [Supabase documentation](https://supabase.com/docs/guides/auth) for other authentication methods like OAuth, magic links, and more.
66
+
67
+ ## Configuring `MastraClient`
68
+
69
+ When `auth` is enabled, all requests made with `MastraClient` must include a valid Supabase access token in the `Authorization` header:
70
+
71
+ ```typescript
72
+ import { MastraClient } from '@mastra/client-js'
73
+
74
+ export const mastraClient = new MastraClient({
75
+ baseUrl: 'https://<mastra-api-url>',
76
+ headers: {
77
+ Authorization: `Bearer ${accessToken}`,
78
+ },
79
+ })
80
+ ```
81
+
82
+ > **Info:** The access token must be prefixed with `Bearer` in the Authorization header.
83
+ >
84
+ > Visit [Mastra Client SDK](https://mastra.ai/docs/server/mastra-client) for more configuration options.
85
+
86
+ ### Making authenticated requests
87
+
88
+ Once `MastraClient` is configured with the Supabase access token, you can send authenticated requests:
89
+
90
+ **React**:
91
+
92
+ ```tsx
93
+ import { mastraClient } from '../../lib/mastra-client'
94
+
95
+ export const TestAgent = () => {
96
+ async function handleClick() {
97
+ const agent = mastraClient.getAgent('weatherAgent')
98
+
99
+ const response = await agent.generate("What's the weather like in New York")
100
+
101
+ console.log(response)
102
+ }
103
+
104
+ return <button onClick={handleClick}>Test Agent</button>
105
+ }
106
+ ```
107
+
108
+ **cURL**:
109
+
110
+ ```bash
111
+ curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \
112
+ -H "Content-Type: application/json" \
113
+ -H "Authorization: Bearer <your-supabase-access-token>" \
114
+ -d '{
115
+ "messages": "Weather in London"
116
+ }'
117
+ ```
@@ -0,0 +1,186 @@
1
+ # MastraAuthWorkos Class
2
+
3
+ The `MastraAuthWorkos` class provides authentication for Mastra using WorkOS. It verifies incoming requests using WorkOS access tokens and integrates with the Mastra server using the `auth` option.
4
+
5
+ ## Prerequisites
6
+
7
+ This example uses WorkOS authentication. Make sure to:
8
+
9
+ 1. Create a WorkOS account at [workos.com](https://workos.com/)
10
+ 2. Set up an Application in your WorkOS Dashboard
11
+ 3. Configure your redirect URIs and allowed origins
12
+ 4. Set up Organizations and configure user roles as needed
13
+
14
+ ```env
15
+ WORKOS_API_KEY=sk_live_...
16
+ WORKOS_CLIENT_ID=client_...
17
+ ```
18
+
19
+ > **Note:** You can find your API key and Client ID in the WorkOS Dashboard under API Keys and Applications respectively.
20
+ >
21
+ > For detailed setup instructions, refer to the [WorkOS documentation](https://workos.com/docs) for your specific platform.
22
+
23
+ ## Installation
24
+
25
+ Before you can use the `MastraAuthWorkos` class you have to install the `@mastra/auth-workos` package.
26
+
27
+ ```bash
28
+ npm install @mastra/auth-workos@latest
29
+ ```
30
+
31
+ ## Usage examples
32
+
33
+ ### Basic usage with environment variables
34
+
35
+ ```typescript
36
+ import { Mastra } from '@mastra/core'
37
+ import { MastraAuthWorkos } from '@mastra/auth-workos'
38
+
39
+ export const mastra = new Mastra({
40
+ server: {
41
+ auth: new MastraAuthWorkos(),
42
+ },
43
+ })
44
+ ```
45
+
46
+ ### Custom configuration
47
+
48
+ ```typescript
49
+ import { Mastra } from '@mastra/core'
50
+ import { MastraAuthWorkos } from '@mastra/auth-workos'
51
+
52
+ export const mastra = new Mastra({
53
+ server: {
54
+ auth: new MastraAuthWorkos({
55
+ apiKey: process.env.WORKOS_API_KEY,
56
+ clientId: process.env.WORKOS_CLIENT_ID,
57
+ }),
58
+ },
59
+ })
60
+ ```
61
+
62
+ ## Configuration
63
+
64
+ ### User Authorization
65
+
66
+ By default, `MastraAuthWorkos` checks whether the authenticated user has an 'admin' role in any of their organization memberships. The authorization process:
67
+
68
+ 1. Retrieves the user's organization memberships using their user ID
69
+ 2. Extracts all roles from their memberships
70
+ 3. Checks if any role has the slug 'admin'
71
+ 4. Grants access only if the user has admin role in at least one organization
72
+
73
+ To customize user authorization, provide a custom `authorizeUser` function:
74
+
75
+ ```typescript
76
+ import { MastraAuthWorkos } from '@mastra/auth-workos'
77
+
78
+ const workosAuth = new MastraAuthWorkos({
79
+ apiKey: process.env.WORKOS_API_KEY,
80
+ clientId: process.env.WORKOS_CLIENT_ID,
81
+ authorizeUser: async user => {
82
+ return !!user
83
+ },
84
+ })
85
+ ```
86
+
87
+ > **Info:** Visit [MastraAuthWorkos](https://mastra.ai/reference/auth/workos) for all available configuration options.
88
+
89
+ ## Client-side setup
90
+
91
+ When using WorkOS auth, you'll need to implement the WorkOS authentication flow to exchange an authorization code for an access token, then use that token with your Mastra requests.
92
+
93
+ ### Installing WorkOS SDK
94
+
95
+ First, install the WorkOS SDK in your application:
96
+
97
+ ```bash
98
+ npm install @workos-inc/node
99
+ ```
100
+
101
+ ### Exchanging code for access token
102
+
103
+ After users complete the WorkOS authentication flow and return with an authorization code, exchange it for an access token:
104
+
105
+ ```typescript
106
+ import { WorkOS } from '@workos-inc/node'
107
+
108
+ const workos = new WorkOS(process.env.WORKOS_API_KEY)
109
+
110
+ export const authenticateWithWorkos = async (code: string, clientId: string) => {
111
+ const authenticationResponse = await workos.userManagement.authenticateWithCode({
112
+ code,
113
+ clientId,
114
+ })
115
+
116
+ return authenticationResponse.accessToken
117
+ }
118
+ ```
119
+
120
+ > **Note:** Refer to the [WorkOS User Management documentation](https://workos.com/docs/authkit/vanilla/nodejs) for more authentication methods and configuration options.
121
+
122
+ ## Configuring `MastraClient`
123
+
124
+ When `auth` is enabled, all requests made with `MastraClient` must include a valid WorkOS access token in the `Authorization` header:
125
+
126
+ ```typescript
127
+ import { MastraClient } from '@mastra/client-js'
128
+
129
+ export const createMastraClient = (accessToken: string) => {
130
+ return new MastraClient({
131
+ baseUrl: 'https://<mastra-api-url>',
132
+ headers: {
133
+ Authorization: `Bearer ${accessToken}`,
134
+ },
135
+ })
136
+ }
137
+ ```
138
+
139
+ > **Info:** The access token must be prefixed with `Bearer` in the Authorization header.
140
+ >
141
+ > Visit [Mastra Client SDK](https://mastra.ai/docs/server/mastra-client) for more configuration options.
142
+
143
+ ### Making authenticated requests
144
+
145
+ Once `MastraClient` is configured with the WorkOS access token, you can send authenticated requests:
146
+
147
+ **React**:
148
+
149
+ ```typescript
150
+ import { WorkOS } from '@workos-inc/node'
151
+ import { MastraClient } from '@mastra/client-js'
152
+
153
+ const workos = new WorkOS(process.env.WORKOS_API_KEY)
154
+
155
+ export const callMastraWithWorkos = async (code: string, clientId: string) => {
156
+ const authenticationResponse = await workos.userManagement.authenticateWithCode({
157
+ code,
158
+ clientId,
159
+ })
160
+
161
+ const token = authenticationResponse.accessToken
162
+
163
+ const mastra = new MastraClient({
164
+ baseUrl: 'http://localhost:4111',
165
+ headers: {
166
+ Authorization: `Bearer ${token}`,
167
+ },
168
+ })
169
+
170
+ const weatherAgent = mastra.getAgent('weatherAgent')
171
+ const response = await weatherAgent.generate("What's the weather like in Nairobi")
172
+
173
+ return response.text
174
+ }
175
+ ```
176
+
177
+ **cURL**:
178
+
179
+ ```bash
180
+ curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \
181
+ -H "Content-Type: application/json" \
182
+ -H "Authorization: Bearer <your-workos-access-token>" \
183
+ -d '{
184
+ "messages": "Weather in London"
185
+ }'
186
+ ```
@@ -0,0 +1,243 @@
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/server/mastra-server) from your client environment.
4
+
5
+ ## Prerequisites
6
+
7
+ To ensure smooth local development, make sure you have:
8
+
9
+ - Node.js `v22.13.0` or later
10
+ - TypeScript `v4.7` or higher (if using TypeScript)
11
+ - Your local Mastra server running (typically on port `4111`)
12
+
13
+ ## Usage
14
+
15
+ The Mastra Client SDK is designed for browser environments and uses the native `fetch` API for making HTTP requests to your Mastra server.
16
+
17
+ ## Installation
18
+
19
+ To use the Mastra Client SDK, install the required dependencies:
20
+
21
+ **npm**:
22
+
23
+ ```bash
24
+ npm install @mastra/client-js@latest
25
+ ```
26
+
27
+ **pnpm**:
28
+
29
+ ```bash
30
+ pnpm add @mastra/client-js@latest
31
+ ```
32
+
33
+ **Yarn**:
34
+
35
+ ```bash
36
+ yarn add @mastra/client-js@latest
37
+ ```
38
+
39
+ **Bun**:
40
+
41
+ ```bash
42
+ bun add @mastra/client-js@latest
43
+ ```
44
+
45
+ ### Initialize the `MastraClient`
46
+
47
+ Once initialized with a `baseUrl`, `MastraClient` exposes a type-safe interface for calling agents, tools, and workflows.
48
+
49
+ ```typescript
50
+ import { MastraClient } from '@mastra/client-js'
51
+
52
+ export const mastraClient = new MastraClient({
53
+ baseUrl: process.env.MASTRA_API_URL || 'http://localhost:4111',
54
+ })
55
+ ```
56
+
57
+ ## Core APIs
58
+
59
+ The Mastra Client SDK exposes all resources served by the Mastra Server
60
+
61
+ - **[Agents](https://mastra.ai/reference/client-js/agents)**: Generate responses and stream conversations.
62
+ - **[Memory](https://mastra.ai/reference/client-js/memory)**: Manage conversation threads and message history.
63
+ - **[Tools](https://mastra.ai/reference/client-js/tools)**: Executed and managed tools.
64
+ - **[Workflows](https://mastra.ai/reference/client-js/workflows)**: Trigger workflows and track their execution.
65
+ - **[Vectors](https://mastra.ai/reference/client-js/vectors)**: Use vector embeddings for semantic search.
66
+ - **[Logs](https://mastra.ai/reference/client-js/logs)**: View logs and debug system behavior.
67
+ - **[Telemetry](https://mastra.ai/reference/client-js/telemetry)**: Monitor app performance and trace activity.
68
+
69
+ ## Generating responses
70
+
71
+ Call `.generate()` with a string prompt:
72
+
73
+ ```typescript
74
+ import { mastraClient } from 'lib/mastra-client'
75
+
76
+ const testAgent = async () => {
77
+ try {
78
+ const agent = mastraClient.getAgent('testAgent')
79
+
80
+ const response = await agent.generate('Hello')
81
+
82
+ console.log(response.text)
83
+ } catch (error) {
84
+ return 'Error occurred while generating response'
85
+ }
86
+ }
87
+ ```
88
+
89
+ > **Info:** You can also call `.generate()` with an array of message objects that include `role` and `content`. Visit the [.generate() reference](https://mastra.ai/reference/client-js/agents) for more information.
90
+
91
+ ## Streaming responses
92
+
93
+ Use `.stream()` for real-time responses with a string prompt:
94
+
95
+ ```typescript
96
+ import { mastraClient } from 'lib/mastra-client'
97
+
98
+ const testAgent = async () => {
99
+ try {
100
+ const agent = mastraClient.getAgent('testAgent')
101
+
102
+ const stream = await agent.stream('Hello')
103
+
104
+ stream.processDataStream({
105
+ onTextPart: text => {
106
+ console.log(text)
107
+ },
108
+ })
109
+ } catch (error) {
110
+ return 'Error occurred while generating response'
111
+ }
112
+ }
113
+ ```
114
+
115
+ > **Info:** You can also call `.stream()` with an array of message objects that include `role` and `content`. Visit the [.stream() reference](https://mastra.ai/reference/client-js/agents) for more information.
116
+
117
+ ## Configuration options
118
+
119
+ `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.
120
+
121
+ ```typescript
122
+ import { MastraClient } from '@mastra/client-js'
123
+
124
+ export const mastraClient = new MastraClient({
125
+ retries: 3,
126
+ backoffMs: 300,
127
+ maxBackoffMs: 5000,
128
+ headers: {
129
+ 'X-Development': 'true',
130
+ },
131
+ })
132
+ ```
133
+
134
+ > **Info:** Visit [MastraClient](https://mastra.ai/reference/client-js/mastra-client) for more configuration options.
135
+
136
+ ## Adding request cancelling
137
+
138
+ `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.
139
+
140
+ Pass an `AbortSignal` to the client constructor to enable cancellation across all requests.
141
+
142
+ ```typescript
143
+ import { MastraClient } from '@mastra/client-js'
144
+
145
+ export const controller = new AbortController()
146
+
147
+ export const mastraClient = new MastraClient({
148
+ baseUrl: process.env.MASTRA_API_URL || 'http://localhost:4111',
149
+ abortSignal: controller.signal,
150
+ })
151
+ ```
152
+
153
+ ### Using the `AbortController`
154
+
155
+ Calling `.abort()` will cancel any ongoing requests tied to that signal.
156
+
157
+ ```typescript
158
+ import { mastraClient, controller } from 'lib/mastra-client'
159
+
160
+ const handleAbort = () => {
161
+ controller.abort()
162
+ }
163
+ ```
164
+
165
+ ## Client tools
166
+
167
+ Define tools directly in client-side applications using the `createTool()` function. Pass them to agents via the `clientTools` parameter in `.generate()` or `.stream()` calls.
168
+
169
+ 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.
170
+
171
+ ```typescript
172
+ import { createTool } from '@mastra/client-js'
173
+ import { z } from 'zod'
174
+
175
+ const handleClientTool = async () => {
176
+ try {
177
+ const agent = mastraClient.getAgent('colorAgent')
178
+
179
+ const colorChangeTool = createTool({
180
+ id: 'color-change-tool',
181
+ description: 'Changes the HTML background color',
182
+ inputSchema: z.object({
183
+ color: z.string(),
184
+ }),
185
+ outputSchema: z.object({
186
+ success: z.boolean(),
187
+ }),
188
+ execute: async inputData => {
189
+ const { color } = inputData
190
+
191
+ document.body.style.backgroundColor = color
192
+ return { success: true }
193
+ },
194
+ })
195
+
196
+ const response = await agent.generate('Change the background to blue', {
197
+ clientTools: { colorChangeTool },
198
+ })
199
+
200
+ console.log(response)
201
+ } catch (error) {
202
+ console.error(error)
203
+ }
204
+ }
205
+ ```
206
+
207
+ ### Client tool's agent
208
+
209
+ This is a standard Mastra [agent](https://mastra.ai/docs/agents/overview) configured to return hex color codes, intended to work with the browser-based client tool defined above.
210
+
211
+ ```typescript
212
+ import { Agent } from '@mastra/core/agent'
213
+
214
+ export const colorAgent = new Agent({
215
+ id: 'color-agent',
216
+ name: 'Color Agent',
217
+ instructions: `You are a helpful CSS assistant.
218
+ You can change the background color of web pages.
219
+ Respond with a hex reference for the color requested by the user`,
220
+ model: 'openai/gpt-5.1',
221
+ })
222
+ ```
223
+
224
+ ## Server-side environments
225
+
226
+ 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:
227
+
228
+ ```typescript
229
+ export async function action() {
230
+ const agent = mastraClient.getAgent('testAgent')
231
+
232
+ const stream = await agent.stream('Hello')
233
+
234
+ return new Response(stream.body)
235
+ }
236
+ ```
237
+
238
+ ## Best practices
239
+
240
+ 1. **Error Handling**: Implement proper [error handling](https://mastra.ai/reference/client-js/error-handling) for development scenarios.
241
+ 2. **Environment Variables**: Use environment variables for configuration.
242
+ 3. **Debugging**: Enable detailed [logging](https://mastra.ai/reference/client-js/logs) when needed.
243
+ 4. **Performance**: Monitor application performance, [telemetry](https://mastra.ai/reference/client-js/telemetry) and traces.