@mastra/client-js 1.7.0 → 1.7.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 (24) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/docs/SKILL.md +44 -0
  3. package/dist/docs/assets/SOURCE_MAP.json +6 -0
  4. package/dist/docs/references/docs-server-auth-auth0.md +220 -0
  5. package/dist/docs/references/docs-server-auth-clerk.md +132 -0
  6. package/dist/docs/references/docs-server-auth-firebase.md +272 -0
  7. package/dist/docs/references/docs-server-auth-jwt.md +110 -0
  8. package/dist/docs/references/docs-server-auth-supabase.md +117 -0
  9. package/dist/docs/references/docs-server-auth-workos.md +186 -0
  10. package/dist/docs/references/docs-server-mastra-client.md +243 -0
  11. package/dist/docs/references/reference-ai-sdk-to-ai-sdk-stream.md +231 -0
  12. package/dist/docs/references/reference-ai-sdk-to-ai-sdk-v4-messages.md +79 -0
  13. package/dist/docs/references/reference-ai-sdk-to-ai-sdk-v5-messages.md +76 -0
  14. package/dist/docs/references/reference-client-js-agents.md +437 -0
  15. package/dist/docs/references/reference-client-js-error-handling.md +16 -0
  16. package/dist/docs/references/reference-client-js-logs.md +24 -0
  17. package/dist/docs/references/reference-client-js-mastra-client.md +63 -0
  18. package/dist/docs/references/reference-client-js-memory.md +221 -0
  19. package/dist/docs/references/reference-client-js-observability.md +72 -0
  20. package/dist/docs/references/reference-client-js-telemetry.md +20 -0
  21. package/dist/docs/references/reference-client-js-tools.md +44 -0
  22. package/dist/docs/references/reference-client-js-vectors.md +79 -0
  23. package/dist/docs/references/reference-client-js-workflows.md +199 -0
  24. package/package.json +5 -5
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # @mastra/client-js
2
2
 
3
+ ## 1.7.1-alpha.0
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [[`df170fd`](https://github.com/mastra-ai/mastra/commit/df170fd139b55f845bfd2de8488b16435bd3d0da), [`ae55343`](https://github.com/mastra-ai/mastra/commit/ae5534397fc006fd6eef3e4f80c235bcdc9289ef), [`c290cec`](https://github.com/mastra-ai/mastra/commit/c290cec5bf9107225de42942b56b487107aa9dce), [`f03e794`](https://github.com/mastra-ai/mastra/commit/f03e794630f812b56e95aad54f7b1993dc003add), [`aa4a5ae`](https://github.com/mastra-ai/mastra/commit/aa4a5aedb80d8d6837bab8cbb2e301215d1ba3e9), [`de3f584`](https://github.com/mastra-ai/mastra/commit/de3f58408752a8d80a295275c7f23fc306cf7f4f), [`d3fb010`](https://github.com/mastra-ai/mastra/commit/d3fb010c98f575f1c0614452667396e2653815f6), [`702ee1c`](https://github.com/mastra-ai/mastra/commit/702ee1c41be67cc532b4dbe89bcb62143508f6f0), [`f495051`](https://github.com/mastra-ai/mastra/commit/f495051eb6496a720f637fc85b6d69941c12554c), [`e622f1d`](https://github.com/mastra-ai/mastra/commit/e622f1d3ab346a8e6aca6d1fe2eac99bd961e50b), [`8d14a59`](https://github.com/mastra-ai/mastra/commit/8d14a591d46fbbbe81baa33c9c267d596f790329), [`861f111`](https://github.com/mastra-ai/mastra/commit/861f11189211b20ddb70d8df81a6b901fc78d11e), [`00f43e8`](https://github.com/mastra-ai/mastra/commit/00f43e8e97a80c82b27d5bd30494f10a715a1df9), [`1b6f651`](https://github.com/mastra-ai/mastra/commit/1b6f65127d4a0d6c38d0a1055cb84527db529d6b), [`96a1702`](https://github.com/mastra-ai/mastra/commit/96a1702ce362c50dda20c8b4a228b4ad1a36a17a), [`cb9f921`](https://github.com/mastra-ai/mastra/commit/cb9f921320913975657abb1404855d8c510f7ac5), [`114e7c1`](https://github.com/mastra-ai/mastra/commit/114e7c146ac682925f0fb37376c1be70e5d6e6e5), [`1b6f651`](https://github.com/mastra-ai/mastra/commit/1b6f65127d4a0d6c38d0a1055cb84527db529d6b), [`72df4a8`](https://github.com/mastra-ai/mastra/commit/72df4a8f9bf1a20cfd3d9006a4fdb597ad56d10a)]:
8
+ - @mastra/core@1.8.0-alpha.0
9
+ - @mastra/schema-compat@1.1.3-alpha.0
10
+
3
11
  ## 1.7.0
4
12
 
5
13
  ### Minor Changes
@@ -0,0 +1,44 @@
1
+ ---
2
+ name: mastra-client-js
3
+ description: Documentation for @mastra/client-js. Use when working with @mastra/client-js APIs, configuration, or implementation.
4
+ metadata:
5
+ package: "@mastra/client-js"
6
+ version: "1.7.1-alpha.0"
7
+ ---
8
+
9
+ ## When to use
10
+
11
+ Use this skill whenever you are working with @mastra/client-js to obtain the domain-specific knowledge.
12
+
13
+ ## How to use
14
+
15
+ Read the individual reference documents for detailed explanations and code examples.
16
+
17
+ ### Docs
18
+
19
+ - [MastraAuthAuth0 Class](references/docs-server-auth-auth0.md) - Documentation for the MastraAuthAuth0 class, which authenticates Mastra applications using Auth0 authentication.
20
+ - [MastraAuthClerk Class](references/docs-server-auth-clerk.md) - Documentation for the MastraAuthClerk class, which authenticates Mastra applications using Clerk authentication.
21
+ - [MastraAuthFirebase Class](references/docs-server-auth-firebase.md) - Documentation for the MastraAuthFirebase class, which authenticates Mastra applications using Firebase Authentication.
22
+ - [MastraJwtAuth Class](references/docs-server-auth-jwt.md) - Documentation for the MastraJwtAuth class, which authenticates Mastra applications using JSON Web Tokens.
23
+ - [MastraAuthSupabase Class](references/docs-server-auth-supabase.md) - Documentation for the MastraAuthSupabase class, which authenticates Mastra applications using Supabase Auth.
24
+ - [MastraAuthWorkos Class](references/docs-server-auth-workos.md) - Documentation for the MastraAuthWorkos class, which authenticates Mastra applications using WorkOS authentication.
25
+ - [Mastra Client SDK](references/docs-server-mastra-client.md) - Learn how to set up and use the Mastra Client SDK
26
+
27
+ ### Reference
28
+
29
+ - [Reference: toAISdkStream()](references/reference-ai-sdk-to-ai-sdk-stream.md) - API reference for toAISdkStream(), a function to convert Mastra streams to AI SDK-compatible streams.
30
+ - [Reference: toAISdkV4Messages()](references/reference-ai-sdk-to-ai-sdk-v4-messages.md) - API reference for toAISdkV4Messages(), a function to convert Mastra messages to AI SDK v4 UI messages.
31
+ - [Reference: toAISdkV5Messages()](references/reference-ai-sdk-to-ai-sdk-v5-messages.md) - API reference for toAISdkV5Messages(), a function to convert Mastra messages to AI SDK v5 UI messages.
32
+ - [Reference: Agents API](references/reference-client-js-agents.md) - Learn how to interact with Mastra AI agents, including generating responses, streaming interactions, and managing agent tools using the client-js SDK.
33
+ - [Reference: Error Handling](references/reference-client-js-error-handling.md) - Learn about the built-in retry mechanism and error handling capabilities in the Mastra client-js SDK.
34
+ - [Reference: Logs API](references/reference-client-js-logs.md) - Learn how to access and query system logs and debugging information in Mastra using the client-js SDK.
35
+ - [Reference: Mastra Client SDK](references/reference-client-js-mastra-client.md) - Learn how to interact with Mastra using the client-js SDK.
36
+ - [Reference: Memory API](references/reference-client-js-memory.md) - Learn how to manage conversation threads and message history in Mastra using the client-js SDK.
37
+ - [Reference: Observability API](references/reference-client-js-observability.md) - Learn how to retrieve traces, monitor application performance, and score traces using the client-js SDK.
38
+ - [Reference: Telemetry API](references/reference-client-js-telemetry.md) - Learn how to retrieve and analyze traces from your Mastra application for monitoring and debugging using the client-js SDK.
39
+ - [Reference: Tools API](references/reference-client-js-tools.md) - Learn how to interact with and execute tools available in the Mastra platform using the client-js SDK.
40
+ - [Reference: Vectors API](references/reference-client-js-vectors.md) - Learn how to work with vector embeddings for semantic search and similarity matching in Mastra using the client-js SDK.
41
+ - [Reference: Workflows API](references/reference-client-js-workflows.md) - Learn how to interact with and execute automated workflows in Mastra using the client-js SDK.
42
+
43
+
44
+ Read [assets/SOURCE_MAP.json](assets/SOURCE_MAP.json) for source code references.
@@ -0,0 +1,6 @@
1
+ {
2
+ "version": "1.7.1-alpha.0",
3
+ "package": "@mastra/client-js",
4
+ "exports": {},
5
+ "modules": {}
6
+ }
@@ -0,0 +1,220 @@
1
+ # MastraAuthAuth0 Class
2
+
3
+ The `MastraAuthAuth0` class provides authentication for Mastra using Auth0. It verifies incoming requests using Auth0-issued JWT tokens and integrates with the Mastra server using the `auth` option.
4
+
5
+ ## Prerequisites
6
+
7
+ This example uses Auth0 authentication. Make sure to:
8
+
9
+ 1. Create an Auth0 account at [auth0.com](https://auth0.com/)
10
+ 2. Set up an Application in your Auth0 Dashboard
11
+ 3. Configure an API in your Auth0 Dashboard with an identifier (audience)
12
+ 4. Configure your application's allowed callback URLs, web origins, and logout URLs
13
+
14
+ ```env
15
+ AUTH0_DOMAIN=your-tenant.auth0.com
16
+ AUTH0_AUDIENCE=your-api-identifier
17
+ ```
18
+
19
+ > **Note:** You can find your domain in the Auth0 Dashboard under Applications > Settings. The audience is the identifier of your API configured in Auth0 Dashboard > APIs.
20
+ >
21
+ > For detailed setup instructions, refer to the [Auth0 quickstarts](https://auth0.com/docs/quickstarts) for your specific platform.
22
+
23
+ ## Installation
24
+
25
+ Before you can use the `MastraAuthAuth0` class you have to install the `@mastra/auth-auth0` package.
26
+
27
+ ```bash
28
+ npm install @mastra/auth-auth0@latest
29
+ ```
30
+
31
+ ## Usage examples
32
+
33
+ ### Basic usage with environment variables
34
+
35
+ ```typescript
36
+ import { Mastra } from '@mastra/core'
37
+ import { MastraAuthAuth0 } from '@mastra/auth-auth0'
38
+
39
+ export const mastra = new Mastra({
40
+ server: {
41
+ auth: new MastraAuthAuth0(),
42
+ },
43
+ })
44
+ ```
45
+
46
+ ### Custom configuration
47
+
48
+ ```typescript
49
+ import { Mastra } from '@mastra/core'
50
+ import { MastraAuthAuth0 } from '@mastra/auth-auth0'
51
+
52
+ export const mastra = new Mastra({
53
+ server: {
54
+ auth: new MastraAuthAuth0({
55
+ domain: process.env.AUTH0_DOMAIN,
56
+ audience: process.env.AUTH0_AUDIENCE,
57
+ }),
58
+ },
59
+ })
60
+ ```
61
+
62
+ ## Configuration
63
+
64
+ ### User Authorization
65
+
66
+ By default, `MastraAuthAuth0` allows all authenticated users who have valid Auth0 tokens for the specified audience. The token verification ensures that:
67
+
68
+ 1. The token is properly signed by Auth0
69
+ 2. The token is not expired
70
+ 3. The token audience matches your configured audience
71
+ 4. The token issuer matches your Auth0 domain
72
+
73
+ To customize user authorization, provide a custom `authorizeUser` function:
74
+
75
+ ```typescript
76
+ import { MastraAuthAuth0 } from '@mastra/auth-auth0'
77
+
78
+ const auth0Provider = new MastraAuthAuth0({
79
+ authorizeUser: async user => {
80
+ // Custom authorization logic
81
+ return user.email?.endsWith('@yourcompany.com') || false
82
+ },
83
+ })
84
+ ```
85
+
86
+ > **Info:** Visit [MastraAuthAuth0](https://mastra.ai/reference/auth/auth0) for all available configuration options.
87
+
88
+ ## Client-side setup
89
+
90
+ When using Auth0 auth, you'll need to set up the Auth0 React SDK, authenticate users, and retrieve their access tokens to pass to your Mastra requests.
91
+
92
+ ### Setting up Auth0 React SDK
93
+
94
+ First, install and configure the Auth0 React SDK in your application:
95
+
96
+ ```bash
97
+ npm install @auth0/auth0-react
98
+ ```
99
+
100
+ ```typescript
101
+ import React from 'react'
102
+ import { Auth0Provider } from '@auth0/auth0-react'
103
+
104
+ const Auth0ProviderWithHistory = ({ children }) => {
105
+ return (
106
+ <Auth0Provider
107
+ domain={process.env.REACT_APP_AUTH0_DOMAIN}
108
+ clientId={process.env.REACT_APP_AUTH0_CLIENT_ID}
109
+ authorizationParams={{
110
+ redirect_uri: window.location.origin,
111
+ audience: process.env.REACT_APP_AUTH0_AUDIENCE,
112
+ scope: 'read:current_user update:current_user_metadata',
113
+ }}
114
+ >
115
+ {children}
116
+ </Auth0Provider>
117
+ )
118
+ }
119
+
120
+ export default Auth0ProviderWithHistory
121
+ ```
122
+
123
+ ### Retrieving access tokens
124
+
125
+ Use the Auth0 React SDK to authenticate users and retrieve their access tokens:
126
+
127
+ ```typescript
128
+ import { useAuth0 } from '@auth0/auth0-react'
129
+
130
+ export const useAuth0Token = () => {
131
+ const { getAccessTokenSilently } = useAuth0()
132
+
133
+ const getAccessToken = async () => {
134
+ const token = await getAccessTokenSilently()
135
+ return token
136
+ }
137
+
138
+ return { getAccessToken }
139
+ }
140
+ ```
141
+
142
+ > **Note:** Refer to the [Auth0 React SDK documentation](https://auth0.com/docs/libraries/auth0-react) for more authentication methods and configuration options.
143
+
144
+ ## Configuring `MastraClient`
145
+
146
+ When `auth` is enabled, all requests made with `MastraClient` must include a valid Auth0 access token in the `Authorization` header:
147
+
148
+ ```typescript
149
+ import { MastraClient } from '@mastra/client-js'
150
+
151
+ export const createMastraClient = (accessToken: string) => {
152
+ return new MastraClient({
153
+ baseUrl: 'https://<mastra-api-url>',
154
+ headers: {
155
+ Authorization: `Bearer ${accessToken}`,
156
+ },
157
+ })
158
+ }
159
+ ```
160
+
161
+ > **Info:** The access token must be prefixed with `Bearer` in the Authorization header.
162
+ >
163
+ > Visit [Mastra Client SDK](https://mastra.ai/docs/server/mastra-client) for more configuration options.
164
+
165
+ ### Making authenticated requests
166
+
167
+ Once `MastraClient` is configured with the Auth0 access token, you can send authenticated requests:
168
+
169
+ **React**:
170
+
171
+ ```tsx
172
+ import React, { useState } from 'react'
173
+ import { useAuth0 } from '@auth0/auth0-react'
174
+ import { MastraClient } from '@mastra/client-js'
175
+
176
+ export const MastraApiTest = () => {
177
+ const { getAccessTokenSilently } = useAuth0()
178
+ const [result, setResult] = useState(null)
179
+
180
+ const callMastraApi = async () => {
181
+ const token = await getAccessTokenSilently()
182
+
183
+ const mastra = new MastraClient({
184
+ baseUrl: 'http://localhost:4111',
185
+ headers: {
186
+ Authorization: `Bearer ${token}`,
187
+ },
188
+ })
189
+
190
+ const weatherAgent = mastra.getAgent('weatherAgent')
191
+ const response = await weatherAgent.generate("What's the weather like in New York")
192
+
193
+ setResult(response.text)
194
+ }
195
+
196
+ return (
197
+ <div>
198
+ <button onClick={callMastraApi}>Test Mastra API</button>
199
+
200
+ {result && (
201
+ <div className="result">
202
+ <h6>Result:</h6>
203
+ <pre>{result}</pre>
204
+ </div>
205
+ )}
206
+ </div>
207
+ )
208
+ }
209
+ ```
210
+
211
+ **cURL**:
212
+
213
+ ```bash
214
+ curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \
215
+ -H "Content-Type: application/json" \
216
+ -H "Authorization: Bearer <your-auth0-access-token>" \
217
+ -d '{
218
+ "messages": "Weather in London"
219
+ }'
220
+ ```
@@ -0,0 +1,132 @@
1
+ # MastraAuthClerk Class
2
+
3
+ The `MastraAuthClerk` class provides authentication for Mastra using Clerk. It verifies incoming requests using Clerk's authentication system and integrates with the Mastra server using the `auth` option.
4
+
5
+ ## Prerequisites
6
+
7
+ This example uses Clerk authentication. Make sure to add your Clerk credentials to your `.env` file and ensure your Clerk project is properly configured.
8
+
9
+ ```env
10
+ CLERK_PUBLISHABLE_KEY=pk_test_...
11
+ CLERK_SECRET_KEY=sk_test_...
12
+ CLERK_JWKS_URI=https://your-clerk-domain.clerk.accounts.dev/.well-known/jwks.json
13
+ ```
14
+
15
+ > **Note:** You can find these keys in your Clerk Dashboard under "API Keys".
16
+
17
+ ## Installation
18
+
19
+ Before you can use the `MastraAuthClerk` class you have to install the `@mastra/auth-clerk` package.
20
+
21
+ ```bash
22
+ npm install @mastra/auth-clerk@latest
23
+ ```
24
+
25
+ ## Usage example
26
+
27
+ ```typescript
28
+ import { Mastra } from '@mastra/core'
29
+ import { MastraAuthClerk } from '@mastra/auth-clerk'
30
+
31
+ export const mastra = new Mastra({
32
+ server: {
33
+ auth: new MastraAuthClerk({
34
+ publishableKey: process.env.CLERK_PUBLISHABLE_KEY,
35
+ secretKey: process.env.CLERK_SECRET_KEY,
36
+ jwksUri: process.env.CLERK_JWKS_URI,
37
+ }),
38
+ },
39
+ })
40
+ ```
41
+
42
+ > **Info:** The default `authorizeUser` method allows all authenticated users. To customize user authorization, provide a custom `authorizeUser` function when constructing the provider.
43
+ >
44
+ > Visit [MastraAuthClerk](https://mastra.ai/reference/auth/clerk) for all available configuration options.
45
+
46
+ ## Client-side setup
47
+
48
+ When using Clerk auth, you'll need to retrieve the access token from Clerk on the client side and pass it to your Mastra requests.
49
+
50
+ ### Retrieving the access token
51
+
52
+ Use the Clerk React hooks to authenticate users and retrieve their access token:
53
+
54
+ ```typescript
55
+ import { useAuth } from '@clerk/nextjs'
56
+
57
+ export const useClerkAuth = () => {
58
+ const { getToken } = useAuth()
59
+
60
+ const getAccessToken = async () => {
61
+ const token = await getToken()
62
+ return token
63
+ }
64
+
65
+ return { getAccessToken }
66
+ }
67
+ ```
68
+
69
+ > **Info:** Refer to the [Clerk documentation](https://clerk.com/docs) for more information.
70
+
71
+ ## Configuring `MastraClient`
72
+
73
+ When `auth` is enabled, all requests made with `MastraClient` must include a valid Clerk access token in the `Authorization` header:
74
+
75
+ ```typescript
76
+ import { MastraClient } from '@mastra/client-js'
77
+
78
+ export const mastraClient = new MastraClient({
79
+ baseUrl: 'https://<mastra-api-url>',
80
+ headers: {
81
+ Authorization: `Bearer ${accessToken}`,
82
+ },
83
+ })
84
+ ```
85
+
86
+ > **Info:** The access token must be prefixed with `Bearer` in the Authorization header.
87
+ >
88
+ > Visit [Mastra Client SDK](https://mastra.ai/docs/server/mastra-client) for more configuration options.
89
+
90
+ ### Making authenticated requests
91
+
92
+ Once `MastraClient` is configured with the Clerk access token, you can send authenticated requests:
93
+
94
+ **React**:
95
+
96
+ ```tsx
97
+ 'use client'
98
+
99
+ import { useAuth } from '@clerk/nextjs'
100
+ import { MastraClient } from '@mastra/client-js'
101
+
102
+ export const TestAgent = () => {
103
+ const { getToken } = useAuth()
104
+
105
+ async function handleClick() {
106
+ const token = await getToken()
107
+
108
+ const client = new MastraClient({
109
+ baseUrl: 'http://localhost:4111',
110
+ headers: token ? { Authorization: `Bearer ${token}` } : undefined,
111
+ })
112
+
113
+ const weatherAgent = client.getAgent('weatherAgent')
114
+ const response = await weatherAgent.generate("What's the weather like in New York")
115
+
116
+ console.log({ response })
117
+ }
118
+
119
+ return <button onClick={handleClick}>Test Agent</button>
120
+ }
121
+ ```
122
+
123
+ **cURL**:
124
+
125
+ ```bash
126
+ curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \
127
+ -H "Content-Type: application/json" \
128
+ -H "Authorization: Bearer <your-clerk-access-token>" \
129
+ -d '{
130
+ "messages": "Weather in London"
131
+ }'
132
+ ```
@@ -0,0 +1,272 @@
1
+ # MastraAuthFirebase Class
2
+
3
+ The `MastraAuthFirebase` class provides authentication for Mastra using Firebase Authentication. It verifies incoming requests using Firebase ID tokens and integrates with the Mastra server using the `auth` option.
4
+
5
+ ## Prerequisites
6
+
7
+ This example uses Firebase Authentication. Make sure to:
8
+
9
+ 1. Create a Firebase project in the [Firebase Console](https://console.firebase.google.com/)
10
+ 2. Enable Authentication and configure your preferred sign-in methods (Google, Email/Password, etc.)
11
+ 3. Generate a service account key from Project Settings > Service Accounts
12
+ 4. Download the service account JSON file
13
+
14
+ ```env
15
+ FIREBASE_SERVICE_ACCOUNT=/path/to/your/service-account-key.json
16
+ FIRESTORE_DATABASE_ID=(default)
17
+ # Alternative environment variable names:
18
+ # FIREBASE_DATABASE_ID=(default)
19
+ ```
20
+
21
+ > **Note:** Store your service account JSON file securely and never commit it to version control.
22
+
23
+ ## Installation
24
+
25
+ Before you can use the `MastraAuthFirebase` class you have to install the `@mastra/auth-firebase` package.
26
+
27
+ ```bash
28
+ npm install @mastra/auth-firebase@latest
29
+ ```
30
+
31
+ ## Usage examples
32
+
33
+ ### Basic usage with environment variables
34
+
35
+ If you set the required environment variables (`FIREBASE_SERVICE_ACCOUNT` and `FIRESTORE_DATABASE_ID`), you can initialize `MastraAuthFirebase` without any constructor arguments. The class will automatically read these environment variables as configuration:
36
+
37
+ ```typescript
38
+ import { Mastra } from '@mastra/core'
39
+ import { MastraAuthFirebase } from '@mastra/auth-firebase'
40
+
41
+ // Automatically uses FIREBASE_SERVICE_ACCOUNT and FIRESTORE_DATABASE_ID env vars
42
+ export const mastra = new Mastra({
43
+ server: {
44
+ auth: new MastraAuthFirebase(),
45
+ },
46
+ })
47
+ ```
48
+
49
+ ### Custom configuration
50
+
51
+ ```typescript
52
+ import { Mastra } from '@mastra/core'
53
+ import { MastraAuthFirebase } from '@mastra/auth-firebase'
54
+
55
+ export const mastra = new Mastra({
56
+ server: {
57
+ auth: new MastraAuthFirebase({
58
+ serviceAccount: '/path/to/service-account.json',
59
+ databaseId: 'your-database-id',
60
+ }),
61
+ },
62
+ })
63
+ ```
64
+
65
+ ## Configuration
66
+
67
+ The `MastraAuthFirebase` class can be configured through constructor options or environment variables.
68
+
69
+ ### Environment Variables
70
+
71
+ - `FIREBASE_SERVICE_ACCOUNT`: Path to Firebase service account JSON file
72
+ - `FIRESTORE_DATABASE_ID` or `FIREBASE_DATABASE_ID`: Firestore database ID
73
+
74
+ > **Note:** When constructor options are not provided, the class automatically reads these environment variables. This means you can simply call `new MastraAuthFirebase()` without any arguments if your environment variables are properly configured.
75
+
76
+ ### User Authorization
77
+
78
+ By default, `MastraAuthFirebase` uses Firestore to manage user access. It expects a collection named `user_access` with documents keyed by user UIDs. The presence of a document in this collection determines whether a user is authorized.
79
+
80
+ ```text
81
+ user_access/
82
+ {user_uid_1}/ // Document exists = user authorized
83
+ {user_uid_2}/ // Document exists = user authorized
84
+ ```
85
+
86
+ To customize user authorization, provide a custom `authorizeUser` function:
87
+
88
+ ```typescript
89
+ import { MastraAuthFirebase } from '@mastra/auth-firebase'
90
+
91
+ const firebaseAuth = new MastraAuthFirebase({
92
+ authorizeUser: async user => {
93
+ // Custom authorization logic
94
+ return user.email?.endsWith('@yourcompany.com') || false
95
+ },
96
+ })
97
+ ```
98
+
99
+ > **Info:** Visit [MastraAuthFirebase](https://mastra.ai/reference/auth/firebase) for all available configuration options.
100
+
101
+ ## Client-side setup
102
+
103
+ When using Firebase auth, you'll need to initialize Firebase on the client side, authenticate users, and retrieve their ID tokens to pass to your Mastra requests.
104
+
105
+ ### Setting up Firebase on the client
106
+
107
+ First, initialize Firebase in your client application:
108
+
109
+ ```typescript
110
+ import { initializeApp } from 'firebase/app'
111
+ import { getAuth, GoogleAuthProvider } from 'firebase/auth'
112
+
113
+ const firebaseConfig = {
114
+ apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
115
+ authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
116
+ projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
117
+ }
118
+
119
+ const app = initializeApp(firebaseConfig)
120
+ export const auth = getAuth(app)
121
+ export const googleProvider = new GoogleAuthProvider()
122
+ ```
123
+
124
+ ### Authenticating users and retrieving tokens
125
+
126
+ Use Firebase authentication to sign in users and retrieve their ID tokens:
127
+
128
+ ```typescript
129
+ import { signInWithPopup, signOut, User } from 'firebase/auth'
130
+ import { auth, googleProvider } from './firebase'
131
+
132
+ export const signInWithGoogle = async () => {
133
+ try {
134
+ const result = await signInWithPopup(auth, googleProvider)
135
+ return result.user
136
+ } catch (error) {
137
+ console.error('Error signing in:', error)
138
+ throw error
139
+ }
140
+ }
141
+
142
+ export const getIdToken = async (user: User) => {
143
+ try {
144
+ const idToken = await user.getIdToken()
145
+ return idToken
146
+ } catch (error) {
147
+ console.error('Error getting ID token:', error)
148
+ throw error
149
+ }
150
+ }
151
+
152
+ export const signOutUser = async () => {
153
+ try {
154
+ await signOut(auth)
155
+ } catch (error) {
156
+ console.error('Error signing out:', error)
157
+ throw error
158
+ }
159
+ }
160
+ ```
161
+
162
+ > **Note:** Refer to the [Firebase documentation](https://firebase.google.com/docs/auth) for other authentication methods like email/password, phone authentication, and more.
163
+
164
+ ## Configuring `MastraClient`
165
+
166
+ When `auth` is enabled, all requests made with `MastraClient` must include a valid Firebase ID token in the `Authorization` header:
167
+
168
+ ```typescript
169
+ import { MastraClient } from '@mastra/client-js'
170
+
171
+ export const createMastraClient = (idToken: string) => {
172
+ return new MastraClient({
173
+ baseUrl: 'https://<mastra-api-url>',
174
+ headers: {
175
+ Authorization: `Bearer ${idToken}`,
176
+ },
177
+ })
178
+ }
179
+ ```
180
+
181
+ > **Info:** The ID token must be prefixed with `Bearer` in the Authorization header.
182
+ >
183
+ > Visit [Mastra Client SDK](https://mastra.ai/docs/server/mastra-client) for more configuration options.
184
+
185
+ ### Making authenticated requests
186
+
187
+ Once `MastraClient` is configured with the Firebase ID token, you can send authenticated requests:
188
+
189
+ **React**:
190
+
191
+ ```tsx
192
+ 'use client'
193
+
194
+ import { useAuthState } from 'react-firebase-hooks/auth'
195
+ import { MastraClient } from '@mastra/client-js'
196
+ import { auth } from '../lib/firebase'
197
+ import { getIdToken } from '../lib/auth'
198
+
199
+ export const TestAgent = () => {
200
+ const [user] = useAuthState(auth)
201
+
202
+ async function handleClick() {
203
+ if (!user) return
204
+
205
+ const token = await getIdToken(user)
206
+ const client = createMastraClient(token)
207
+
208
+ const weatherAgent = client.getAgent('weatherAgent')
209
+ const response = await weatherAgent.generate("What's the weather like in New York")
210
+
211
+ console.log({ response })
212
+ }
213
+
214
+ return (
215
+ <button onClick={handleClick} disabled={!user}>
216
+ Test Agent
217
+ </button>
218
+ )
219
+ }
220
+ ```
221
+
222
+ **Node.js**:
223
+
224
+ ```typescript
225
+ const express = require('express')
226
+ const admin = require('firebase-admin')
227
+ const { MastraClient } = require('@mastra/client-js')
228
+
229
+ // Initialize Firebase Admin
230
+ admin.initializeApp({
231
+ credential: admin.credential.cert({
232
+ // Your service account credentials
233
+ }),
234
+ })
235
+
236
+ const app = express()
237
+ app.use(express.json())
238
+
239
+ app.post('/generate', async (req, res) => {
240
+ try {
241
+ const { idToken } = req.body
242
+
243
+ // Verify the token
244
+ await admin.auth().verifyIdToken(idToken)
245
+
246
+ const mastra = new MastraClient({
247
+ baseUrl: 'http://localhost:4111',
248
+ headers: {
249
+ Authorization: `Bearer ${idToken}`,
250
+ },
251
+ })
252
+
253
+ const weatherAgent = mastra.getAgent('weatherAgent')
254
+ const response = await weatherAgent.generate("What's the weather like in Nairobi")
255
+
256
+ res.json({ response: response.text })
257
+ } catch (error) {
258
+ res.status(401).json({ error: 'Unauthorized' })
259
+ }
260
+ })
261
+ ```
262
+
263
+ **cURL**:
264
+
265
+ ```bash
266
+ curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \
267
+ -H "Content-Type: application/json" \
268
+ -H "Authorization: Bearer <your-firebase-id-token>" \
269
+ -d '{
270
+ "messages": "Weather in London"
271
+ }'
272
+ ```