Skip to Content
ドキュメント使い方インストール

Mastraをローカルでインストールする

Mastraを実行するには、LLMへのアクセスが必要です。通常、OpenAIAnthropic、またはGoogle GeminiなどのLLMプロバイダーからAPIキーを取得することをお勧めします。また、Ollamaを使用してローカルLLMでMastraを実行することもできます。

前提条件

自動インストール

新しいプロジェクトを作成する

create-mastraを使用して新しいMastraプロジェクトを開始することをお勧めします。これによりプロジェクトの足場が構築されます。プロジェクトを作成するには、次のコマンドを実行します:

npx create-mastra@latest

インストール時に、以下のプロンプトが表示されます:

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 Turn your IDE into a Mastra expert? (Installs MCP server) Skip for now Cursor Windsurf

プロンプトの後、create-mastraは以下を行います:

  1. TypeScriptでプロジェクトディレクトリをセットアップ
  2. 依存関係のインストール
  3. 選択したコンポーネントとLLMプロバイダーの設定
  4. IDEにMCPサーバーを設定(選択した場合)- コーディング中にドキュメント、例、ヘルプにすぐにアクセスできます

MCPに関する注意: 別のIDEを使用している場合は、MCPサーバードキュメントの指示に従ってMCPサーバーを手動でインストールできます。また、MCPサーバーを有効化するにはCursorとWindsurfに追加の手順があることに注意してください。

APIキーの設定

設定したLLMプロバイダーのAPIキーを.envファイルに追加します。

.env
OPENAI_API_KEY=<your-openai-key>

非インタラクティブモード

プロジェクト名を位置引数として、または-p, --project-nameオプションで指定できるようになりました。これはMastra CLI(mastra create)とcreate-mastraパッケージの両方で一貫して機能します。両方が提供された場合、引数はオプションよりも優先されます。

例:

npx create-mastra@latest my-app --components agents,tools --llm openai --example npx create-mastra@latest --project-name my-app --components agents,tools --llm openai --example # 両方が提供された場合、引数が優先されます: npx create-mastra@latest my-app --project-name ignored-name --components agents,tools --llm openai --example # プロジェクトは「my-app」として作成されます

サンプルコードを明示的に除外するには、--no-exampleまたは-nフラグを使用します:

npx create-mastra@latest my-app --components agents,tools --llm openai --no-example # または省略形を使用 npx create-mastra@latest my-app --components agents,tools --llm openai -n

オプションの--dirまたは-dフラグを使用して、ソースコードのターゲットディレクトリを指定することもできます(デフォルト:src/):

npx create-mastra@latest my-app --components agents,tools --llm openai --dir src/

インストールタイムアウトの設定: インストールに時間がかかりすぎる場合にタイムアウトを設定するには、timeoutフラグを使用します:

npx create-mastra@latest --timeout 120000

LLMに関する注意: 例を含む簡単なワンライナーを実行するには:

npx -y mastra@latest --project-name <your-project> --example --components "tools,agents,workflows" --llm <llm-provider>

--llmフラグで使用できるオプションは:openai|anthropic|groq|google|cerebrasです。

ヒント: 必要なすべてのフラグ(引数またはオプション-p, --project-nameでのプロジェクト名、--components--llm、および--exampleまたは--no-exampleのいずれか)を提供すれば、CLIはプロンプトなしで完全に非インタラクティブに実行されます。


Mastraプロジェクトを手動でセットアップしたい場合は、以下の手順に従ってください:

新しいプロジェクトの作成

プロジェクトディレクトリを作成し、その中に移動します:

mkdir hello-mastra cd hello-mastra

次に、@mastra/coreパッケージを含むTypeScriptプロジェクトを初期化します:

npm init -y npm install typescript tsx @types/node mastra@latest --save-dev npm install @mastra/core@latest zod @ai-sdk/openai npx tsc --init

TypeScriptの初期化

プロジェクトのルートに以下の設定でtsconfig.jsonファイルを作成します:

{ "compilerOptions": { "target": "ES2022", "module": "ES2022", "moduleResolution": "bundler", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true, "outDir": "dist" }, "include": ["src/**/*"], "exclude": ["node_modules", "dist", ".mastra"] }

このTypeScript設定は、最新のモジュール解決と厳格な型チェックを使用して、Mastraプロジェクト向けに最適化されています。

APIキーの設定

プロジェクトのルートディレクトリに.envファイルを作成し、APIキーを追加します:

.env
OPENAI_API_KEY=<your-openai-key>

your_openai_api_keyを実際のAPIキーに置き換えてください。

ツールの作成

weather-toolツールファイルを作成します:

mkdir -p src/mastra/tools && touch src/mastra/tools/weather-tool.ts

次に、src/mastra/tools/weather-tool.tsに以下のコードを追加します:

src/mastra/tools/weather-tool.ts
import { createTool } from "@mastra/core/tools"; 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}&current=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"; }

エージェントを作成する

weatherエージェントファイルを作成します:

mkdir -p src/mastra/agents && touch src/mastra/agents/weather.ts

次に、以下のコードをsrc/mastra/agents/weather.tsに追加します:

src/mastra/agents/weather.ts
import { openai } from "@ai-sdk/openai"; import { Agent } from "@mastra/core/agent"; 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 - If the location name isn't in English, please translate it - Include relevant details like humidity, wind conditions, and precipitation - Keep responses concise but informative Use the weatherTool to fetch current weather data.`, model: openai("gpt-4o-mini"), tools: { weatherTool }, });

エージェントの登録

最後に、src/mastra/index.tsにMastraのエントリーポイントを作成し、エージェントを登録します:

src/mastra/index.ts
import { Mastra } from "@mastra/core"; import { weatherAgent } from "./agents/weather"; export const mastra = new Mastra({ agents: { weatherAgent }, });

これにより、エージェントがMastraに登録され、mastra devがそれを検出して提供できるようになります。

Mastraプロジェクトを手動でセットアップしたい場合は、以下の手順に従ってください:

新しいプロジェクトの作成

プロジェクトディレクトリを作成し、その中に移動します:

mkdir hello-mastra cd hello-mastra

次に、@mastra/coreパッケージを含むTypeScriptプロジェクトを初期化します:

npm init -y npm install typescript tsx @types/node mastra --save-dev npm install @mastra/core zod @ai-sdk/openai npx tsc --init

TypeScriptの初期化

プロジェクトのルートに以下の設定でtsconfig.jsonファイルを作成します:

{ "compilerOptions": { "target": "ES2022", "module": "ES2022", "moduleResolution": "bundler", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true, "outDir": "dist" }, "include": ["src/**/*"], "exclude": ["node_modules", "dist", ".mastra"] }

このTypeScript設定は、最新のモジュール解決と厳格な型チェックを使用して、Mastraプロジェクト向けに最適化されています。

APIキーの設定

プロジェクトのルートディレクトリに.envファイルを作成し、APIキーを追加します:

.env
OPENAI_API_KEY=<your-openai-key>

your_openai_api_keyを実際のAPIキーに置き換えてください。

ツールの作成

weather-toolツールファイルを作成します:

mkdir -p src/mastra/tools && touch src/mastra/tools/weather-tool.ts

次に、src/mastra/tools/weather-tool.tsに以下のコードを追加します:

src/mastra/tools/weather-tool.ts
import { createTool } from "@mastra/core/tools"; 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}&current=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"; }

エージェントを作成する

weatherエージェントファイルを作成します:

mkdir -p src/mastra/agents && touch src/mastra/agents/weather.ts

次に、以下のコードをsrc/mastra/agents/weather.tsに追加します:

src/mastra/agents/weather.ts
import { openai } from "@ai-sdk/openai"; import { Agent } from "@mastra/core/agent"; 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 - If the location name isn't in English, please translate it - Include relevant details like humidity, wind conditions, and precipitation - Keep responses concise but informative Use the weatherTool to fetch current weather data.`, model: openai("gpt-4o-mini"), tools: { weatherTool }, });

エージェントの登録

最後に、src/mastra/index.tsにMastraのエントリーポイントを作成し、エージェントを登録します:

src/mastra/index.ts
import { Mastra } from "@mastra/core"; import { weatherAgent } from "./agents/weather"; export const mastra = new Mastra({ agents: { weatherAgent }, });

これにより、エージェントがMastraに登録され、mastra devがそれを検出して提供できるようになります。

既存プロジェクトへのインストール

既存のプロジェクトにMastraを追加するには、既存のプロジェクトにmastraを追加するについてのローカル開発ドキュメントをご覧ください。

また、Next.jsなどのフレームワーク固有のドキュメントもご確認いただけます。

Mastraサーバーを起動する

Mastraは、エージェントをRESTエンドポイントを通じて提供するためのコマンドを提供しています

開発サーバー

以下のコマンドを実行してMastraサーバーを起動します:

npm run dev

mastra CLIをインストールしている場合は、次のコマンドを実行します:

mastra dev

このコマンドはエージェント用のREST APIエンドポイントを作成します。

エンドポイントのテスト

curlまたはfetchを使用してエージェントのエンドポイントをテストできます:

curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \ -H "Content-Type: application/json" \ -d '{"messages": ["What is the weather in London?"]}'

クライアントでMastraを使用する

フロントエンドアプリケーションでMastraを使用するには、タイプセーフなクライアントSDKを使用して MastraのREST APIとやり取りすることができます。

詳細な使用方法については、Mastra クライアントSDKのドキュメントを参照してください。