### Install Mastra with `create mastra` CLI Source: https://mastra.ai/en/docs/getting-started/installation This command initiates the Mastra project setup wizard, which guides you through creating a new project with example agents, workflows, and tools. It's the fastest way to get started. Dependencies include Node.js 20+ and an API key. ```bash npm create mastra@latest -y ``` ```bash pnpm create mastra@latest -y ``` ```bash yarn create mastra@latest -y ``` ```bash bun create mastra@latest -y ``` -------------------------------- ### Example: Install Text-to-SQL Mastra Template Source: https://mastra.ai/en/docs/getting-started/templates Demonstrates installing a specific Mastra template for a text-to-SQL application using npx. This is a practical example of the `create-mastra` command. ```bash npx create-mastra@latest --template text-to-sql ``` -------------------------------- ### Install Mastra Core with bun Source: https://mastra.ai/en/examples/observability/basic-ai-tracing Installs the Mastra core library using bun. Bun is a fast JavaScript runtime that can also manage packages. ```bash bun add @mastra/core ``` -------------------------------- ### Install Mastra Core with npm Source: https://mastra.ai/en/examples/observability/basic-ai-tracing Installs the Mastra core library using npm. This is the first step in setting up Mastra for AI tracing and other functionalities. ```bash npm install @mastra/core ``` -------------------------------- ### Run Development Server Source: https://mastra.ai/en/docs/getting-started/installation Commands to start the development server using different package managers (npm, pnpm, yarn, bun). This allows for testing the implemented agent and tool setup. ```bash npm run dev ``` ```bash pnpm run dev ``` ```bash yarn run dev ``` ```bash bun run dev ``` -------------------------------- ### Install Mastra MCP Dependencies with pnpm Source: https://mastra.ai/en/examples/agents/deploying-mcp-server Installs the necessary Mastra MCP and core packages, along with the tsup build tool. This command is essential for setting up the project environment. ```bash pnpm add @mastra/mcp @mastra/core tsup ``` -------------------------------- ### Install Mastra Core with pnpm Source: https://mastra.ai/en/examples/observability/basic-ai-tracing Installs the Mastra core library using pnpm. This command is an alternative to npm for dependency management. ```bash pnpm add @mastra/core ``` -------------------------------- ### Install Mastra Template using create-mastra Source: https://mastra.ai/en/reference/templates/overview Installs a Mastra template using the npx command, creating a complete project structure with necessary code and configurations. This is the primary method for starting a new project with a Mastra template. ```shell npx create-mastra@latest --template template-name ``` -------------------------------- ### Install Mastra Core with yarn Source: https://mastra.ai/en/examples/observability/basic-ai-tracing Installs the Mastra core library using yarn. This command is another alternative for managing Node.js dependencies. ```bash yarn add @mastra/core ``` -------------------------------- ### Start Development Server (Shell) Source: https://mastra.ai/en/examples/agents/ai-sdk-v5-integration This shell command starts the Next.js development server using `pnpm`. After executing this command, the application will be accessible at `http://localhost:3000`. ```shell pnpm dev ``` -------------------------------- ### Install Dependencies and Run Inngest Dev Server Source: https://mastra.ai/en/examples/workflows/inngest-workflow Installs necessary Mastra and Inngest packages using npm and starts the Inngest development server for local testing. It configures the server to connect to a local application at http://host.docker.internal:3000/inngest/api. ```bash npm install @mastra/inngest inngest @mastra/core @mastra/deployer @hono/node-server @ai-sdk/openai docker run --rm -p 8288:8288 \ inngest/inngest \ inngest dev -u http://host.docker.internal:3000/inngest/api ``` -------------------------------- ### Set up Mastra MCPServer with TypeScript Source: https://mastra.ai/en/examples/agents/deploying-mcp-server Defines a basic Mastra MCPServer using the stdio transport in TypeScript. It includes importing the MCPServer class and a sample weather tool, then starts the server. Ensure your tools and server name are correctly configured. ```typescript #!/usr/bin/env node import { MCPServer } from "@mastra/mcp"; import { weatherTool } from "./tools"; const server = new MCPServer({ name: "my-mcp-server", version: "1.0.0", tools: { weatherTool }, }); server.startStdio().catch((error) => { console.error("Error running MCP server:", error); process.exit(1); }); ``` -------------------------------- ### Install Cedar-OS CLI Source: https://mastra.ai/en/docs/frameworks/agentic-uis/cedar-os Command to install and run the Cedar-OS CLI for project setup. This is the initial step for integrating Cedar-OS. ```bash npx cedar-os-cli plant-seed ``` -------------------------------- ### Mastra Environment Variables Example (.env.example) Source: https://mastra.ai/en/reference/templates/overview An example file demonstrating required environment variables for Mastra templates. It includes placeholders for API keys for various LLM providers and other services, guiding users on necessary configurations. ```dotenv # LLM provider API keys (choose one or more) OPENAI_API_KEY=your_openai_api_key_here ANTHROPIC_API_KEY=your_anthropic_api_key_here GOOGLE_GENERATIVE_AI_API_KEY=your_google_api_key_here # Other service API keys as needed OTHER_SERVICE_API_KEY=your_api_key_here ``` -------------------------------- ### Package Installation (npm) Source: https://mastra.ai/en/docs/memory/storage/memory-with-libsql Lists the npm packages required to use Mastra's LibSQL memory integration and fastembed for local embeddings. These commands ensure that the necessary libraries are installed in the project to run the provided code examples. ```bash npm install @mastra/libsql ``` ```bash npm install @mastra/fastembed ``` -------------------------------- ### Multi-Environment Setup with Vector Query Tools (JavaScript) Source: https://mastra.ai/en/examples/rag/usage/database-specific-config Demonstrates setting up vector query tools with different configurations for development, staging, and production environments in JavaScript. It covers creating environment-specific tools and dynamically switching environments at runtime using RuntimeContext. ```JavaScript import { openai } from "@ai-sdk/openai"; import { createVectorQueryTool } from "@mastra/rag"; import { RuntimeContext } from "@mastra/core/runtime-context"; // Base configuration const createSearchTool = (environment) => { return createVectorQueryTool({ vectorStoreName: "pinecone", indexName: "documents", model: openai.embedding("text-embedding-3-small"), databaseConfig: { pinecone: { namespace: environment } } }); }; // Create environment-specific tools const devSearchTool = createSearchTool('dev'); const prodSearchTool = createSearchTool('prod'); // Or use runtime override const dynamicSearchTool = createVectorQueryTool({ vectorStoreName: "pinecone", indexName: "documents", model: openai.embedding("text-embedding-3-small") }); // Switch environment at runtime const switchEnvironment = async (environment, query) => { const runtimeContext = new RuntimeContext(); runtimeContext.set('databaseConfig', { pinecone: { namespace: environment } }); return await dynamicSearchTool.execute({ context: { queryText: query }, mastra, runtimeContext }); }; ``` -------------------------------- ### Multi-Environment Setup with Vector Query Tools (TypeScript) Source: https://mastra.ai/en/examples/rag/usage/database-specific-config Demonstrates setting up vector query tools with different configurations for development, staging, and production environments. It shows how to create environment-specific tools and how to dynamically switch environments at runtime using RuntimeContext. ```TypeScript import { openai } from "@ai-sdk/openai"; import { createVectorQueryTool } from "@mastra/rag"; import { RuntimeContext } from "@mastra/core/runtime-context"; // Base configuration const createSearchTool = (environment: 'dev' | 'staging' | 'prod') => { return createVectorQueryTool({ vectorStoreName: "pinecone", indexName: "documents", model: openai.embedding("text-embedding-3-small"), databaseConfig: { pinecone: { namespace: environment } } }); }; // Create environment-specific tools const devSearchTool = createSearchTool('dev'); const prodSearchTool = createSearchTool('prod'); // Or use runtime override const dynamicSearchTool = createVectorQueryTool({ vectorStoreName: "pinecone", indexName: "documents", model: openai.embedding("text-embedding-3-small") }); // Switch environment at runtime const switchEnvironment = async (environment: string, query: string) => { const runtimeContext = new RuntimeContext(); runtimeContext.set('databaseConfig', { pinecone: { namespace: environment } }); return await dynamicSearchTool.execute({ context: { queryText: query }, mastra, runtimeContext }); }; ``` -------------------------------- ### Initialize Project and Install Dependencies (bun) Source: https://mastra.ai/en/docs/getting-started/installation Initializes a new Node.js project with bun and installs necessary development and core Mastra dependencies, including TypeScript. Requires Node.js 20+. ```bash bun init -y bun add -d typescript @types/node mastra@latest bun add @mastra/core@latest zod@^4 ``` -------------------------------- ### Get Agent Instructions (JavaScript) Source: https://mastra.ai/en/reference/agents/getInstructions Retrieves the instructions for an agent. This is a basic usage example without any options. ```javascript await agent.getInstructions(); ``` -------------------------------- ### Install AI SDK v5 and Mastra Dependencies (JSON) Source: https://mastra.ai/en/examples/agents/ai-sdk-v5-integration This `package.json` file lists the project's dependencies, including beta versions of `@ai-sdk/openai`, `@ai-sdk/react`, and Mastra libraries, along with Next.js, React, SWR, and Zod. It's crucial for ensuring compatibility with AI SDK v5. ```json { "dependencies": { "@ai-sdk/openai": "2.0.0-beta.1", "@ai-sdk/react": "2.0.0-beta.1", "@mastra/core": "0.0.0-ai-v5-20250625173645", "@mastra/libsql": "0.0.0-ai-v5-20250625173645", "@mastra/memory": "0.0.0-ai-v5-20250625173645", "next": "15.1.7", "react": "^19.0.0", "react-dom": "^19.0.0", "swr": "^2.3.3", "zod": "^3.25.67" } } ``` -------------------------------- ### Initialize Project and Install Dependencies (npm) Source: https://mastra.ai/en/docs/getting-started/installation Initializes a new Node.js project with npm and installs necessary development and core Mastra dependencies, including TypeScript. Requires Node.js 20+. ```bash npm init -y npm install -D typescript @types/node mastra@latest npm install @mastra/core@latest zod@^4 ``` -------------------------------- ### Install Mastra Client SDK with bun Source: https://mastra.ai/en/docs/server-db/mastra-client Installs the latest version of the Mastra Client SDK using bun. bun is a fast all-in-one JavaScript runtime. ```bash bun add @mastra/client-js@latest ``` -------------------------------- ### OtelExporter - Basic Usage Example Source: https://mastra.ai/en/reference/observability/ai-tracing/exporters/otel Demonstrates the basic setup of the OtelExporter, configuring it to send traces to a Signoz instance using an API key. It shows how to import the exporter and instantiate it with provider-specific settings. ```typescript import { OtelExporter } from '@mastra/otel-exporter'; const exporter = new OtelExporter({ provider: { signoz: { apiKey: process.env.SIGNOZ_API_KEY, region: 'us', } }, }); ``` -------------------------------- ### Initialize Project and Install Dependencies (pnpm) Source: https://mastra.ai/en/docs/getting-started/installation Initializes a new Node.js project with pnpm and installs necessary development and core Mastra dependencies, including TypeScript. Requires Node.js 20+. ```bash pnpm init -y pnpm add -D typescript @types/node mastra@latest pnpm add @mastra/core@latest zod@^4 ``` -------------------------------- ### Initialize Project and Install Dependencies (yarn) Source: https://mastra.ai/en/docs/getting-started/installation Initializes a new Node.js project with yarn and installs necessary development and core Mastra dependencies, including TypeScript. Requires Node.js 20+. ```bash yarn init -y yarn add -D typescript @types/node mastra@latest yarn add @mastra/core@latest zod@^4 ``` -------------------------------- ### Usage Example Source: https://mastra.ai/en/reference/deployer/deployer An example demonstrating how to create a custom deployer by extending the abstract Deployer class and implementing the `deploy` method. ```APIDOC ## Usage Example ```typescript import { Deployer } from "@mastra/deployer"; // Create a custom deployer by extending the abstract Deployer class class CustomDeployer extends Deployer { constructor() { super({ name: "custom-deployer" }); } // Implement the abstract deploy method async deploy(outputDirectory: string): Promise { // Prepare the output directory await this.prepare(outputDirectory); // Bundle the application await this._bundle("server.ts", "mastra.ts", outputDirectory); // Custom deployment logic // ... } } ``` ``` -------------------------------- ### Initialize Mastra Project with CLI Source: https://mastra.ai/en/docs/frameworks/agentic-uis/openrouter Initializes a new Mastra project using the npx create-mastra command. This CLI tool guides users through project setup, including naming, component selection (Agents recommended), and initial provider choice (OpenAI recommended, to be manually changed later). ```bash npx create-mastra@latest ``` -------------------------------- ### Start Mastra Dev Server (CLI) Source: https://mastra.ai/en/docs/frameworks/web-frameworks/sveltekit Starts the Mastra Dev Server directly using the mastra CLI command. This is an alternative to using npm scripts for starting the development server. ```bash mastra dev:mastra ``` -------------------------------- ### Retrieve Trace IDs from Mastra Workflow Runs Source: https://mastra.ai/en/docs/observability/ai-tracing This example illustrates how to get the `traceId` from Mastra workflow executions, both for asynchronous runs started with `createRunAsync` and for streamed workflows. The trace ID is available in the result of `start` and in the final state of a streamed workflow. ```javascript // Create a workflow run const run = await mastra.getWorkflow('myWorkflow').createRunAsync(); // Start the workflow const result = await run.start({ inputData: { data: 'process this' } }); console.log('Trace ID:', result.traceId); // Or stream the workflow const { stream, getWorkflowState } = run.stream({ inputData: { data: 'process this' } }); // Get the final state which includes the trace ID const finalState = await getWorkflowState(); console.log('Trace ID:', finalState.traceId); ``` -------------------------------- ### Manually Create Mastra Project Directory Source: https://mastra.ai/en/docs/getting-started/installation Creates a new directory for your Mastra project and navigates into it. This is the first step in the manual installation process. ```bash mkdir my-first-agent && cd my-first-agent ``` -------------------------------- ### Custom OpenTelemetry Exporter Setup (Langfuse Example) Source: https://mastra.ai/en/docs/observability/nextjs-tracing This option demonstrates setting up a custom OpenTelemetry exporter, using Langfuse as an example. It involves installing necessary dependencies and creating an `instrumentation.ts` file to initialize the NodeSDK with a specific exporter and resource attributes, including the service name. ```bash npm install @opentelemetry/api langfuse-vercel ``` ```typescript import { NodeSDK, ATTR_SERVICE_NAME, resourceFromAttributes, } from "@mastra/core/telemetry/otel-vendor"; import { LangfuseExporter } from "langfuse-vercel"; export function register() { const exporter = new LangfuseExporter({ // ... Langfuse config }); const sdk = new NodeSDK({ resource: resourceFromAttributes({ [ATTR_SERVICE_NAME]: "ai", }), traceExporter: exporter, }); sdk.start(); } ``` -------------------------------- ### Install Mastra Client SDK with pnpm Source: https://mastra.ai/en/docs/server-db/mastra-client Installs the latest version of the Mastra Client SDK using pnpm. pnpm is a performant package manager that saves disk space and speeds up installations. ```bash pnpm add @mastra/client-js@latest ``` -------------------------------- ### Register Mastra Agent (TypeScript) Source: https://mastra.ai/en/examples/agents/runtime-context Registers a new Mastra agent named 'supportAgent' with the Mastra core instance. This is the initial setup step required before using any agents. It imports the Mastra class and the specific agent implementation. ```typescript import { Mastra } from "@mastra/core/mastra"; import { supportAgent } from "./agents/support-agent"; export const mastra = new Mastra({ agents: { supportAgent } }); ``` -------------------------------- ### Start Mastra Development Server Source: https://mastra.ai/en/docs/getting-started/studio Instructions to start the local Mastra development server using various package managers. This command initiates the server, making the Playground UI and REST API accessible. ```shell npm run dev ``` ```shell pnpm run dev ``` ```shell yarn run dev ``` ```shell bun run dev ``` ```shell mastra dev ``` -------------------------------- ### Copy Environment Example File Source: https://mastra.ai/en/docs/getting-started/templates Copies the example environment file (`.env.example`) to a new file named `.env`. This is a common step to set up project-specific configurations and secrets. ```bash cp .env.example .env ``` -------------------------------- ### Install Mastra AI Evals Source: https://mastra.ai/en/examples/evals/content-similarity Installs the Mastra AI Evals package, which provides tools for evaluating content similarity. This is the first step before using any of the provided metrics. ```bash npm install @mastra/evals ``` -------------------------------- ### Install Mastra Core Package Source: https://mastra.ai/en/docs/agents/overview Installs the Mastra core package required for agent functionality. This is a prerequisite for setting up and creating agents. ```bash npm install @mastra/core ``` -------------------------------- ### Install Dependencies with pnpm Source: https://mastra.ai/en/reference/observability/otel-tracing/providers/keywordsai Installs the necessary project dependencies using the pnpm package manager. Ensure you have Node.js and pnpm installed globally. ```bash pnpm install ``` -------------------------------- ### Install Mastra Supabase Auth Package Source: https://mastra.ai/en/docs/auth/supabase Install the `@mastra/auth-supabase` package using npm. This is a prerequisite for using the MastraAuthSupabase class. ```bash npm install @mastra/auth-supabase@latest ``` -------------------------------- ### Install Voice Provider Package Source: https://mastra.ai/en/docs/voice/speech-to-text Install specific voice provider packages using pnpm to extend Mastra's STT capabilities. This example shows how to add the OpenAI provider. ```bash pnpm add @mastra/voice-openai # Example for OpenAI ``` -------------------------------- ### Use Deployed Mastra MCPServer with MCPClient Source: https://mastra.ai/en/examples/agents/deploying-mcp-server Demonstrates how to instantiate an MCPClient and configure it to use a deployed Mastra MCPServer. It shows how to specify the command to run the server package, commonly using 'npx', and retrieves tools and toolsets from the server configuration. ```typescript import { MCPClient } from "@mastra/mcp"; const mcp = new MCPClient({ servers: { // Give this MCP server instance a name yourServerName: { command: "npx", args: ["-y", "@your-org-name/your-package-name@latest"], // Replace with your package name }, }, }); // You can then get tools or toolsets from this configuration to use in your agent const tools = await mcp.getTools(); const toolsets = await mcp.getToolsets(); ``` -------------------------------- ### QdrantVector Constructor and Basic Usage (Python) Source: https://mastra.ai/en/reference/rag/qdrant This snippet demonstrates how to initialize the QdrantVector store with connection details and API key, and includes an example of a basic query operation. It highlights the use of indexName, queryVector, and topK parameters. ```python from langchain_community.vectorstores import QdrantVector # Initialize QdrantVector store store = QdrantVector( url="https://xyz-example.eu-central.aws.cloud.qdrant.io:6333", apiKey="YOUR_API_KEY", https=True ) # Example query query_vector = [0.1, 0.2, 0.3] # Replace with your actual query vector results = store.query( indexName="my_index", queryVector=query_vector, topK=5 ) print(results) ``` -------------------------------- ### Create a New Mastra Project (Bun) Source: https://mastra.ai/en/reference/cli/create-mastra Initializes a new Mastra project using Bun. This command scaffolds a complete Mastra setup in a dedicated directory. It runs interactively by default. ```bash bun create mastra@latest ``` -------------------------------- ### Example: Low Word Inclusion Score in JavaScript Source: https://mastra.ai/en/examples/evals/custom-native-javascript-eval Shows an example of using the `WordInclusionMetric` to get a low score. In this scenario, none of the query words are present in the response, resulting in a score of 0. ```javascript import { WordInclusionMetric } from "./mastra/evals/example-word-inclusion"; const metric = new WordInclusionMetric(); const query = "Colombia, Brazil, Panama"; const response = "Let's go to Mexico"; const result = await metric.measure(query, response); console.log(result); ``` -------------------------------- ### Vercel's OpenTelemetry Setup Source: https://mastra.ai/en/docs/observability/nextjs-tracing This method utilizes Vercel's built-in OpenTelemetry integration. It requires installing the `@vercel/otel` package and creating an `instrumentation.ts` file to register the OpenTelemetry setup with your specified service name. ```bash npm install @opentelemetry/api @vercel/otel ``` ```typescript import { registerOTel } from "@vercel/otel"; export function register() { registerOTel({ serviceName: "your-project-name" }); } ``` -------------------------------- ### Install Arize Exporter with bun Source: https://mastra.ai/en/docs/observability/ai-tracing/exporters/arize Installs the Arize Exporter package using bun. Bun is a fast JavaScript runtime and package manager. ```bash bun add @mastra/arize ``` -------------------------------- ### Install Mastra Packages (npm, yarn, pnpm, bun) Source: https://mastra.ai/en/docs/frameworks/web-frameworks/sveltekit Installs the necessary Mastra packages for SvelteKit integration. This includes the core Mastra library and specific adapters like `@mastra/libsql`. Ensure you have Node.js and a package manager installed. ```npm npm install mastra@latest @mastra/core@latest @mastra/libsql@latest ``` ```yarn yarn add mastra@latest @mastra/core@latest @mastra/libsql@latest ``` ```pnpm pnpm add mastra@latest @mastra/core@latest @mastra/libsql@latest ``` ```bun bun add mastra@latest @mastra/core@latest @mastra/libsql@latest ``` -------------------------------- ### Install AIHubMix Provider with bun Source: https://mastra.ai/en/models/providers/aihubmix Installs the AIHubMix AI SDK provider package using the Bun runtime. This command facilitates the integration of AIHubMix models into Mastra applications. ```bash bun add @aihubmix/ai-sdk-provider ``` -------------------------------- ### Example Usage: Single and Multiple Embeddings with AI SDK Source: https://mastra.ai/en/reference/rag/embeddings This example demonstrates how to use both the `embed` and `embedMany` functions from the AI SDK. It shows the setup for generating a single embedding and multiple embeddings using the OpenAI embedding model. ```typescript import { embed, embedMany } from "ai"; import { openai } from "@ai-sdk/openai"; // Single embedding const singleResult = await embed({ model: openai.embedding("text-embedding-3-small"), value: "What is the meaning of life?", }); // Multiple embeddings const multipleResult = await embedMany({ model: openai.embedding("text-embedding-3-small"), values: [ "First question about life", "Second question about universe", "Third question about everything", ], }); ``` -------------------------------- ### Install Mastra Template using bun Source: https://mastra.ai/en/docs/getting-started/templates Installs a Mastra template using the bun runtime. This command uses `bun create` to run the latest `create-mastra` and allows specifying a template. ```bash bun create mastra@latest --template template-name ``` -------------------------------- ### Mastra Client Initialization Source: https://mastra.ai/en/reference/client-js/mastra-client Example of how to initialize the Mastra Client with a base URL. ```APIDOC ## Mastra Client Initialization ### Description Initializes the Mastra Client with the necessary configuration, including the base URL for API requests. ### Method `new MastraClient(options)` ### Parameters #### Request Body - **baseUrl** (string) - Required - The base URL for the Mastra API. - **retries** (number) - Optional - The number of times a request will be retried on failure. - **backoffMs** (number) - Optional - The initial delay in milliseconds before retrying a failed request. - **maxBackoffMs** (number) - Optional - The maximum backoff time in milliseconds. - **headers** (Record) - Optional - Custom HTTP headers to include with every request. - **credentials** (\"omit\" | \"same-origin\" | \"include\") - Optional - Credentials mode for requests. ### Request Example ```typescript import { MastraClient } from "@mastra/client-js"; export const mastraClient = new MastraClient({ baseUrl: "http://localhost:4111/", retries: 5, backoffMs: 500, }); ``` ### Response #### Success Response (200) - **MastraClient** - An instance of the MastraClient. #### Response Example ```json // No direct JSON response, returns a MastraClient instance. ``` ``` -------------------------------- ### Install CloudflareDeployer - npm Source: https://mastra.ai/en/docs/deployment/serverless-platforms/cloudflare-deployer Installs the CloudflareDeployer package from npm. This is the first step to using the deployer for Cloudflare Workers. ```bash npm install @mastra/deployer-cloudflare@latest ``` -------------------------------- ### Install Vercel Deployer Package Source: https://mastra.ai/en/docs/deployment/serverless-platforms/vercel-deployer Installs the latest version of the Vercel deployer package for Mastra applications using npm. ```bash npm install @mastra/deployer-vercel@latest ``` -------------------------------- ### Example Usage of RAG Agent for Question Answering Source: https://mastra.ai/en/examples/rag/usage/basic-rag Demonstrates how to use the configured RAG agent to generate a response based on a prompt and retrieved context. The prompt guides the agent to use only the provided context for its answer. ```typescript const prompt = " [Insert query based on document here] Please base your answer only on the context provided in the tool. If the context doesn't contain enough information to fully answer the question, please state that explicitly. "; const completion = await agent.generate(prompt); console.log(completion.text); ``` -------------------------------- ### Start Mastra Dev Server (npm) Source: https://mastra.ai/en/docs/frameworks/web-frameworks/sveltekit Starts the Mastra Dev Server using the npm run command. This command exposes agents as REST endpoints locally. ```bash npm run dev:mastra ``` -------------------------------- ### Install MastraAuthAuth0 Package Source: https://mastra.ai/en/docs/auth/auth0 Installs the `@mastra/auth-auth0` package using npm. This is a prerequisite for using the MastraAuthAuth0 class in your project. ```bash npm install @mastra/auth-auth0@latest ``` -------------------------------- ### Shell Curl Command to Start Mastra Workflow Source: https://mastra.ai/en/examples/workflows_legacy/workflow-variables This curl command demonstrates how to asynchronously start the 'user-registration' Mastra workflow. It sends a JSON payload containing user email, name, and age to the specified API endpoint. ```shell curl --location 'http://localhost:4111/api/workflows/user-registration/start-async' \ --header 'Content-Type: application/json' \ --data '{ "email": "user@example.com", "name": "John Doe", "age": 25 }' ``` -------------------------------- ### Install xAI Provider Package using bun Source: https://mastra.ai/en/models/providers/xai This command installs the xAI provider directly as a standalone package using bun. Bun is a fast JavaScript runtime and package manager, offering an alternative for installing the xAI provider. ```bash bun add @ai-sdk/xai ``` -------------------------------- ### Navigate and Configure Mastra Project Source: https://mastra.ai/en/reference/templates/overview Provides commands for navigating into the newly created project directory, copying environment variable configuration, and installing project dependencies. These steps are crucial after template installation. ```shell cd your-project-name cp .env.example .env npm install ``` -------------------------------- ### ArizeExporter Usage: Arize AX Configuration Source: https://mastra.ai/en/reference/observability/ai-tracing/exporters/arize Example demonstrating the configuration of ArizeExporter for Arize AX. This setup requires a `spaceId`, an `apiKey`, and the `projectName`. ```javascript import { ArizeExporter } from '@mastra/arize'; const exporter = new ArizeExporter({ spaceId: process.env.ARIZE_SPACE_ID!, apiKey: process.env.ARIZE_API_KEY!, projectName: 'my-ai-project', }); ``` -------------------------------- ### Install LangSmith Exporter with bun Source: https://mastra.ai/en/docs/observability/ai-tracing/exporters/langsmith Installs the LangSmith Exporter package using bun. Bun is a fast JavaScript runtime and toolkit. ```bash bun add @mastra/langsmith ``` -------------------------------- ### Install @mastra/mcp using npm Source: https://mastra.ai/en/guides/guide/notes-mcp-server Installs the @mastra/mcp package into your project. This is a Node.js package manager command. ```bash npm install @mastra/mcp ``` -------------------------------- ### Install Mastra Client SDK with npm Source: https://mastra.ai/en/docs/server-db/mastra-client Installs the latest version of the Mastra Client SDK using npm. This is the first step to integrating Mastra's capabilities into your project. ```bash npm install @mastra/client-js@latest ``` -------------------------------- ### Basic Mastra Firebase Authentication Setup (TypeScript) Source: https://mastra.ai/en/reference/auth/firebase This example demonstrates the basic setup for Mastra authentication using Firebase. It automatically utilizes environment variables for Firebase service account and Firestore database ID. The Mastra server is configured with the MastraAuthFirebase instance. ```typescript import { Mastra, } from "@mastra/core/mastra"; import { MastraAuthFirebase, } from "@mastra/auth-firebase"; // Automatically uses FIREBASE_SERVICE_ACCOUNT and FIRESTORE_DATABASE_ID env vars export const mastra = new Mastra({ // .. server: { experimental_auth: new MastraAuthFirebase(), }, }); ``` -------------------------------- ### High Example: Mastra Agent Response Validation (TypeScript) Source: https://mastra.ai/en/examples/processors/response-validator Demonstrates a successful response validation scenario using a Mastra agent configured with `ResponseValidator`. The agent's prompt is designed to elicit keywords that the validator requires, resulting in a passed validation. This example includes the agent setup and the generation call. ```typescript import { Agent } from "@mastra/core/agent"; import { openai } from "@ai-sdk/openai"; import { ResponseValidator } from "./mastra/processors/response-validator"; // Create agent that requires AI-related keywords export const agent = new Agent({ name: 'validated-agent', instructions: 'You are an AI expert. Always mention artificial intelligence and machine learning when discussing AI topics.', model: openai("gpt-4o"), outputProcessors: [ new ResponseValidator(['artificial intelligence', 'machine learning']), ], }); const result = await agent.generate("Explain how AI systems learn from data."); console.log("✅ Response passed validation:"); console.log(result.text); ``` -------------------------------- ### Install OpenAI SDK using bun Source: https://mastra.ai/en/models/providers/openai This snippet shows how to install the OpenAI SDK as a standalone package using bun. This package can be used directly, bypassing the Mastra model router for specific use cases. No other dependencies are needed for this installation command. ```bash bun add @ai-sdk/openai ``` -------------------------------- ### Install Mastra Inngest Packages Source: https://mastra.ai/en/docs/workflows/inngest-workflow Installs the necessary Mastra packages for Inngest integration via npm. ```bash npm install @mastra/inngest @mastra/core @mastra/deployer ``` -------------------------------- ### Configure package.json for Mastra MCPServer Build Source: https://mastra.ai/en/examples/agents/deploying-mcp-server Configures the 'bin' entry in package.json to point to the compiled server file and defines a 'build:mcp' script using tsup. This script compiles the TypeScript server file, generates type definitions, and makes the output executable. ```json { "bin": "dist/stdio.js", "scripts": { "build:mcp": "tsup src/mastra/stdio.ts --format esm --no-splitting --dts && chmod +x dist/stdio.js" } } ``` -------------------------------- ### Get SSE Transport Object Source: https://mastra.ai/en/reference/tools/mcp-server Retrieves the SSEServerTransport object if the server was started with `startSSE()`. This is mainly for internal checks or testing and returns an object or undefined. ```typescript getSseTransport(): SSEServerTransport | undefined ``` -------------------------------- ### Get Stdio Transport Object Source: https://mastra.ai/en/reference/tools/mcp-server Retrieves the StdioServerTransport object if the server was started with `startStdio()`. This is primarily for internal checks or testing and returns an object or undefined. ```typescript getStdioTransport(): StdioServerTransport | undefined ``` -------------------------------- ### Build Mastra Project Source: https://mastra.ai/en/docs/deployment/server-deployment Initiates the Mastra project build process. This command compiles your Mastra application into a production-ready format. No specific input or output configurations are provided by default. ```bash mastra build ``` -------------------------------- ### Bootstrap Mastra Server Project Source: https://mastra.ai/en/docs/frameworks/agentic-uis/assistant-ui This command initializes a new Mastra project using an interactive wizard. It prompts for a project name and sets up basic configurations for your Mastra server. Ensure npx is available in your environment. ```bash npx create-mastra@latest ``` -------------------------------- ### Get Streamable HTTP Transport Object Source: https://mastra.ai/en/reference/tools/mcp-server Retrieves the StreamableHTTPServerTransport object if the server was started with `startHTTP()`. This is mainly for internal checks or testing and returns an object or undefined. ```typescript getStreamableHTTPTransport(): StreamableHTTPServerTransport | undefined ``` -------------------------------- ### Usage Example Source: https://mastra.ai/en/reference/observability/ai-tracing/exporters/langsmith Demonstrates how to import and initialize the LangSmithExporter. ```APIDOC ## Usage ### Description Example of initializing the LangSmithExporter. ### Code Example ```javascript import { LangSmithExporter } from '@mastra/langsmith'; const exporter = new LangSmithExporter({ apiKey: process.env.LANGSMITH_API_KEY, apiUrl: 'https://api.smith.langchain.com', logLevel: 'info', }); ``` ``` -------------------------------- ### Specify Watch Event Type with .watch() in JavaScript Source: https://mastra.ai/en/reference/workflows/run-methods/watch This JavaScript example shows an extended usage of the .watch() method, explicitly specifying the 'watch' event type. This ensures that only step completion events are monitored. The callback function logs the current step ID. Similar to the basic example, a run is created and then started after the watch is set up. ```javascript const run = await workflow.createRunAsync(); run.watch((event) => { console.log(event?.payload?.currentStep?.id); }, "watch"); const result = await run.start({ inputData: { value: "initial data" } }); ``` -------------------------------- ### Get Hono SSE Transport Object Source: https://mastra.ai/en/reference/tools/mcp-server Retrieves the SSETransport object if the server was started with `startHonoSSE()`. Similar to `getSseTransport`, this is for internal checks or testing and returns an object or undefined. ```typescript getSseHonoTransport(): SSETransport | undefined ``` -------------------------------- ### KeywordCoverageMetric - Examples with Analysis Source: https://mastra.ai/en/reference/evals/keyword-coverage Provides examples of using the `measure` method with different scenarios, including perfect, partial, and technical term coverage. ```APIDOC ## KeywordCoverageMetric - Examples with Analysis ### Description This section provides concrete examples demonstrating the `measure` method's behavior with various inputs, illustrating perfect coverage, partial coverage, and the handling of technical terms. ### Examples #### Perfect Coverage Example ```javascript import { KeywordCoverageMetric } from "@mastra/evals/nlp"; const metric = new KeywordCoverageMetric(); const result1 = await metric.measure( "The quick brown fox jumps over the lazy dog", "A quick brown fox jumped over a lazy dog" ); // Expected output: { score: 1.0, info: { matchedKeywords: 6, totalKeywords: 6 } } ``` #### Partial Coverage Example ```javascript import { KeywordCoverageMetric } from "@mastra/evals/nlp"; const metric = new KeywordCoverageMetric(); const result2 = await metric.measure( "Python features include easy syntax, dynamic typing, and extensive libraries", "Python has simple syntax and many libraries" ); // Expected output: { score: 0.67, info: { matchedKeywords: 4, totalKeywords: 6 } } (approximate) ``` #### Technical Terms Example ```javascript import { KeywordCoverageMetric } from "@mastra/evals/nlp"; const metric = new KeywordCoverageMetric(); const result3 = await metric.measure( "Discuss React.js component lifecycle and state management", "React components have lifecycle methods and manage state" ); // Expected output: { score: 1.0, info: { matchedKeywords: 4, totalKeywords: 4 } } ``` ### Scoring Details The metric evaluates keyword coverage by matching keywords with the following features: * Common word and stop word filtering (e.g., “the”, “a”, “and”) * Case-insensitive matching * Word form variation handling * Special handling of technical terms and compound words ### Scoring Process 1. Processes keywords from input and output: * Filters out common words and stop words * Normalizes case and word forms * Handles special terms and compounds 2. Calculates keyword coverage: * Matches keywords between texts * Counts successful matches * Computes coverage ratio Final score: `(matched_keywords / total_keywords) * scale` (default scale 0-1) ``` -------------------------------- ### Define AITracing Interface Source: https://mastra.ai/en/reference/observability/ai-tracing/interfaces The primary interface for AI Tracing in Mastra AI. It provides methods to get configuration, exporters, processors, logger, start spans, and shut down tracing. ```typescript interface AITracing { /** Get current configuration */ getConfig(): Readonly>; /** Get all exporters */ getExporters(): readonly AITracingExporter[]; /** Get all processors */ getProcessors(): readonly AISpanProcessor[]; /** Get the logger instance (for exporters and other components) */ getLogger(): IMastraLogger; /** Start a new span of a specific AISpanType */ startSpan(options: StartSpanOptions): AISpan; /** Shutdown AI tracing and clean up resources */ shutdown(): Promise; } ``` -------------------------------- ### Install Mastra MCP Dependency Source: https://mastra.ai/en/docs/tools-mcp/mcp-overview Installs the necessary Mastra MCP package using npm. This is the first step to enabling MCP functionality in your project. ```bash npm install @mastra/mcp@latest ``` -------------------------------- ### Run and Resume Workflow - TypeScript Source: https://mastra.ai/en/reference/workflows/workflow This example illustrates how to initiate and manage a workflow run asynchronously. It shows starting a workflow, handling a suspended state, and resuming the workflow with the appropriate data. ```typescript import { mastra } from "./mastra"; const run = await mastra.getWorkflow("workflow").createRunAsync(); const result = await run.start({...}); if (result.status === "suspended") { const resumedResult = await run.resume({...}); } ``` -------------------------------- ### Initialize Mastra Application Orchestrator Source: https://mastra.ai/en/reference/core/mastra-class Example of initializing the Mastra class, registering workflows, agents, storage, and logger. It demonstrates setting up the core components of a Mastra application. ```typescript import { Mastra } from '@mastra/core/mastra'; import { PinoLogger } from '@mastra/loggers'; import { LibSQLStore } from '@mastra/libsql'; import { weatherWorkflow } from './workflows/weather-workflow'; import { weatherAgent } from './agents/weather-agent'; export const mastra = new Mastra({ workflows: { weatherWorkflow }, agents: { weatherAgent }, storage: new LibSQLStore({ url: ":memory:", }), logger: new PinoLogger({ name: 'Mastra', level: 'info', }), }); ``` -------------------------------- ### Workflow Execution with Query in TypeScript Source: https://mastra.ai/en/examples/rag/usage/cot-workflow-rag Executes a configured Mastra AI workflow with a given query. It defines the prompt, creates a run, and starts the workflow, logging the results. ```typescript const query = "What are the main adaptation strategies for farmers?"; console.log("\nQuery:", query); const prompt = ` Please answer the following question: ${query} Please base your answer only on the context provided in the tool. If the context doesn't contain enough information to fully answer the question, please state that explicitly. `; const { runId, start } = await ragWorkflow.createRunAsync(); console.log("Run:", runId); const workflowResult = await start({ triggerData: { query: prompt, }, }); console.log("\nThought Process:"); console.log(workflowResult.results); ``` -------------------------------- ### Observe Workflow Stream with JavaScript Source: https://mastra.ai/en/reference/streaming/workflows/observeStreamVNext This example demonstrates how to use .observeStreamVNext() to get a ReadableStream of events from a running workflow. It first creates a run, streams initial data, then observes the stream for event chunks. ```javascript const run = await workflow.createRunAsync(); run.streamVNext({ inputData: { value: "initial data", }, }); const stream = await run.observeStreamVNext(); for await (const chunk of stream) { console.log(chunk); } ``` -------------------------------- ### Get Default Agent Generation Options Source: https://mastra.ai/en/reference/agents/getDefaultGenerateOptions This example demonstrates how to retrieve the default generation options for an agent. The method `getDefaultGenerateOptions()` is called without any arguments, returning the agent's pre-configured settings. ```javascript await agent.getDefaultGenerateOptions(); ``` -------------------------------- ### Create a New Mastra Project (PNPM) Source: https://mastra.ai/en/reference/cli/create-mastra Initializes a new Mastra project using PNPM. This command scaffolds a complete Mastra setup in a dedicated directory. It runs interactively by default. ```bash pnpm create mastra@latest ``` -------------------------------- ### Configure Mastra Server with Clerk Authentication Source: https://mastra.ai/en/docs/auth/clerk Example of initializing the Mastra server with MastraAuthClerk for Clerk authentication. It requires Clerk credentials from environment variables. This setup enables server-side authentication for Mastra. ```typescript import { Mastra } from "@mastra/core/mastra"; import { MastraAuthClerk } from '@mastra/auth-clerk'; export const mastra = new Mastra({ // .. server: { experimental_auth: new MastraAuthClerk({ publishableKey: process.env.CLERK_PUBLISHABLE_KEY, secretKey: process.env.CLERK_SECRET_KEY, jwksUri: process.env.CLERK_JWKS_URI }), }, }); ``` -------------------------------- ### Start Workflow Run with Multiple Inputs Source: https://mastra.ai/en/docs/workflows/control-flow Provides an example of initiating a workflow run with multiple inputs. Each input object is processed sequentially through the specified step, demonstrating how to handle batch data processing. ```typescript import { mastra } from "./mastra"; const run = await mastra.getWorkflow("testWorkflow").createRunAsync(); const result = await run.start({ inputData: [{ number: 10 }, { number: 100 }, { number: 200 }] }); ``` -------------------------------- ### Chunk Markdown Content with MDocument Source: https://mastra.ai/en/examples/rag/chunking/chunk-markdown This example demonstrates how to load markdown content into an MDocument object and then chunk it into smaller pieces suitable for RAG pipelines. It leverages the MDocument.fromMarkdown() and doc.chunk() methods. Ensure the '@mastra/rag' library is installed. ```typescript import { MDocument } from "@mastra/rag"; const doc = MDocument.fromMarkdown("# Your markdown content..."); const chunks = await doc.chunk(); ``` -------------------------------- ### Get Final Workflow State After Streaming with .stream() in JavaScript Source: https://mastra.ai/en/reference/streaming/workflows/stream This example shows how to use the .stream() method to initiate a workflow run and then retrieve its final state. It highlights the usage of the `getWorkflowState` function returned by the .stream() method. ```javascript const { getWorkflowState } = await run.stream({ inputData: { value: "initial data" } }); const result = await getWorkflowState(); ``` -------------------------------- ### Create Mastra Entry Point File Source: https://mastra.ai/en/docs/getting-started/installation This command creates the main TypeScript file for the Mastra application. This file will be used to initialize and export the Mastra instance. ```bash touch src/mastra/index.ts ``` -------------------------------- ### Install HTTP/Protobuf Exporter for SigNoz Source: https://mastra.ai/en/docs/observability/ai-tracing/exporters/otel Instructions to install the HTTP/Protobuf exporter package, which is required when using SigNoz as the provider. This resolves 'Missing Dependency Error'. ```bash npm install @opentelemetry/exporter-trace-otlp-proto ``` -------------------------------- ### Initialize LibSQL Storage - JavaScript Source: https://mastra.ai/en/reference/storage/libsql Demonstrates how to initialize the LibSQLStore for different storage scenarios. It shows examples for file-based storage (suitable for development) and persistent storage using an environment variable for the database URL. Requires the `@mastra/libsql` package. ```javascript import { LibSQLStore } from "@mastra/libsql"; // File database (development) const storage = new LibSQLStore({ url: "file:./storage.db", }); // Persistent database (production) const storage = new LibSQLStore({ url: process.env.DATABASE_URL, }); ``` -------------------------------- ### Mastra Workflow Step: Analyze Context Source: https://mastra.ai/en/examples/rag/usage/cot-workflow-rag Defines a Mastra workflow step 'analyzeContext' that retrieves the query from the context, gets the 'ragAgent', and generates an initial analysis of the query. The output is an object containing 'initialAnalysis'. ```typescript const analyzeContext = new Step({ id: "analyzeContext", outputSchema: z.object({ initialAnalysis: z.string(), }), execute: async ({ context, mastra }) => { console.log("---------------------------"); const ragAgent = mastra?.getAgent("ragAgent"); const query = context?.getStepResult<{ query: string }>("trigger")?.query; const analysisPrompt = `${query} 1. First, carefully analyze the retrieved context chunks and identify key information.`; const analysis = await ragAgent?.generate(analysisPrompt); console.log(analysis?.text); return { initialAnalysis: analysis?.text ?? "", }; }, }); ``` -------------------------------- ### Configure Simple Agent with Default Strategy Source: https://mastra.ai/en/examples/processors/message-length-limiter Shows how to instantiate a Mastra Agent using a simplified approach for MessageLengthLimiter, relying on the default 'block' strategy. This is useful for quick setup when the default behavior is desired. ```typescript import { Agent } from "@mastra/core/agent"; import { MessageLengthLimiter } from "../processors/message-length-limiter"; export const simpleAgent = new Agent({ name: 'simple-agent', instructions: 'You are a helpful assistant', model: "openai/gpt-4o", inputProcessors: [ new MessageLengthLimiter(500), ], }); ``` -------------------------------- ### Custom Deployer Implementation Example (TypeScript) Source: https://mastra.ai/en/reference/deployer/deployer Demonstrates how to create a custom deployer by extending the abstract Deployer class. It includes implementing the abstract deploy method, preparing the output directory, and bundling the application. This example highlights the extensibility of the Deployer for specific deployment needs. ```typescript import { Deployer } from "@mastra/deployer"; // Create a custom deployer by extending the abstract Deployer class class CustomDeployer extends Deployer { constructor() { super({ name: "custom-deployer" }); } // Implement the abstract deploy method async deploy(outputDirectory: string): Promise { // Prepare the output directory await this.prepare(outputDirectory); // Bundle the application await this._bundle("server.ts", "mastra.ts", outputDirectory); // Custom deployment logic // ... } } ``` -------------------------------- ### Monitor Workflow Run Execution with .stream() in JavaScript Source: https://mastra.ai/en/reference/streaming/workflows/stream This example demonstrates how to initiate a workflow run and start monitoring its execution in real-time using the .stream() method. It shows how to pass initial input data and access the streaming events. ```javascript const run = await workflow.createRunAsync(); const { stream } = await run.stream({ inputData: { value: "initial data", }, }); ``` -------------------------------- ### Add API Key to .env File Source: https://mastra.ai/en/docs/getting-started/installation Adds your API key for a supported model provider (e.g., Google Gemini) to the `.env` file. Replace `` with your actual key. This enables Mastra to interact with the AI model. ```env GOOGLE_GENERATIVE_AI_API_KEY= ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.