### Setup and Execution of Mastra Keyword Coverage Example Source: https://github.com/xendit/mastra/blob/main/examples/basics/evals/keyword-coverage/README.md Instructions for cloning the repository, installing dependencies, and executing the keyword coverage evaluation example using the Mastra framework. ```bash git clone https://github.com/mastra-ai/mastra cd examples/basics/evals/keyword-coverage pnpm install pnpm start ``` -------------------------------- ### Setup and Run Prompt Alignment Example Source: https://github.com/xendit/mastra/blob/main/examples/basics/evals/prompt-alignment/README.md Commands to configure environment variables, install project dependencies, and execute the prompt alignment demonstration. ```bash cp .env.example .env pnpm install pnpm start ``` -------------------------------- ### Install and Run Example Project Source: https://github.com/xendit/mastra/blob/main/examples/basics/scorers/completeness/README.md Provides the command-line instructions to set up the environment, install dependencies, and execute the completeness scorer example project. ```bash git clone https://github.com/mastra-ai/mastra cd examples/basics/scorers/completeness pnpm install --ignore-workspace pnpm start ``` -------------------------------- ### Setup and Execution of Mastra Bias Example Source: https://github.com/xendit/mastra/blob/main/examples/basics/evals/bias/README.md Commands to clone the repository, configure environment variables, install dependencies, and execute the bias evaluation example. ```bash git clone https://github.com/mastra-ai/mastra cd examples/basics/evals/bias cp .env.example .env pnpm install pnpm start ``` ```env OPENAI_API_KEY=sk-your-api-key-here ``` -------------------------------- ### Setup and Execution of Mastra Chunking Example Source: https://github.com/xendit/mastra/blob/main/examples/basics/rag/adjust-chunk-size/README.md Provides the command-line interface instructions to clone the repository, install necessary dependencies, and execute the chunking demonstration project. ```bash git clone https://github.com/mastra-ai/mastra cd examples/basics/rag/chunk-text pnpm install pnpm start ``` -------------------------------- ### Setup and Execution of Contextual Recall Example Source: https://github.com/xendit/mastra/blob/main/examples/basics/evals/contextual-recall/README.md Commands to clone the Mastra repository, configure environment variables, install dependencies, and execute the contextual recall evaluation example. ```bash git clone https://github.com/mastra-ai/mastra cd examples/basics/evals/contextual-recall cp .env.example .env pnpm install pnpm start ``` ```env OPENAI_API_KEY=sk-your-api-key-here ``` -------------------------------- ### Setup and Run Mastra Markdown Chunking Example Source: https://github.com/xendit/mastra/blob/main/examples/basics/rag/chunk-markdown/README.md Commands to clone the Mastra repository, install necessary project dependencies using pnpm, and execute the chunking example. ```bash git clone https://github.com/mastra-ai/mastra cd examples/basics/rag/chunk-markdown pnpm install pnpm start ``` -------------------------------- ### Setup Mastra Tone Scorer Example Source: https://github.com/xendit/mastra/blob/main/examples/basics/scorers/tone-consistency/README.md Provides the shell commands required to clone the repository, install dependencies, and execute the tone consistency example project. ```bash git clone https://github.com/mastra-ai/mastra cd examples/basics/scorers/tone-consistency pnpm install --ignore-workspace pnpm start ``` -------------------------------- ### Install and Setup Mastra Template Source: https://github.com/xendit/mastra/blob/main/docs/src/content/en/reference/templates.mdx Commands to initialize a new Mastra project from a template, configure environment variables, and start the development server. ```bash npx create-mastra@latest --template template-name cd your-project-name cp .env.example .env npm install npm run dev ``` -------------------------------- ### Setup and Execution for JSON Chunking Source: https://github.com/xendit/mastra/blob/main/examples/basics/rag/chunk-json/README.md Commands to initialize the Mastra JSON chunking example. This includes cloning the repository, installing necessary dependencies, and starting the execution process. ```bash git clone https://github.com/mastra-ai/mastra cd examples/basics/rag/chunk-json pnpm install pnpm start ``` -------------------------------- ### Setup Inngest and Mastra Dependencies Source: https://github.com/xendit/mastra/blob/main/docs/src/content/en/examples/workflows/inngest-workflow.mdx Installs necessary packages for Inngest and Mastra, and starts the Inngest development server. This setup is crucial for running the workflow locally. ```sh 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 ``` -------------------------------- ### Setup and Environment Configuration Source: https://github.com/xendit/mastra/blob/main/templates/template-pdf-to-audio/README.md Commands to initialize the project, install dependencies, and configure necessary environment variables for the OpenAI API. ```bash git clone cd template-pdf-to-audio pnpm install cp .env.example .env npx tsx example.ts ``` ```env OPENAI_API_KEY="your-openai-api-key-here" ``` -------------------------------- ### Initialize and Run Mastra Textual Difference Example Source: https://github.com/xendit/mastra/blob/main/examples/basics/evals/textual-difference/README.md Commands to clone the Mastra repository, install necessary dependencies, and execute the textual difference evaluation example. This setup requires Node.js v20.0+ and a package manager like pnpm or npm. ```bash git clone https://github.com/mastra-ai/mastra cd examples/basics/evals/textual-difference pnpm install pnpm start ``` -------------------------------- ### Setup Project and Environment Source: https://github.com/xendit/mastra/blob/main/templates/template-pdf-questions/README.md Commands to clone the repository, install dependencies, and configure the necessary environment variables for the Mastra PDF project. ```bash git clone cd template-pdf-questions pnpm install cp .env.example .env ``` ```env OPENAI_API_KEY="your-openai-api-key-here" ``` ```bash npx tsx example.ts ``` -------------------------------- ### Configure and Start Mastra Project Source: https://github.com/xendit/mastra/blob/main/docs/src/content/en/docs/getting-started/templates.mdx Standard workflow for setting up a newly created template, including navigating to the directory, initializing environment variables from the example file, and starting the development server. ```bash cd your-project-name cp .env.example .env npm run dev ``` -------------------------------- ### Clone Mastra Repository and Navigate Source: https://github.com/xendit/mastra/blob/main/examples/basics/evals/content-similarity/README.md Clones the Mastra GitHub repository and navigates the user into the content similarity example directory. This is the initial setup step for running the example. ```bash git clone https://github.com/mastra-ai/mastra cd examples/basics/evals/content-similarity ``` -------------------------------- ### Setup Mastra Project Dependencies and Environment Source: https://github.com/xendit/mastra/blob/main/templates/template-csv-to-questions/README.md Instructions for setting up the project, including cloning the repository, installing dependencies using pnpm, and configuring environment variables such as the OpenAI API key. ```bash git clone cd template-csv-to-questions pnpm install ``` ```bash cp .env.example .env # Edit .env and add your API keys ``` ```env OPENAI_API_KEY="your-openai-api-key-here" ``` ```bash npx tsx example.ts ``` -------------------------------- ### Local DynamoDB Development Setup Source: https://github.com/xendit/mastra/blob/main/docs/src/content/en/reference/storage/dynamodb.mdx Provides instructions and code examples for configuring the DynamoDBStore to connect with a local DynamoDB instance. ```APIDOC ## Local DynamoDB Development Setup ### Description Configures the `DynamoDBStore` to connect to a local DynamoDB instance, typically used during development. This involves setting the `endpoint` and potentially `region` parameters. ### Method Instantiation of `DynamoDBStore` class with specific configuration for local development. ### Endpoint N/A (Client-side configuration) ### Parameters #### Request Body - **name** (string) - Required - A name for this storage instance (e.g., "dynamodb-local"). - **config.tableName** (string) - Required - The name of your DynamoDB table (must exist in the local instance). - **config.region** (string) - Required for local - Can be any string (e.g., 'localhost'). - **config.endpoint** (string) - Required for local - The URL of the local DynamoDB instance (e.g., 'http://localhost:8000'). - **config.credentials** (object) - Optional - Credentials are usually not required for local DynamoDB unless specifically configured. ### Request Example ```typescript import { DynamoDBStore } from "@mastra/dynamodb"; const storage = new DynamoDBStore({ name: "dynamodb-local", config: { tableName: "mastra-single-table", // Ensure this table is created in your local DynamoDB region: "localhost", // Can be any string for local, 'localhost' is common endpoint: "http://localhost:8000", // For DynamoDB Local, credentials are not typically required unless configured. // If you've configured local credentials: // credentials: { accessKeyId: "fakeMyKeyId", secretAccessKey: "fakeSecretAccessKey" } }, }); ``` ### Response #### Success Response (200) N/A (Initialization does not return a response in this context) #### Response Example N/A ### Notes Ensure DynamoDB Local is running (e.g., via Docker) and the necessary table and GSIs are created in the local instance before running this configuration. ``` -------------------------------- ### Document Mastra Template Usage in README.md Source: https://github.com/xendit/mastra/blob/main/templates/README.md An example README.md file for a Mastra template. It includes an overview, setup instructions, and a list of required environment variables with their descriptions. This documentation guides users on how to install, configure, and run the template. ```markdown # My New Template This template demonstrates how to build an agent using OpenAI as the LLM provider with Mastra. ## Overview The overview of the template. ## Setup 1. Copy .env.example to .env and fill in your API keys. 2. Install dependencies: `pnpm install` 3. Run the project: `pnpm dev`. ## Environment Variables - `OPENAI_API_KEY`: Your OpenAI API key. [https://platform.openai.com/api-keys](https://platform.openai.com/api-keys) - `OTHER_REQUIRED_VARIABLE`: Description of what this variable is for. ``` -------------------------------- ### Set Up Environment Variables Source: https://github.com/xendit/mastra/blob/main/examples/basics/evals/custom-eval/README.md Copies the example environment file and instructs the user to add their OpenAI API key, which is necessary for LLM-based evaluations. ```bash cp .env.example .env # Edit .env and add your OpenAI API key: # OPENAI_API_KEY=sk-your-api-key-here ``` -------------------------------- ### MSSQLStore Constructor Examples Source: https://github.com/xendit/mastra/blob/main/docs/src/content/en/reference/storage/mssql.mdx Examples demonstrating different ways to instantiate the MSSQLStore. ```APIDOC ## Constructor Examples ### Using a connection string only ```ts import { MSSQLStore } from "@mastra/mssql"; const store1 = new MSSQLStore({ connectionString: "mssql://user:password@localhost:1433/mydb", }); ``` ### Using a connection string with a custom schema name ```ts import { MSSQLStore } from "@mastra/mssql"; const store2 = new MSSQLStore({ connectionString: "mssql://user:password@localhost:1433/mydb", schemaName: "custom_schema", // optional }); ``` ### Using individual connection parameters ```ts const store4 = new MSSQLStore({ server: "localhost", port: 1433, database: "mydb", user: "user", password: "password", }); ``` ### Individual parameters with schemaName ```ts const store5 = new MSSQLStore({ server: "localhost", port: 1433, database: "mydb", user: "user", password: "password", schemaName: "custom_schema", // optional }); ``` ``` -------------------------------- ### Initialize Project and Install Dependencies (Bash) Source: https://github.com/xendit/mastra/blob/main/docs/src/content/en/guides/guide/research-assistant.mdx Sets up a new Node.js project, installs necessary Mastra, OpenAI, and AI SDK packages, and configures environment variables for API keys and database connections. It also creates the required directory structure and files for the project. ```bash mkdir research-assistant cd research-assistant npm init -y npm install @mastra/core@latest @mastra/rag@latest @mastra/pg@latest @ai-sdk/openai@latest ai@latest zod@latest # .env file content: OPENAI_API_KEY=your_openai_api_key POSTGRES_CONNECTION_STRING=your_connection_string # Create directories and files: mkdir -p src/mastra/agents touch src/mastra/agents/researchAgent.ts touch src/mastra/index.ts src/store.ts src/index.ts ``` -------------------------------- ### Project Setup Source: https://context7.com/xendit/mastra/llms.txt Use the Mastra CLI to create a new project with interactive configuration. ```APIDOC ## Project Setup ### Description Create a new Mastra project using the CLI for the fastest setup with interactive configuration for LLM providers, tools, agents, and workflows. ### Method CLI Command ### Endpoint N/A ### Parameters N/A ### Request Example ```bash npx create-mastra@latest ``` ### Response N/A ``` -------------------------------- ### Run Bias Scorer Example Source: https://github.com/xendit/mastra/blob/main/examples/basics/scorers/bias/README.md Executes the Bias Scorer example by cloning the repository, setting up environment variables with an OpenAI API key, installing dependencies, and running the start script. ```bash git clone https://github.com/mastra-ai/mastra cd examples/basics/scorers/bias cp .env.example .env # Edit .env and add your OPENAI_API_KEY pnpm install --ignore-workspace pnpm start ``` -------------------------------- ### Environment Setup for Mastra Scorers Source: https://github.com/xendit/mastra/blob/main/examples/basics/scorers/faithfulness/README.md Commands to clone the repository, configure environment variables, and install dependencies required to run the Mastra scorer examples. ```bash git clone https://github.com/mastra-ai/mastra cd examples/basics/scorers/faithfulness cp .env.example .env # Add OPENAI_API_KEY to .env pnpm install --ignore-workspace pnpm start ``` -------------------------------- ### Setup Mastra Custom Scorer Environment Source: https://github.com/xendit/mastra/blob/main/examples/basics/scorers/custom-scorer/README.md Commands to initialize the Mastra custom scorer example project. This includes cloning the repository, configuring environment variables, and installing necessary dependencies. ```bash git clone https://github.com/mastra-ai/mastra cd examples/basics/scorers/custom-scorer cp .env.example .env pnpm install --ignore-workspace pnpm start ``` ```env OPENAI_API_KEY=sk-your-api-key-here ``` -------------------------------- ### Starting MCPServer with Standard Input/Output Source: https://github.com/xendit/mastra/blob/main/docs/src/content/en/reference/tools/mcp-server.mdx The `startStdio` method initializes the MCPServer to communicate via standard input and output, which is suitable for command-line applications. This method is asynchronous and returns a Promise that resolves when the server is ready. ```typescript import { MCPServer } from "@xendit/mcp"; const server = new MCPServer({ // ... server configuration }); async function startServer() { await server.startStdio(); console.log("MCP Server started with stdio communication."); } startServer(); ``` -------------------------------- ### Install and Run Mastra Agent Source: https://github.com/xendit/mastra/blob/main/examples/basics/agents/system-prompt/README.md Commands to install project dependencies using pnpm and execute the agent example. ```bash pnpm install pnpm start ``` -------------------------------- ### Example Usage Source: https://github.com/xendit/mastra/blob/main/docs/src/content/en/docs/server-db/mastra-client.mdx Demonstrates how to use the initialized MastraClient to interact with agents and generate responses. ```APIDOC ## Example Usage Once your MastraClient is initialized, you can start making client calls via the type-safe interface. ```typescript // Get a reference to your local agent const agent = client.getAgent("dev-agent-id"); // Generate responses const response = await agent.generate({ messages: [ { role: "user", content: "Hello, I'm testing the local development setup!", }, ], }); ``` ``` -------------------------------- ### Mastra Class - Usage Example Source: https://github.com/xendit/mastra/blob/main/docs/src/content/en/reference/core/mastra-class.mdx Example demonstrating how to use the Mastra instance to get an agent and generate a response. ```APIDOC ## Usage Any of the below methods can be used with the Mastra class, for example: ```typescript {3} filename="example.ts" showLineNumbers import { mastra } from "./mastra"; const agent = mastra.getAgent("weatherAgent"); const result = await agent.generate("What's the weather like in London?"); ``` ``` -------------------------------- ### Install Dependencies Source: https://github.com/xendit/mastra/blob/main/examples/basics/scorers/answer-relevancy/README.md Installs the necessary project dependencies using pnpm. This command ensures all required packages are available for the example to run. ```bash pnpm install --ignore-workspace ``` -------------------------------- ### Example MCP Server with Resources Source: https://github.com/xendit/mastra/blob/main/docs/src/content/en/reference/tools/mcp-server.mdx An example demonstrating how to configure an MCP server with custom resource handlers, including static resources and resource templates. ```typescript import { MCPServer } from "@mastra/mcp"; import type { MCPServerResourceContent, Resource, ResourceTemplate, } from "@mastra/mcp"; // Resources/resource templates will generally be dynamically fetched. const myResources: Resource[] = [ { uri: "file://data/123.txt", name: "Data File", mimeType: "text/plain" }, ]; const myResourceContents: Record = { "file://data.txt/123": { text: "This is the content of the data file." }, }; const myResourceTemplates: ResourceTemplate[] = [ { uriTemplate: "file://data/{id}", name: "Data File", description: "A file containing data.", mimeType: "text/plain", }, ]; const myResourceHandlers: MCPServerResources = { listResources: async () => myResources, getResourceContent: async ({ uri }) => { if (myResourceContents[uri]) { return myResourceContents[uri]; } throw new Error(`Resource content not found for ${uri}`); }, resourceTemplates: async () => myResourceTemplates, }; const serverWithResources = new MCPServer({ name: "Resourceful Server", version: "1.0.0", tools: { /* ... your tools ... */ }, resources: myResourceHandlers, }); ``` -------------------------------- ### Initialize MCPServer with Tools, Agents, and Workflows Source: https://github.com/xendit/mastra/blob/main/docs/src/content/en/reference/tools/mcp-server.mdx Demonstrates how to instantiate an MCPServer by providing a name, version, and a collection of tools, agents, and workflows. The agents and workflows are automatically exposed as tools to the connected MCP client. ```typescript import { openai } from "@ai-sdk/openai"; import { Agent } from "@mastra/core/agent"; import { createTool } from "@mastra/core/tools"; import { MCPServer } from "@mastra/mcp"; import { z } from "zod"; import { dataProcessingWorkflow } from "../workflows/dataProcessingWorkflow"; const myAgent = new Agent({ name: "MyExampleAgent", description: "A generalist to help with basic questions.", instructions: "You are a helpful assistant.", model: openai("gpt-4o-mini"), }); const weatherTool = createTool({ id: "getWeather", description: "Gets the current weather for a location.", inputSchema: z.object({ location: z.string() }), execute: async ({ context }) => `Weather in ${context.location} is sunny.`, }); const server = new MCPServer({ name: "My Custom Server", version: "1.0.0", tools: { weatherTool }, agents: { myAgent }, workflows: { dataProcessingWorkflow, } }); ``` -------------------------------- ### Install Netlify Deployer Source: https://github.com/xendit/mastra/blob/main/deployers/netlify/README.md Install the necessary package using the pnpm package manager to start deploying Mastra applications to Netlify. ```bash pnpm add @mastra/deployer-netlify ``` -------------------------------- ### Install Mastra CLI Source: https://github.com/xendit/mastra/blob/main/packages/cli/README.md Installs the Mastra CLI globally using npm. This command is typically the first step to start using Mastra. ```bash npm i -g mastra ``` -------------------------------- ### Initialize Mastra RAG Example Project Source: https://github.com/xendit/mastra/blob/main/examples/basics/rag/rerank-rag/README.md Commands to clone the repository and navigate to the specific RAG re-ranking example directory. ```bash git clone https://github.com/mastra-ai/mastra cd examples/basics/rag/rerank-rag ``` -------------------------------- ### Clone Mastra Repository and Install Dependencies Source: https://github.com/xendit/mastra/blob/main/DEVELOPMENT.md Clones the Mastra repository and installs all project dependencies using pnpm. This is the initial setup step for development. ```bash git clone https://github.com/mastra-ai/mastra.git cd mastra corepack enable pnpm run setup ``` -------------------------------- ### Initialize Mastra Agent Project Source: https://github.com/xendit/mastra/blob/main/examples/basics/agents/system-prompt/README.md Commands to clone the repository, navigate to the specific agent example directory, and prepare the environment. ```bash git clone https://github.com/mastra-ai/mastra cd examples/basics/agents/system-prompt ``` -------------------------------- ### Example: Using MastraMCPClient with Stdio Server Source: https://github.com/xendit/mastra/blob/main/docs/src/content/en/reference/tools/client.mdx Demonstrates how to initialize and use the MastraMCPClient with a Stdio server, connect to it, retrieve tools, and use them with a Mastra Agent. ```APIDOC ## Example: Using MastraMCPClient with Stdio Server ### Description This example shows how to set up a Mastra Agent and connect it to an MCP server running via Docker. It covers initializing the client, connecting, handling process exits, fetching tools, and generating a response using the agent with the fetched tools. ### Code Example ```typescript import { Agent } from "@mastra/core/agent"; import { MastraMCPClient } from "@mastra/mcp"; import { openai } from "@ai-sdk/openai"; // Initialize the MCP client using mcp/fetch as an example https://hub.docker.com/r/mcp/fetch // Visit https://github.com/docker/mcp-servers for other reference docker mcp servers const fetchClient = new MastraMCPClient({ name: "fetch", server: { command: "docker", args: ["run", "-i", "--rm", "mcp/fetch"], logger: (logMessage) => { console.log(`[${logMessage.level}] ${logMessage.message}`); }, }, }); // Create a Mastra Agent const agent = new Agent({ name: "Fetch agent", instructions: "You are able to fetch data from URLs on demand and discuss the response data with the user.", model: openai("gpt-4o-mini"), }); try { // Connect to the MCP server await fetchClient.connect(); // Gracefully handle process exits so the docker subprocess is cleaned up process.on("exit", () => { fetchClient.disconnect(); }); // Get available tools const tools = await fetchClient.tools(); // Use the agent with the MCP tools const response = await agent.generate( "Tell me about mastra.ai/docs. Tell me generally what this page is and the content it includes.", { toolsets: { fetch: tools, }, }, ); console.log("\n\n" + response.text); } catch (error) { console.error("Error:", error); } finally { // Always disconnect when done await fetchClient.disconnect(); } ``` ``` -------------------------------- ### Initialize and Start OpenAPI Spec Generator Source: https://github.com/xendit/mastra/blob/main/examples/openapi-spec-writer/README.md Commands to clone the repository, install necessary dependencies, and start the local development server. These steps are required to run the application locally. ```bash git clone cd openapi-spec-generator pnpm install cp .env.sample .env.local pnpm dev ``` -------------------------------- ### Initialize Mastra Project Source: https://context7.com/xendit/mastra/llms.txt Use the CLI to bootstrap a new Mastra project with interactive configuration for LLM providers and tools. ```bash npx create-mastra@latest ``` -------------------------------- ### Getting Started with Mastra vNext Workflows Source: https://github.com/xendit/mastra/blob/main/packages/core/src/workflows/README.md Import necessary functions to begin creating vNext workflows. ```APIDOC ## Getting Started with Mastra vNext Workflows To use vNext workflows, first import the necessary functions from the vNext module: ```typescript import { createWorkflow, createStep } from '@mastra/core/workflows/vNext'; import { z } from 'zod'; // For schema validation ``` ``` -------------------------------- ### Configure Authentication Middleware Source: https://github.com/xendit/mastra/blob/main/docs/src/content/en/reference/tools/mcp-server.mdx Example of how to populate authentication information in the HTTP server middleware before starting the MCP server. ```typescript httpServer.createServer((req, res) => { req.auth = validateAuthToken(req.headers.authorization); server.startHTTP({ url, httpPath, req, res }); }); ``` -------------------------------- ### Initialize Project Environment Source: https://github.com/xendit/mastra/blob/main/examples/bird-checker-with-nextjs-and-eval/README.md Commands to clone the repository, install dependencies, and prepare the environment configuration file for the Bird Checker application. ```bash git clone cd bird-checker-with-nextjs-and-eval pnpm install cp .env.example .env.local ``` -------------------------------- ### Make Request to Weather API Endpoint Source: https://github.com/xendit/mastra/blob/main/docs/src/content/en/docs/frameworks/servers/express.mdx These examples show how to make a GET request to the `/api/weather` endpoint of the running Express application. It includes examples using `httpie` and `curl`, demonstrating how to pass the required `city` query parameter. ```bash http://localhost:3000/api/weather?city=London ``` ```bash curl "http://localhost:3000/api/weather?city=London" ``` -------------------------------- ### Run Documentation Development Server Source: https://github.com/xendit/mastra/blob/main/docs/README.md Command to start the local development server for the documentation site. ```bash npm run dev ``` -------------------------------- ### Basic Message Pagination Example Source: https://github.com/xendit/mastra/blob/main/stores/upstash/PAGINATION.md Example demonstrating how to retrieve messages with pagination metadata. It shows how to get the first page of messages and access total count and hasMore flags. Also includes backward-compatible usage without pagination metadata. ```typescript // Get first page of messages with pagination metadata const page1 = await store.getMessages({ threadId: 'thread-123', page: 0, perPage: 20, format: 'v2', }); console.log(`Showing ${page1.messages.length} of ${page1.total} messages`); console.log(`Has more: ${page1.hasMore}`); // Backward compatible usage (no pagination metadata) const allMessages = await store.getMessages({ threadId: 'thread-123', format: 'v2', }); console.log(`Retrieved ${allMessages.length} messages`); ``` -------------------------------- ### Initialize Mastra RAG Project Source: https://github.com/xendit/mastra/blob/main/examples/basics/rag/embed-chunk-array/README.md Commands to clone the repository, configure environment variables, and install necessary dependencies for the RAG example. ```bash git clone https://github.com/mastra-ai/mastra cd examples/basics/rag/embed-chunk-array cp .env.example .env pnpm install pnpm start ``` ```env OPENAI_API_KEY=sk-your-api-key-here ``` -------------------------------- ### Configure Static Toolset with MCPClient Source: https://github.com/xendit/mastra/blob/main/docs/src/content/en/reference/tools/mcp-client.mdx Demonstrates how to initialize MCPClient with a static configuration of servers and tools, and then create an agent that can access these tools. It also shows examples of interacting with tool resources and prompts. ```typescript import { MCPClient } from "@mastra/mcp"; import { Agent } from "@mastra/core/agent"; import { openai } from "@ai-sdk/openai"; const mcp = new MCPClient({ servers: { stockPrice: { command: "npx", args: ["tsx", "stock-price.ts"], env: { API_KEY: "your-api-key", }, log: (logMessage) => { console.log(`[${logMessage.level}] ${logMessage.message}`); }, }, weather: { url: new URL("http://localhost:8080/sse"), }, }, timeout: 30000, // Global 30s timeout }); // Create an agent with access to all tools const agent = new Agent({ name: "Multi-tool Agent", instructions: "You have access to multiple tool servers.", model: openai("gpt-4"), tools: await mcp.getTools(), }); // Example of using resource methods async function checkWeatherResource() { try { const weatherResources = await mcp.resources.list(); if (weatherResources.weather && weatherResources.weather.length > 0) { const currentWeatherURI = weatherResources.weather[0].uri; const weatherData = await mcp.resources.read( "weather", currentWeatherURI, ); console.log("Weather data:", weatherData.contents[0].text); } } catch (error) { console.error("Error fetching weather resource:", error); } } checkWeatherResource(); // Example of using prompt methods async function checkWeatherPrompt() { try { const weatherPrompts = await mcp.prompts.list(); if (weatherPrompts.weather && weatherPrompts.weather.length > 0) { const currentWeatherPrompt = weatherPrompts.weather.find( (p) => p.name === "current" ); if (currentWeatherPrompt) { console.log("Weather prompt:", currentWeatherPrompt); } else { console.log("Current weather prompt not found"); } } } catch (error) { console.error("Error fetching weather prompt:", error); } } checkWeatherPrompt(); ``` -------------------------------- ### Example Usage with Runtime Context Source: https://github.com/xendit/mastra/blob/main/docs/src/content/en/examples/agents/dynamic-agents.mdx This example demonstrates how to set up `RuntimeContext` with specific values for 'user-tier' and 'language', retrieve the 'supportAgent', and then call its `generate` method with the populated runtime context. ```APIDOC ## Example Usage with Runtime Context ### Description Demonstrates how to set `RuntimeContext`, retrieve an agent, and call `generate` with the context. ### Method N/A (This is a code example, not an API endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ```typescript import "dotenv/config"; import { mastra } from "./mastra"; import { RuntimeContext } from "@mastra/core/runtime-context"; type SupportRuntimeContext = { "user-tier": "free" | "pro" | "enterprise"; language: "en" | "es" | "ja"; }; const runtimeContext = new RuntimeContext(); runtimeContext.set("user-tier", "free"); runtimeContext.set("language", "ja"); const agent = mastra.getAgent("supportAgent"); const response = await agent.generate("Can Mastra Cloud handle long-running requests?", { runtimeContext }); console.log(response.text); ``` ``` -------------------------------- ### Example Workflow Execution Source: https://github.com/xendit/mastra/blob/main/packages/core/src/workflows/README.md Demonstrates how to create, start, and handle the results of a Mastra workflow execution, including resuming suspended workflows. ```APIDOC ## Example Usage ```typescript const result = await workflow.createRun().start({ inputData: { /* ... */ }, }); if (result.status === 'success') { // Workflow completed successfully console.log('Final result:', result.result); console.log('Step outputs:', result.steps); } else if (result.status === 'suspended') { // Workflow is waiting for user input console.log('Suspended steps:', result.suspended); // Resume the workflow with user input const resumedResult = await workflowRun.resume({ step: result.suspended[0], resumeData: { /* user input */ }, }); } else if (result.status === 'failed') { // Workflow encountered an error console.error('Workflow failed:', result.error); throw result.error; } ``` ``` -------------------------------- ### Basic Memory Setup with Processors Source: https://github.com/xendit/mastra/blob/main/docs/src/content/en/examples/memory/memory-processors.mdx Demonstrates the basic setup of Mastra memory with TokenLimiter and ToolCallFilter processors. ```typescript import { Memory } from "@mastra/memory"; import { TokenLimiter, ToolCallFilter } from "@mastra/memory/processors"; // Create memory with processors const memory = new Memory({ processors: [new TokenLimiter(127000), new ToolCallFilter()] }); ``` -------------------------------- ### Install Mastra Client SDK (Bash) Source: https://github.com/xendit/mastra/blob/main/docs/src/content/en/docs/frameworks/agentic-uis/copilotkit.mdx Instructions for installing the Mastra Client SDK using npm, yarn, or pnpm. ```bash npm install @mastra/client-js ``` ```bash yarn add @mastra/client-js ``` ```bash pnpm add @mastra/client-js ``` -------------------------------- ### Get Agent Instructions Source: https://github.com/xendit/mastra/blob/main/docs/src/content/en/reference/agents/getInstructions.mdx Retrieves the instructions configured for an agent. These instructions guide the agent's behavior and define its capabilities and constraints. ```APIDOC ## GET /agents/{agentId}/instructions ### Description Retrieves the instructions configured for a specific agent. These instructions guide the agent's behavior and define its capabilities and constraints. The instructions can be returned as a direct string or a promise that resolves to the instructions. ### Method GET ### Endpoint `/agents/{agentId}/instructions` ### Parameters #### Query Parameters - **options** (object) - Optional - Optional configuration object containing runtime context. - **runtimeContext** (RuntimeContext) - Optional - Runtime context for dependency injection and contextual information. ### Request Example ```json { "options": { "runtimeContext": "" } } ``` ### Response #### Success Response (200) - **instructions** (string | Promise) - The instructions configured for the agent, either as a direct string or a promise that resolves to the instructions. #### Response Example ```json { "instructions": "This is a sample instruction string." } ``` ``` -------------------------------- ### Textual Difference Scorer API Source: https://github.com/xendit/mastra/blob/main/docs/src/content/en/examples/scorers/textual-difference.mdx This section details the Textual Difference Scorer, its installation, and provides examples of its usage with different text inputs. ```APIDOC ## Textual Difference Scorer Use `createTextualDifferenceScorer` to evaluate the similarity between two text strings by analyzing sequence differences and edit operations. ### Installation ```bash npm install @mastra/evals ``` ### No Differences Example This example demonstrates the scorer when the input and output texts are identical. #### Request ```typescript import { createTextualDifferenceScorer } from "@mastra/evals/scorers/code"; const scorer = createTextualDifferenceScorer(); const input = 'The quick brown fox jumps over the lazy dog'; const output = 'The quick brown fox jumps over the lazy dog'; const result = await scorer.run({ input: [{ role: 'user', content: input }], output: { role: 'assistant', text: output }, }); console.log('Score:', result.score); console.log('AnalyzeStepResult:', result.analyzeStepResult); ``` #### Response Example (No Differences) ```json { "score": 1, "analyzeStepResult": { "confidence": 1, "ratio": 1, "changes": 0, "lengthDiff": 0 } } ``` ### Minor Differences Example This example shows the scorer's behavior with texts that have minor variations. #### Request ```typescript import { createTextualDifferenceScorer } from "@mastra/evals/scorers/code"; const scorer = createTextualDifferenceScorer(); const input = 'Hello world! How are you?'; const output = 'Hello there! How is it going?'; const result = await scorer.run({ input: [{ role: 'user', content: input }], output: { role: 'assistant', text: output }, }); console.log('Score:', result.score); console.log('AnalyzeStepResult:', result.analyzeStepResult); ``` #### Response Example (Minor Differences) ```json { "score": 0.5925925925925926, "analyzeStepResult": { "confidence": 0.8620689655172413, "ratio": 0.5925925925925926, "changes": 5, "lengthDiff": 0.13793103448275862 } } ``` ### Major Differences Example This example illustrates the scorer's output when texts have significant differences. #### Request ```typescript import { createTextualDifferenceScorer } from "@mastra/evals/scorers/code"; const scorer = createTextualDifferenceScorer(); const input = 'Python is a high-level programming language'; const output = 'JavaScript is used for web development'; const result = await scorer.run({ input: [{ role: 'user', content: input }], output: { role: 'assistant', text: output }, }); console.log('Score:', result.score); console.log('AnalyzeStepResult:', result.analyzeStepResult); ``` #### Response Example (Major Differences) ```json { "score": 0.3170731707317073, "analyzeStepResult": { "confidence": 0.8636363636363636, "ratio": 0.3170731707317073, "changes": 8, "lengthDiff": 0.13636363636363635 } } ``` ## Scorer Configuration Instantiate the `TextualDifferenceScorer` with default settings. ```typescript const scorer = createTextualDifferenceScorer(); ``` ## Understanding the Results The `.run()` method returns an object with the following structure: ```typescript { runId: string, analyzeStepResult: { confidence: number, ratio: number, changes: number, lengthDiff: number }, score: number } ``` ### Score Interpretation - **1.0**: Identical texts. - **0.7–0.9**: Minor differences. - **0.4–0.6**: Moderate differences. - **0.1–0.3**: Major differences. - **0.0**: Completely different texts. ``` -------------------------------- ### Create Mastra Project with Example Code Source: https://github.com/xendit/mastra/blob/main/packages/create-mastra/README.md Creates a new Mastra project and includes example code to help demonstrate functionality. ```bash npx create-mastra@latest --example ``` -------------------------------- ### Upstash Storage Initialization Source: https://github.com/xendit/mastra/blob/main/docs/src/content/en/reference/storage/upstash.mdx Demonstrates how to install and initialize the Upstash Storage client with necessary credentials and configuration options. ```APIDOC ## Installation ```bash npm install @mastra/upstash@latest ``` ## Usage ```typescript import { UpstashStore } from "@mastra/upstash"; const storage = new UpstashStore({ url: process.env.UPSTASH_URL, token: process.env.UPSTASH_TOKEN, prefix: "mastra:" // Optional: Key prefix for all stored items }); ``` ### Parameters - **url** (string) - Required - Upstash Redis URL. - **token** (string) - Required - Upstash Redis authentication token. - **prefix** (string) - Optional - Key prefix for all stored items. Defaults to `mastra:`. ``` -------------------------------- ### Clone Mastra Repository Source: https://github.com/xendit/mastra/blob/main/examples/basics/rag/basic-rag/README.md Clones the Mastra repository and navigates to the basic RAG example directory. This is the initial step to get the project files. ```bash git clone https://github.com/mastra-ai/mastra cd examples/basics/rag/basic-rag ``` -------------------------------- ### SSL Certificate Setup with Certbot Source: https://github.com/xendit/mastra/blob/main/docs/src/components/content-blocks/server-config.mdx Steps to stop Nginx, install Certbot, obtain SSL certificates, and configure necessary TLS parameters. ```bash export SITE_NAME="mastra" export DOMAIN_NAME="" export EMAIL="" sudo systemctl stop nginx sudo apt install certbot -y sudo certbot certonly --standalone -d $DOMAIN_NAME --non-interactive --agree-tos -m $EMAIL if [ ! -f /etc/letsencrypt/options-ssl-nginx.conf ]; then sudo wget https://raw.githubusercontent.com/certbot/certbot/refs/heads/main/certbot-nginx/src/certbot_nginx/_internal/tls_configs/options-ssl-nginx.conf -P /etc/letsencrypt/ fi if [ ! -f /etc/letsencrypt/ssl-dhparams.pem ]; then sudo openssl dhparam -out /etc/letsencrypt/ssl-dhparams.pem 2048 fi ```