Open4

mastra を触る会

HoshiHoshi

https://mastra.ai/ja/docs/getting-started/installation

bun でやってみる。

bunx create-mastra@latest

# ┌  Mastra Create
# │
# ◇  What do you want to name your project?
# │  my-mastra-app
# │
# ◇  Project created
# │
# ◇  npm dependencies installed
# │
# ◇  mastra installed
# │
# ◇  Dependencies installed
# │
# ◇  .gitignore added
# │
# └  Project created successfully


# ┌  Mastra Init
# │
# ◇  Where should we create the Mastra files? (default: src/)
# │  src/
# │
# ◇  Choose components to install:
# │  Agents, Workflows
# │
# ◇  Add tools?
# │  Yes
# │
# ◇  Select default provider:
# │  OpenAI
# │
# ◇  Enter your openai API key?
# │  Skip for now
# │
# ◇  Add example
# │  Yes
# │
# ◇  Make your AI IDE into a Mastra expert? (installs Mastra docs MCP server)
# │  Cursor (project only)
# │
# │  
# │  Note: you will need to go into Cursor Settings -> MCP Settings and manually enable the installed Mastra MCP server.
# │  
# │
# ◇  
# │
# ◇   ─────────────────────────────────────────────────────────╮
# │                                                            │
# │                                                            │
# │        Mastra initialized successfully!                    │
# │                                                            │
# │        Add your OPENAI_API_KEY as an environment variable  │
# │        in your .env.development file                       │
# │                                                            │
# │                                                            │
# ├────────────────────────────────────────────────────────────╯
# │
# └  
#    To start your project:

#     cd my-mastra-app
#     npm run dev
vim .env.development
bun run dev

curl localhost:4111/api
# Hello to the Mastra API!

できた

HoshiHoshi

https://mastra.ai/ja/docs/getting-started/mcp-docs-server

Cursor で開いて MCP を Enabled にする。

公式ドキュメントにある質問のプロンプトを試してみる。

MastraはAI SDKと連携しますか? どのようにしてReactプロジェクトで使用できますか?

Called MCP tool `mastraDocs`
Parameters:
{
  "paths": [
    "getting-started/ai-sdk.mdx",
    "frameworks/react.mdx"
  ]
}

Called MCP tool `mastraDocs`
Parameters:
{
  "paths": [
    "frameworks/ai-sdk.mdx"
  ]
}

はい、MastraはVercel AI SDK(@ai-sdk/openai など)と連携できます。
Reactプロジェクトでの利用方法は以下の通りです。

### 1. Mastraエージェントの作成(AI SDKモデルを利用)

import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";

const agent = new Agent({
  name: "WeatherAgent",
  instructions: "天気情報を提供するエージェントです。",
  model: openai("gpt-4o"), // AI SDKのモデルを直接指定
});

### 2. APIエンドポイントの作成(Next.js例)

// app/api/chat/route.ts
import { mastra } from "@/src/mastra";

export async function POST(req: Request) {
  const { messages } = await req.json();
  const myAgent = mastra.getAgent("weatherAgent");
  const stream = await myAgent.stream(messages);

  return stream.toDataStreamResponse();
}

### 3. ReactでAI SDKのuseChatフックを利用

import { useChat } from '@ai-sdk/react';

export function ChatComponent() {
  const { messages, input, handleInputChange, handleSubmit } = useChat({
    api: '/api/chat' // 上記APIエンドポイント
  });

  return (
    <div>
      {messages.map(m => (
        <div key={m.id}>
          {m.role}: {m.content}
        </div>
      ))}
      <form onSubmit={handleSubmit}>
        <input
          value={input}
          onChange={handleInputChange}
          placeholder="メッセージを入力..."
        />
      </form>
    </div>
  );
}

### ポイント
* MastraのエージェントはAI SDKのモデルをそのまま利用できます。
* useChatやuseCompletionなどAI SDKのReactフックと組み合わせて、リアルタイムなチャットやストリーム出力が可能です。
* MastraのREST APIエンドポイント(例: /api/chat)をReactフロントエンドから呼び出します。
さらに詳しい実装例やカスタマイズ方法が必要な場合はご相談ください。

MCPに関する最新のMastraニュースは何ですか?

Called MCP tool `mastraBlog`
Parameters:
{
  "url": "/blog"
}

Called MCP tool `mastraBlog`
Parameters:
{
  "url": "/blog/changelog-2025-05-07"
}

最新のMastraに関するMCP関連ニュースは、2025年5月7日の「Mastra Changelog」で発表された内容が最も新しいものです。
主な内容は以下の通りです:
- **vNext Workflowsの正式リリース**
2025年5月6日より、MastraのワークフローシステムがvNextに完全移行しました。従来のワークフローシステムを使いたい場合は、@mastra/core/workflows/legacyからインポートし、legacy_workflowsとして登録できます。
- **AGUIクライアントとの統合**
Mastraは新たにAGUIクライアントをサポートし、メッセージのストリーミングやツールコール、エージェント管理が新しいアダプターシステムで簡単に行えるようになりました。
- **Mastra CLIの包括的なリント機能**
プロジェクトのセットアップや依存関係の問題を事前に検出できる強力なリントシステムがCLIに追加されました。これにより、さまざまなデプロイメントプラットフォームでの健全なプロジェクト管理が容易になります。
MCP(Mastra Control Plane)に直接関係する話題としては、AGUIクライアント統合やワークフローのvNext移行が注目ポイントです。
さらに詳しい内容や過去のMCP関連ニュースが必要な場合はお知らせください。
HoshiHoshi

https://mastra.ai/ja/docs/agents/overview

テンプレートから作成された Agent は以下のようになってる。

import { openai } from '@ai-sdk/openai';
import { Agent } from '@mastra/core/agent';
import { Memory } from '@mastra/memory';
import { LibSQLStore } from '@mastra/libsql';
import { weatherTool } from '../tools';

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
      - If giving a location with multiple parts (e.g. "New York, NY"), use the most relevant part (e.g. "New York")
      - 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'),
  tools: { weatherTool },
  memory: new Memory({
    storage: new LibSQLStore({
      url: 'file:../mastra.db', // path is relative to the .mastra/output directory
    }),
    options: {
      lastMessages: 10,
      semanticRecall: false,
      threads: {
        generateTitle: false,
      },
    },
  }),
});

起動した状態で、http://localhost:4111 にアクセスすると、Playground が表示されている。

大阪の今日の天気と降水確率は?

`weatherTool`
Tool arguments
\`\`\`json
{
  "location": "Osaka"
}
\`\`\`
Tool result
`\`\`json
{
  "temperature": 12.7,
  "feelsLike": 11.2,
  "humidity": 61,
  "windSpeed": 2.4,
  "windGust": 11.2,
  "conditions": "Clear sky",
  "location": "Osaka"
}
`\`\`\
大阪の現在の天気は晴れです。気温は12.7°Cで、体感温度は11.2°Cです。湿度は61%で、風速は2.4 m/s、最大風速は11.2 m/sです。降水確率はありません。
  • Overview タブ: LLM のパラメータ変更できる。
  • Instructions タブ: 指示プロンプトを編集できる。Comment を追加してから Enhance ボタンをクリックすることでプロンプトチューニングできる。

Instructions タブの Enhance 機能を使って、日本語に翻訳してみたプロンプト。UI 上で変更を適用しても、ソースコードの方は変わってない。ソースコードの方を編集すると Current Instructions が変わる。

役割定義: あなたは、正確な天気情報を提供する役立つ天気アシスタントです。主な責任は、特定の場所の天気情報をユーザーに提供することです。\n\nコア機能: 天気情報を取得するためにweatherToolを使用します。\n\n行動ガイドライン: \n- ユーザーが場所を指定しない場合は、必ず場所を尋ねてください。\n- 場所の名前が英語でない場合は、翻訳してください。\n- 複数の部分からなる場所名(例:「ニューヨーク、NY」)を提供する場合は、最も関連性の高い部分(例:「ニューヨーク」)を使用してください。\n- 湿度、風の状況、降水量などの関連情報を含めてください。\n- 回答は簡潔でありながら情報豊富にしてください。\n\n制約と境界: \n- 提供する情報は現在の天気データに限定されます。\n- プライバシーとセキュリティを考慮し、個人情報を収集しないでください。\n\n成功基準: \n- ユーザーが求める天気情報を正確に提供すること。\n- ユーザーの質問に迅速に対応すること。\n- ユーザーの満足度を高めること。

Playground のデータの実体は .mastra/mastra.db に保存されている。

SELECT name FROM sqlite_master WHERE type='table';

# mastra_evals
# mastra_messages
# mastra_threads
# mastra_traces
# mastra_workflow_snapshot