メインコンテンツへ移動

Express プロジェクトに Mastra を統合する

このガイドでは、Mastra と Express を使用して Tool を呼び出す AI Agent を構築します。Express サーバーアダプターを使用すると、ルーティングを自分で記述したり、別の Mastra サーバーを実行したりすることなく、Agent を HTTP エンドポイントとして公開できます。

始める前に
始める前にへの直接リンク

  • サポートされているモデル Provider の API キーが必要です。特に希望がなければ、OpenAI を使用してください。
  • Node.js v22.13.0 以降をインストールしてください

新しい Express アプリを作成する(任意)
新しい Express アプリを作成する(任意)への直接リンク

Express アプリがすでにある場合は、次の手順に進んでください。

このボイラープレートリポジトリをクローンし、依存関係をインストールします。

git clone https://github.com/mastra-ai/express-ts-boilerplate.git
cd express-ts-boilerplate
npm install

Mastra を初期化する
Mastra を初期化するへの直接リンク

Express プロジェクトのディレクトリ内で、mastra init を実行します。

プロンプトが表示されたら、Provider(OpenAI など)を選択してキーを入力します。

npx mastra@latest init

これにより、天気 Agent のサンプルと次のファイルを含む src/mastra フォルダーが作成されます。

  • index.ts - Memory を含む Mastra の設定
  • tools/weather-tool.ts - 指定した場所の天気を取得する Tool
  • agents/weather-agent.ts- Tool を使用するプロンプトを備えた天気 Agent

後ほど、src/mastra/index.ts ファイルを Express サーバーアダプターに渡します。

サーバーアダプターを追加する
サーバーアダプターを追加するへの直接リンク

Express サーバーアダプターパッケージをインストールします。

npm install @mastra/express@latest

src/index.ts にある Express のエントリーファイルを開き、必要な import と初期化コードを追加します。

src/index.ts
import express, { type Request, type Response } from 'express'
import { MastraServer } from '@mastra/express'
import { mastra } from './mastra'

const app = express()
const PORT = process.env.PORT || 3000

// Middleware
app.use(express.json())

const server = new MastraServer({ app, mastra })
await server.init()

// Routes
app.get('/', (_req: Request, res: Response) => {
res.json({ message: 'Hello, World!' })
})

// Start server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`)
})

MastraServer は、既存の Express app とルートの mastra インスタンスを使用して初期化されます。⁠init() を呼び出すと Mastra ミドルウェアが登録され、利用可能なすべての Mastra エンドポイントが公開されます。

Agent をテストする
Agent をテストするへの直接リンク

デフォルトでは、Mastra のエンドポイントは /api サブパスの下に追加され、Agent または Workflow の ID が使用されます。mastra init で作成されるデフォルトの weather-agent は、/api/agents/weather-agent で利用できます。

Express サーバーを起動します。

npm run start

別のターミナルウィンドウで、curl を使用して天気 Agent に質問します。

curl -X POST http://localhost:3000/api/agents/weather-agent/generate -H "Content-Type: application/json" -d "{\"messages\":[{\"role\":\"user\",\"content\":\"What is the weather like in Seoul?\"}]}"

次のステップ
次のステップへの直接リンク

Express で Mastra Agent を構築できました!🎉

ここから、独自の Tool やロジックを追加してプロジェクトを拡張できます。

  • Agent について詳しく学ぶ
  • Agent に独自の Tool を追加する
  • Agent に人間のような Memory を追加する

Mastra と Express の統合について詳しくは、次を参照してください。