Mastra + Ollama + MCPでローカルAIエージェントを作る

に公開

はじめに

どんな人向けの記事?

  • ローカルLLMでAIエージェントを作りたい方

背景

2ヶ月ほど前、生成AIなんでも展示会向けにMastra + MCPを組み合わせたローカルのAIエージェントを作成した。当初Mastra + Ollama + MCPの組み合わせは動かなかったが、4月末時点で動くようになった。

https://x.com/gosrum/status/1917071781653057846

この方法を記事にしていなかったので、今更ながらその方法の備忘録メモを残す。

開発環境は以下の通りだが、MacやWindows環境でもほぼ同じコマンドで動作するはず。

開発環境
Ubuntu 24.04@EVO-X2(AMD Ryzen AI Max+ 395、UMA 128GB)

今回作成したコード

  • Mastra + Ollama + MCP構成のサンプルコード(手っ取り早くローカルAIエージェントを使いたい人用)

https://github.com/robustonian/mastra_ollama_mcp

  • Streamable HTTP transportなMCPサーバー(デプロイ済なのでCloneは不要)

https://github.com/robustonian/streamable_http_mcp_test

Mastraの導入

mastraリポジトリのREADME.mdおよび、ニケちゃんさんの記事に従ってMastraを導入する。

https://github.com/mastra-ai/mastra

https://note.com/nike_cha_n/n/nbc7696f06eb8

というわけで、まずはMastraを導入する。Mastraの導入自体は簡単で下記のコマンドを一つ打つだけで良い。

$ npx create-mastra@latest
Need to install the following packages:
create-mastra@0.10.5
Ok to proceed? (y) y

┌   Mastra Create 
│
◇  What do you want to name your project?
│  mastra_ollama_mcp
│
◇  Project structure created
│
◇  npm dependencies installed
│
◇  mastra installed
│
◇  Mastra dependencies installed
│
◇  .gitignore added
│
└  Project created successfully


┌   Mastra Init 
│
◇  Where should we create the Mastra files? (default: src/)
│  src/
│
◇  Select default provider:
│  OpenAI
│
◇  Enter your openai API key?
│  Skip for now
│
◇  Make your AI IDE into a Mastra expert? (installs Mastra docs MCP server)
│  Skip for now
│

up to date, audited 759 packages in 1s

126 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities
◇  
│
◇   ─────────────────────────────────────────────────────────╮
│                                                            │
│                                                            │
│        Mastra initialized successfully!                    │
│                                                            │
│        Add your OPENAI_API_KEY as an environment variable  │
│        in your .env file                                   │
│                                                            │
│                                                            │
├────────────────────────────────────────────────────────────╯
│
└  
   To start your project:

    cd mastra_ollama_mcp
    npm run dev

OpenAIを使いたい場合は、APIキーを設定する。あとは下記のコマンドを実行し、webブラウザでhttp://localhost:4111にアクセスすればMastraのGUIが起動する。

$ cd mastra_ollama_mcp
$ npm run dev

> mastra_ollama_mcp@1.0.0 dev
> mastra dev

INFO [2025-06-25 00:09:29.175 +0900] (Mastra CLI): Installing dependencies
added 250 packages, and audited 251 packages in 2s

9 packages are looking for funding
  run `npm fund` for details
INFO [2025-06-25 00:09:30.974 +0900] (Mastra CLI): added 250 packages, and audited 251 packages in 2s

9 packages are looking for funding
  run `npm fund` for details
found 0 vulnerabilities
INFO [2025-06-25 00:09:30.975 +0900] (Mastra CLI): found 0 vulnerabilities
INFO [2025-06-25 00:09:30.994 +0900] (Mastra CLI): Done installing dependencies
INFO [2025-06-25 00:09:30.995 +0900] (Mastra CLI): Starting watcher...
INFO [2025-06-25 00:09:31.389 +0900] (Mastra CLI): Bundling finished, starting server...
INFO [2025-06-25 00:09:31.410 +0900] (Mastra CLI): [Mastra Dev] - Starting server...
INFO [2025-06-25 00:09:32.565 +0900] (Mastra):  Mastra API running on port http://localhost:4111/api
INFO [2025-06-25 00:09:32.567 +0900] (Mastra): 👨‍💻 Playground available at http://localhost:4111

.envにOPENAI_API_KEY=sk-proj...のAPIキーを入力することで、デフォルトのAIエージェントとの会話ができる。ただし、私の環境ではweatherToolが使えなかった。まあこのツールは使わないので気にしないで良い。

MastraへのOllama + MCP導入

MastraでOllamaを使うために、ollama-ai-provider@mastra/mcpおよびdotenvを導入する。

$ npm i ollama-ai-provider @mastra/mcp dotenv

mastra_ollama_mcp/src/mastra/index.tsを下記のように書き換える。

mastra_ollama_mcp/src/mastra/index.ts
import { Mastra } from '@mastra/core/mastra';
import { PinoLogger } from '@mastra/loggers';
import { LibSQLStore } from '@mastra/libsql';
import { weatherWorkflow} from './workflows/weather-workflow';
import { weatherAgent } from './agents/weather-agent';
import { OllamaAgent } from './agents/mcpAgent';

export const mastra = new Mastra({
  workflows: { weatherWorkflow },
  agents: { weatherAgent, OllamaAgent}, 
  storage: new LibSQLStore({
    // stores telemetry, evals, ... into memory storage, if it needs to persist, change to file:../mastra.db
    url: ":memory:",
  }),
  logger: new PinoLogger({
    name: 'Mastra',
    level: 'info',
  }),
});

次に、mastra_ollama_mcp/src/mastra/agents/mcpAgent.tsを下記のように作成する。

mastra_ollama_mcp/src/mastra/agents/mcpAgent.ts
import { Agent } from '@mastra/core/agent';
import { Memory } from '@mastra/memory';
import { LibSQLStore } from '@mastra/libsql';
import { MCPClient } from "@mastra/mcp";
import { createOllama } from 'ollama-ai-provider';
import 'dotenv/config';

const ollama = createOllama({
  baseURL: process.env.OLLAMA_BASE_URL || 'http://localhost:11434/api',
});

const mcp = new MCPClient({
  servers: {
    // stdio example
    // "mastra-docs": {
    //   "command": "npx",
    //   "args": [
    //     "-y",
    //     "@mastra/mcp-docs-server"
    //   ],
    // },
    // streamable http example
    "dice-roller": {
      "command": "npx",
      "args": [
        "-y",
        "mcp-remote", "https://streamable_http_mcp_test.robustonian.com/mcp"
      ],
    },
  },
});

export const OllamaAgent = new Agent({
  name: 'Ollama Agent',
//   instructions: `
//       あなたはmastra-docsツールを介して、MastraのDocumentsにアクセスできるAIエージェントです。
// `,
  instructions: `
      あなたはサイコロを振るスキルを持った特別なAIエージェントです。
`,
  model: ollama(process.env.OLLAMA_MODEL || 'qwen3:8b'),
  tools: await mcp.getTools(),
  memory: new Memory({
    storage: new LibSQLStore({
      url: 'file:../mastra.db', // path is relative to the .mastra/output directory
    }),
  }),
});

最後に、.envに下記を追加する。必要に応じてURLやモデル名を修正されたい。

.env
OLLAMA_BASE_URL=http://localhost:11434/api
OLLAMA_MODEL=Qwen3-32B-GGUF:UD-Q4_K_XL_think

改めてnpm run devを実行する。

$ npm run dev

> mastra_ollama_mcp@1.0.0 dev
> mastra dev

INFO [2025-06-25 22:03:02.169 +0900] (Mastra CLI): Starting watcher...
INFO [2025-06-25 22:03:02.708 +0900] (Mastra CLI): Bundling finished, starting server...
INFO [2025-06-25 22:03:02.722 +0900] (Mastra CLI): [Mastra Dev] - Starting server...
INFO [2025-06-25 22:03:04.805 +0900] (Mastra):  Mastra API running on port http://localhost:4111/api
INFO [2025-06-25 22:03:04.807 +0900] (Mastra): 👨‍💻 Playground available at http://localhost:4111

webブラウザでhttp://localhost:4111にアクセスし、Agents -> Ollama Agentをクリックすると、Agentと会話ができる。

しかし、そのままの状態でツールを使おうとすると失敗する。

上述したとおり、Chat MethodをGenerateに変更することでOllamaモデルでもMCPを利用することができるようになる。

上記のようにDice Roller MCPを使い、その結果に基づいて回答してくれていることがわかる。

以上で、Mastra + Ollama + MCPによるAIエージェントが作れたことになる。

AITuberKitとの連携

最後に、作成したローカルAIエージェントとAITuberKitの接続を試みる。

...が、AITuberKitの方は逆にストリーミングモードしか選択できず、残念ながら連携できず。

https://x.com/gosrum/status/1937907634755305829

上述したように、Ollamaの最近の更新でTool Use時にもStreamingできるようにはなっているはずなので、ollama-ai-providerをTool Streamingに対応させることができれば、万事解決するはず!

とはいえこの改修については本筋からそれてしまうため、本記事はここまでとしたい。

まとめ

今回の記事では、下記について備忘録的にまとめました。

  • Mastra + Ollama + MCPを用いたローカルAIエージェントの作成方法
  • ollama-ai-providerの注意点
  • AITuberKitとの接続について

残念ながら、AITuberKitとの接続については、ollama-ai-providerをTool Streaming対応が必要であることがわかりました。

というわけで、(うまくいったら)次回はAITuberKitとの接続方法を含めて連携についての記事を書きたいと思います。

最後まで読んでいただきありがとうございました。次回もぜひよろしくお願いします。

Discussion