エージェントでツールを使用する
ツールは、エージェントやワークフローによって実行できる型付き関数です。各ツールには、その入力を定義するスキーマ、ロジックを実装する実行関数、およびオプションで設定された統合へのアクセスがあります。
ツールの作成
以下はツールを作成する基本的な例です:
import { createTool } from "@mastra/core/tools";
import { z } from "zod";
export const weatherInfo = createTool({
id: "Get Weather Information",
inputSchema: z.object({
city: z.string(),
}),
description: `Fetches the current weather information for a given city`,
execute: async ({ context: { city } }) => {
// Tool logic here (e.g., API call)
console.log("Using tool to fetch weather information for", city);
return { temperature: 20, conditions: "Sunny" }; // Example return
},
});
ツールの作成と設計の詳細については、ツールの概要をご覧ください。
エージェントにツールを追加する
ツールをエージェントで利用可能にするには、エージェントの設定の tools
プロパティに追加します。
import { Agent } from "@mastra/core/agent";
import { openai } from "@ai-sdk/openai";
import { weatherInfo } from "../tools/weatherInfo";
export const weatherAgent = new Agent({
name: "Weather Agent",
instructions:
"You are a helpful assistant that provides current weather information. When asked about the weather, use the weather information tool to fetch the data.",
model: openai("gpt-4o-mini"),
tools: {
weatherInfo,
},
});
エージェントを呼び出すと、設定されたツールを指示内容とユーザーのプロンプトに基づいて使用するかどうかを判断できるようになります。
AgentにMCPツールを追加する
Model Context Protocol (MCP) は、AIモデルが外部ツールやリソースを発見し、それらと相互作用するための標準化された方法を提供します。MastraエージェントをMCPサーバーに接続して、サードパーティが提供するツールを使用できます。
MCPの概念やMCPクライアントとサーバーの設定方法の詳細については、MCP概要を参照してください。
インストール
まず、Mastra MCPパッケージをインストールします:
npm install @mastra/mcp@latest
MCPツールの使用
選択できるMCPサーバーレジストリが非常に多いため、MCPサーバーを見つけるのに役立つMCP Registry Registry を作成しました。
エージェントで使用したいサーバーが決まったら、MastraのMCPClient
をインポートし、サーバー設定を追加します。
import { MCPClient } from "@mastra/mcp";
// MCPClientを設定してサーバーに接続
export const mcp = new MCPClient({
servers: {
filesystem: {
command: "npx",
args: [
"-y",
"@modelcontextprotocol/server-filesystem",
"/Users/username/Downloads",
],
},
},
});
次に、エージェントをサーバーツールに接続します:
import { Agent } from "@mastra/core/agent";
import { openai } from "@ai-sdk/openai";
import { mcp } from "../mcp";
// エージェントを作成し、MCPクライアントからツールを追加
const agent = new Agent({
name: "Agent with MCP Tools",
instructions: "You can use tools from connected MCP servers.",
model: openai("gpt-4o-mini"),
tools: await mcp.getTools(),
});
MCPClient
の設定や静的および動的MCPサーバー設定の違いの詳細については、MCP概要を参照してください。
MCP リソースへのアクセス
ツールに加えて、MCPサーバーはリソース(アプリケーションで取得・使用できるデータやコンテンツ)も公開できます。
import { mcp } from "./mcp";
// Get resources from all connected MCP servers
const resources = await mcp.getResources();
// Access resources from a specific server
if (resources.filesystem) {
const resource = resources.filesystem.find(
(r) => r.uri === "filesystem://Downloads",
);
console.log(`Resource: ${resource?.name}`);
}
各リソースには、URI、名前、説明、MIMEタイプがあります。getResources()
メソッドはエラーを適切に処理します - サーバーが失敗したり、リソースをサポートしていない場合、結果から除外されます。
MCP プロンプトへのアクセス
MCP サーバーはプロンプトも公開できます。プロンプトは、エージェント向けの構造化されたメッセージテンプレートや会話コンテキストを表します。
プロンプトの一覧表示
import { mcp } from "./mcp";
// 接続されているすべての MCP サーバーからプロンプトを取得
const prompts = await mcp.prompts.list();
// 特定のサーバーからプロンプトにアクセス
if (prompts.weather) {
const prompt = prompts.weather.find(
(p) => p.name === "current"
);
console.log(`Prompt: ${prompt?.name}`);
}
各プロンプトには名前、説明、および(オプションの)バージョンがあります。
プロンプトとそのメッセージの取得
const { prompt, messages } = await mcp.prompts.get({ serverName: "weather", name: "current" });
console.log(prompt); // { name: "current", version: "v1", ... }
console.log(messages); // [ { role: "assistant", content: { type: "text", text: "..." } }, ... ]
MCPServerを介してAgentをToolとして公開する
MCPサーバーからツールを使用することに加えて、あなたのMastra Agent自体をMastraのMCPServer
を使用して任意のMCP互換クライアントにツールとして公開することができます。
Agent
インスタンスがMCPServer
の設定に提供されると:
- 自動的に呼び出し可能なツールに変換されます。
- ツールは
ask_<agentKey>
という名前になります。ここで<agentKey>
は、MCPServer
のagents
設定にエージェントを追加する際に使用した識別子です。 - エージェントの
description
プロパティ(空でない文字列である必要があります)がツールの説明を生成するために使用されます。
これにより、他のAIモデルやMCPクライアントが、あなたのMastra Agentを標準的なツールであるかのように、通常は質問を「尋ねる」ことで対話できるようになります。
Agentを含むMCPServer
設定の例:
import { Agent } from "@mastra/core/agent";
import { MCPServer } from "@mastra/mcp";
import { openai } from "@ai-sdk/openai";
import { weatherInfo } from "../tools/weatherInfo";
import { generalHelper } from "../agents/generalHelper";
const server = new MCPServer({
name: "My Custom Server with Agent-Tool",
version: "1.0.0",
tools: {
weatherInfo,
},
agents: { generalHelper }, // 'ask_generalHelper'ツールを公開
});
エージェントがMCPServer
によってツールに正常に変換されるためには、そのコンストラクタ設定でdescription
プロパティが空でない文字列に設定されている必要があります。説明が欠けているか空の場合、MCPServer
は初期化中にエラーをスローします。
MCPServer
の設定と構成の詳細については、MCPServerリファレンスドキュメントを参照してください。