Installation
To run Mastra, you need access to an LLM. Typically, you’ll want to get an API key from an LLM provider such as OpenAI, Anthropic, or Google Gemini. You can also run Mastra with a local LLM using Ollama.
Prerequisites
- Node.js
v20.0
or higher - Access to a supported large language model (LLM).
Automatic Installation
Create a New Project
We recommend starting a new Mastra project using create-mastra
, which will scaffold your project. To create
a project, run:
npx create-mastra@latest
On installation, you’ll be guided through the following prompts:
What do you want to name your project? my-mastra-app
Choose components to install:
◯ Agents (recommended)
◯ Tools
◯ Workflows
Select default provider:
◯ OpenAI (recommended)
◯ Anthropic
◯ Groq
Would you like to include example code? No / Yes
After the prompts, create-mastra
will set up your project directory with TypeScript, install dependencies, and configure your selected components and LLM provider.
Set Up your API Key
Add the API key for your configured LLM provider in your .env
file.
OPENAI_API_KEY=<your-openai-key>
Note: If you prefer to run the command with flags (non-interactive mode) and include the example code, you can use:
npx create-mastra@latest --components agents,tools --llm openai --example
This allows you to specify your preferences upfront without being prompted.
Manual Installation
If you prefer to set up your Mastra project manually, follow these steps:
Create a New Project
Create a project directory and navigate into it:
mkdir hello-mastra
cd hello-mastra
Then, initialize a TypeScript project including the @mastra/core
package:
npm init -y
npm install typescript tsx @types/node mastra@alpha --save-dev
npm install @mastra/core@alpha zod
npx tsc --init
Set Up your API Key
Create a .env
file in your project root directory and add your API key:
OPENAI_API_KEY=<your-openai-key>
Replace your_openai_api_key with your actual API key.
Create a Tool
Create a weather-tool
tool file:
mkdir -p src/mastra/tools && touch src/mastra/tools/weather-tool.ts
Then, add the following code to src/mastra/tools/weather-tool.ts
:
import { createTool } from "@mastra/core";
import { z } from "zod";
interface WeatherResponse {
current: {
time: string;
temperature_2m: number;
apparent_temperature: number;
relative_humidity_2m: number;
wind_speed_10m: number;
wind_gusts_10m: number;
weather_code: number;
};
}
export const weatherTool = createTool({
id: "get-weather",
description: "Get current weather for a location",
inputSchema: z.object({
location: z.string().describe("City name"),
}),
outputSchema: z.object({
temperature: z.number(),
feelsLike: z.number(),
humidity: z.number(),
windSpeed: z.number(),
windGust: z.number(),
conditions: z.string(),
location: z.string(),
}),
execute: async ({ context }) => {
return await getWeather(context.location);
},
});
const getWeather = async (location: string) => {
const geocodingUrl = `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(location)}&count=1`;
const geocodingResponse = await fetch(geocodingUrl);
const geocodingData = await geocodingResponse.json();
if (!geocodingData.results?.[0]) {
throw new Error(`Location '${location}' not found`);
}
const { latitude, longitude, name } = geocodingData.results[0];
const weatherUrl = `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}¤t=temperature_2m,apparent_temperature,relative_humidity_2m,wind_speed_10m,wind_gusts_10m,weather_code`;
const response = await fetch(weatherUrl);
const data: WeatherResponse = await response.json();
return {
temperature: data.current.temperature_2m,
feelsLike: data.current.apparent_temperature,
humidity: data.current.relative_humidity_2m,
windSpeed: data.current.wind_speed_10m,
windGust: data.current.wind_gusts_10m,
conditions: getWeatherCondition(data.current.weather_code),
location: name,
};
};
function getWeatherCondition(code: number): string {
const conditions: Record<number, string> = {
0: "Clear sky",
1: "Mainly clear",
2: "Partly cloudy",
3: "Overcast",
45: "Foggy",
48: "Depositing rime fog",
51: "Light drizzle",
53: "Moderate drizzle",
55: "Dense drizzle",
56: "Light freezing drizzle",
57: "Dense freezing drizzle",
61: "Slight rain",
63: "Moderate rain",
65: "Heavy rain",
66: "Light freezing rain",
67: "Heavy freezing rain",
71: "Slight snow fall",
73: "Moderate snow fall",
75: "Heavy snow fall",
77: "Snow grains",
80: "Slight rain showers",
81: "Moderate rain showers",
82: "Violent rain showers",
85: "Slight snow showers",
86: "Heavy snow showers",
95: "Thunderstorm",
96: "Thunderstorm with slight hail",
99: "Thunderstorm with heavy hail",
};
return conditions[code] || "Unknown";
}
Create an Agent
Create a weather
agent file:
mkdir -p src/mastra/agents && touch src/mastra/agents/weather.ts
Then, add the following code to src/mastra/agents/weather.ts
:
import { Agent } from "@mastra/core";
import { weatherTool } from "../tools/weather-tool";
export const weatherAgent = new Agent({
name: "Weather Agent",
instructions: `You are a helpful weather assistant that provides accurate weather information.
Your primary function is to help users get weather details for specific locations. When responding:
- Always ask for a location if none is provided
- Include relevant details like humidity, wind conditions, and precipitation
- Keep responses concise but informative
Use the weatherTool to fetch current weather data.`,
model: {
provider: "OPEN_AI",
name: "gpt-4o",
},
tools: { weatherTool },
});
Register Agent
Finally, create the Mastra entry point in src/mastra/index.ts
and register agent:
import { Mastra } from "@mastra/core";
import { weatherAgent } from "./agents/weather";
export const mastra = new Mastra({
agents: { weatherAgent },
});
This registers your agent with Mastra so that mastra dev
can discover and serve it.
To add Mastra to an existing project, see our Local dev docs on mastra init.
Start the Mastra Server
Mastra provides commands to serve your agents via REST endpoints
Development Server
Run the following command to start the Mastra server:
npm run dev
If you have the mastra CLI installed, run:
mastra dev
This command creates REST API endpoints for your agents.
Test the Endpoint
You can test the agent’s endpoint using curl
or fetch
:
curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \
-H "Content-Type: application/json" \
-d '{"messages": ["What is the weather in London?"]}'
Run from the command line
If you’d like to directly call agents from the command line, you can create a script to get an agent and call it:
import { mastra } from "./mastra";
async function main() {
const agent = await mastra.getAgent("weatherAgent");
const result = await agent.generate("What is the weather in London?");
console.log("Agent response:", result.text);
}
main();
Then, run the script to test that everything is set up correctly:
npx tsx src/index.ts
This should output the agent’s response to your console.