Hono プロジェクトに Mastra を統合する
このガイドでは、Mastra と Hono を使用して Tool を呼び出す AI Agent を構築します。Hono サーバーアダプターを使用すると、ルーティングを自分で記述したり、別の Mastra サーバーを実行したりすることなく、Agent を HTTP エンドポイントとして公開できます。
始める前に始める前にへの直接リンク
- サポートされているモデル Provider の API キーが必要です。特に希望がなければ、OpenAI を使用してください。
- Node.js
v22.13.0以降をインストールしてください
新しい Hono アプリを作成する(任意)新しい Hono アプリを作成する(任意)への直接リンク
Hono アプリがすでにある場合は、次の手順に進んでください。
次のコマンドを実行して、新しい Hono アプリを作成します。
- npm
- pnpm
- Yarn
- Bun
npm create hono@latest mastra-hono -- --template nodejs --install --pm npm
pnpm create hono mastra-hono --template nodejs --install --pm npm
yarn create hono mastra-hono --template nodejs --install --pm npm
bunx create-hono mastra-hono --template nodejs --install --pm npm
これにより mastra-hono というプロジェクトが作成されますが、任意の名前に置き換えられます。
Mastra を初期化するMastra を初期化するへの直接リンク
Hono プロジェクトのディレクトリに移動します。
cd mastra-hono
mastra init を実行します。プロンプトが表示されたら、Provider(OpenAI など)を選択してキーを入力します。
- npm
- pnpm
- Yarn
- Bun
npx mastra@latest init
pnpm dlx mastra@latest init
yarn dlx mastra@latest init
bun x mastra@latest init
これにより、天気 Agent のサンプルと次のファイルを含む src/mastra フォルダーが作成されます。
index.ts- Memory を含む Mastra の設定tools/weather-tool.ts- 指定した場所の天気を取得する Toolagents/weather-agent.ts- Tool を使用するプロンプトを備えた天気 Agent
後ほど、src/mastra/index.ts ファイルを Hono サーバーアダプターに渡します。
サーバーアダプターを追加するサーバーアダプターを追加するへの直接リンク
Hono サーバーアダプターパッケージをインストールします。
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/hono@latest
pnpm add @mastra/hono@latest
yarn add @mastra/hono@latest
bun add @mastra/hono@latest
src/index.ts にある Hono のエントリーファイルを開き、必要な import と初期化コードを追加します。
import { serve } from '@hono/node-server'
import { Hono } from 'hono'
import { type HonoBindings, type HonoVariables, MastraServer } from '@mastra/hono'
import { mastra } from './mastra/index.js'
const app = new Hono<{ Bindings: HonoBindings; Variables: HonoVariables }>()
const server = new MastraServer({ app, mastra })
await server.init()
app.get('/', c => {
return c.text('Hello Hono!')
})
serve(
{
fetch: app.fetch,
port: 3000,
},
info => {
console.log(`Server is running on http://localhost:${info.port}`)
},
)
MastraServer は、既存の Hono app とルートの mastra インスタンスを使用して初期化されます。init() を呼び出すと Mastra ミドルウェアが登録され、利用可能なすべての Mastra エンドポイントが公開されます。
Agent をテストするAgent をテストするへの直接リンク
デフォルトでは、Mastra のエンドポイントは /api サブパスの下に追加され、Agent または Workflow の ID が使用されます。mastra init で作成されるデフォルトの weather-agent は、/api/agents/weather-agent で利用できます。
Hono サーバーを起動します。
- npm
- pnpm
- Yarn
- Bun
npm run dev
pnpm run dev
yarn dev
bun run dev
別のターミナルウィンドウで、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?\"}]}"
次のステップ次のステップへの直接リンク
Hono で Mastra Agent を構築できました!🎉
ここから、独自の Tool やロジックを追加してプロジェクトを拡張できます。
Mastra と Hono の統合について詳しくは、次を参照してください。