MCPServer
MCPServer
クラスは、既存の Mastra のツールやエージェントを Model Context Protocol(MCP)サーバーとして公開するための機能を提供します。これにより、任意の MCP クライアント(Cursor、Windsurf、Claude Desktop など)がこれらの機能に接続し、エージェントで利用できるようになります。
ツールやエージェントを Mastra アプリケーション内で直接使うだけで十分な場合は、必ずしも MCP サーバーを作成する必要はありません。この API は、Mastra のツールやエージェントを外部の MCP クライアントに公開するためのものです。
stdio(サブプロセス)および SSE(HTTP)の MCP トランスポート の両方に対応しています。
コンストラクター
新しい MCPServer
を作成するには、サーバーに関する基本情報、そのサーバーが提供するツール、そして任意で、ツールとして公開したいエージェントを指定します。
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { createTool } from "@mastra/core/tools";
import { MCPServer } from "@mastra/mcp";
import { z } from "zod";
import { dataProcessingWorkflow } from "../workflows/dataProcessingWorkflow";
const myAgent = new Agent({
name: "MyExampleAgent",
description: "A generalist to help with basic questions."
instructions: "You are a helpful assistant.",
model: openai("gpt-4o-mini"),
});
const weatherTool = createTool({
id: "getWeather",
description: "Gets the current weather for a location.",
inputSchema: z.object({ location: z.string() }),
execute: async ({ context }) => `Weather in ${context.location} is sunny.`,
});
const server = new MCPServer({
name: "My Custom Server",
version: "1.0.0",
tools: { weatherTool },
agents: { myAgent }, // このエージェントはツール「ask_myAgent」になります
workflows: {
dataProcessingWorkflow, // このワークフローはツール「run_dataProcessingWorkflow」になります
}
});
設定プロパティ
コンストラクタは、以下のプロパティを持つ MCPServerConfig
オブジェクトを受け取ります:
name:
version:
tools:
agents?:
workflows?:
id?:
description?:
repository?:
releaseDate?:
isLatest?:
packageCanonical?:
packages?:
remotes?:
resources?:
prompts?:
エージェントをツールとして公開する
MCPServer
の強力な機能の1つは、Mastra エージェントを自動的に呼び出し可能なツールとして公開できることです。設定の agents
プロパティにエージェントを指定すると:
-
ツール名: 各エージェントは
ask_<agentKey>
という名前のツールに変換されます。ここで<agentKey>
はagents
オブジェクトでそのエージェントに使用したキーです。たとえば、agents: { myAgentKey: myAgentInstance }
と設定した場合、ask_myAgentKey
という名前のツールが作成されます。 -
ツールの機能:
- 説明: 生成されるツールの説明は次の形式になります: “エージェント
<AgentName>
に質問します。元のエージェントの指示:<agent description>
” - 入力: ツールは
message
プロパティ(文字列)を持つ単一のオブジェクト引数を受け取ります:{ message: "エージェントへの質問内容" }
。 - 実行: このツールが呼び出されると、対応するエージェントの
generate()
メソッドを、渡されたquery
とともに実行します。 - 出力: エージェントの
generate()
メソッドの結果が、そのままツールの出力として返されます。
- 説明: 生成されるツールの説明は次の形式になります: “エージェント
-
名前の衝突:
tools
設定で定義された明示的なツールが、エージェント由来のツールと同じ名前を持つ場合(例:ask_myAgentKey
というツールがあり、同時にキーmyAgentKey
のエージェントもある場合)、明示的に定義されたツールが優先されます。この衝突が起きた場合、そのエージェントはツールに変換されず、警告がログに記録されます。
これにより、MCP クライアントは他のツールと同様に、自然言語によるクエリでエージェントとやり取りできるようになります。
エージェントからツールへの変換
agents
構成プロパティでエージェントを指定すると、MCPServer
は各エージェントに対応するツールを自動的に作成します。ツール名は ask_<agentIdentifier>
となり、<agentIdentifier>
は agents
オブジェクトで使用したキーです。
生成されるツールの説明は次のとおりです: “エージェント <agent.name>
に質問します。エージェントの説明: <agent.description>
”。
重要: エージェントをツールに変換するには、インスタンス化時の構成で空でない description
文字列プロパティが設定されている必要があります(例: new Agent({ name: 'myAgent', description: 'This agent does X.', ... })
)。description
が欠落している、または空のエージェントが MCPServer
に渡された場合、MCPServer
のインスタンス化時にエラーがスローされ、サーバーのセットアップは失敗します。
これにより、MCP を通じてエージェントの生成能力を迅速に公開でき、クライアントはエージェントに直接「質問」できるようになります。
メソッド
MCPServer
インスタンスに対して呼び出して、動作を制御したり情報を取得したりできる関数です。
startStdio()
このメソッドは、サーバーを標準入力・標準出力(stdio)で通信するモードで起動します。サーバーをコマンドラインプログラムとして実行する場合に一般的です。
async startStdio(): Promise<void>
stdio を使ってサーバーを起動する方法は次のとおりです:
const server = new MCPServer({
// example configuration above
});
await server.startStdio();
startSSE()
このメソッドは、既存のウェブサーバーにMCPサーバーを統合し、通信にServer-Sent Events (SSE) を利用できるようにするためのものです。SSE用またはメッセージ用のパスへのリクエストを受け取った際、ウェブサーバー側のコードから呼び出してください。
async startSSE({
url,
ssePath,
messagePath,
req,
res,
}: {
url: URL;
ssePath: string;
messagePath: string;
req: any;
res: any;
}): Promise<void>
以下は、HTTPサーバーのリクエストハンドラー内でstartSSE
を使用する例です。この例では、MCPクライアントはhttp://localhost:1234/sse
であなたのMCPサーバーに接続できます。
import http from "http";
const httpServer = http.createServer(async (req, res) => {
await server.startSSE({
url: new URL(req.url || "", `http://localhost:1234`),
ssePath: "/sse",
messagePath: "/message",
req,
res,
});
});
httpServer.listen(PORT, () => {
console.log(`HTTP server listening on port ${PORT}`);
});
startSSE
メソッドに必要な値の詳細は次のとおりです:
url:
ssePath:
messagePath:
req:
res:
startHonoSSE()
このメソッドは、既存のウェブサーバーにMCPサーバーを統合し、通信にServer-Sent Events(SSE)を利用できるようにします。SSE用またはメッセージ用のパスへのリクエストを受け取った際に、ウェブサーバー側のコードから呼び出してください。
async startHonoSSE({
url,
ssePath,
messagePath,
req,
res,
}: {
url: URL;
ssePath: string;
messagePath: string;
req: any;
res: any;
}): Promise<void>
以下は、HTTPサーバーのリクエストハンドラー内でstartHonoSSE
を使用する例です。この例では、MCPクライアントはhttp://localhost:1234/hono-sse
であなたのMCPサーバーに接続できます。
import http from "http";
const httpServer = http.createServer(async (req, res) => {
await server.startHonoSSE({
url: new URL(req.url || "", `http://localhost:1234`),
ssePath: "/hono-sse",
messagePath: "/message",
req,
res,
});
});
httpServer.listen(PORT, () => {
console.log(`HTTP server listening on port ${PORT}`);
});
startHonoSSE
メソッドに必要な値の詳細は次のとおりです。
url:
ssePath:
messagePath:
req:
res:
startHTTP()
このメソッドは、既存のWebサーバーにMCPサーバーを統合し、通信にストリーム対応のHTTPを使えるようにします。WebサーバーがHTTPリクエストを受け取ったときに、その処理コードから呼び出してください。
async startHTTP({
url,
httpPath,
req,
res,
options = { sessionIdGenerator: () => randomUUID() },
}: {
url: URL;
httpPath: string;
req: http.IncomingMessage;
res: http.ServerResponse<http.IncomingMessage>;
options?: StreamableHTTPServerTransportOptions;
}): Promise<void>
以下は、HTTPサーバーのリクエストハンドラー内でstartHTTP
を使用する例です。この例では、MCPクライアントはhttp://localhost:1234/http
であなたのMCPサーバーに接続できます。
import http from "http";
const httpServer = http.createServer(async (req, res) => {
await server.startHTTP({
url: new URL(req.url || '', 'http://localhost:1234'),
httpPath: `/mcp`,
req,
res,
options: {
sessionIdGenerator: undefined,
},
});
});
httpServer.listen(PORT, () => {
console.log(`HTTP server listening on port ${PORT}`);
});
startHTTP
メソッドに必要な各値の詳細は次のとおりです。
url:
httpPath:
req:
res:
options:
StreamableHTTPServerTransportOptions
オブジェクトでは、HTTPトランスポートの動作をカスタマイズできます。利用可能なオプションは次のとおりです。
sessionIdGenerator:
onsessioninitialized:
enableJsonResponse:
eventStore:
close()
このメソッドはサーバーを終了し、すべてのリソースを解放します。
async close(): Promise<void>
getServerInfo()
このメソッドはサーバーの基本情報を取得します。
getServerInfo(): ServerInfo
getServerDetail()
このメソッドはサーバーの詳細情報を取得します。
getServerDetail(): ServerDetail
getToolListInfo()
このメソッドを使うと、サーバー作成時に設定されたツールの一覧を確認できます。読み取り専用のリストで、デバッグに役立ちます。
getToolListInfo(): ToolListInfo
getToolInfo()
このメソッドは、特定のツールの詳細情報を取得します。
getToolInfo(toolName: string): ToolInfo
executeTool()
このメソッドは指定したツールを実行し、その結果を返します。
executeTool(toolName: string, input: any): Promise<any>
getStdioTransport()
サーバーを startStdio()
で起動した場合、stdio 通信を管理するオブジェクトを取得するために使用できます。これは主に内部チェックやテストのために用いられます。
getStdioTransport(): StdioServerTransport | undefined
getSseTransport()
サーバーを startSSE()
で起動している場合、SSE 通信を管理するオブジェクトを取得できます。getStdioTransport
と同様に、主に内部確認やテスト用途で使用します。
getSseTransport(): SSEServerTransport | undefined
getSseHonoTransport()
サーバーを startHonoSSE()
で起動した場合、SSE 通信を管理するオブジェクトを取得するために使用できます。getSseTransport
と同様に、主に内部的な確認やテストのために用いられます。
getSseHonoTransport(): SSETransport | undefined
getStreamableHTTPTransport()
サーバーを startHTTP()
で起動した場合、HTTP 通信を管理するオブジェクトを取得するために使用できます。getSseTransport
と同様に、主に内部確認やテスト用途を想定しています。
getStreamableHTTPTransport(): StreamableHTTPServerTransport | undefined
tools()
この MCP サーバーが提供する特定のツールを実行します。
async executeTool(
toolId: string,
args: any,
executionContext?: { messages?: any[]; toolCallId?: string },
): Promise<any>
toolId:
args:
executionContext?:
リソースの扱い
MCP Resources とは?
Resources は Model Context Protocol (MCP) における中核的なプリミティブで、サーバーがクライアントから読み取られ、LLM とのやり取りの文脈として利用できるデータやコンテンツを公開するための仕組みです。これは MCP サーバーが提供したいあらゆる種類のデータを表し、例えば次のようなものがあります:
- ファイルの内容
- データベースのレコード
- API のレスポンス
- ライブシステムのデータ
- スクリーンショットや画像
- ログファイル
Resources は一意の URI(例: file:///home/user/documents/report.pdf
, postgres://database/customers/schema
)で識別され、テキスト(UTF-8 エンコード)またはバイナリデータ(base64 エンコード)を含むことができます。
クライアントは次の方法で Resources を発見できます:
- Direct resources: サーバーは
resources/list
エンドポイントを通じて具体的な Resource の一覧を公開します。 - Resource templates: 動的な Resource のために、サーバーはクライアントが Resource URI を構築する際に用いる URI テンプレート(RFC 6570)を公開できます。
Resource を読み取るには、クライアントは対象の URI を指定して resources/read
リクエストを送信します。クライアントがその Resource を購読している場合、サーバーは Resource 一覧の変更(notifications/resources/list_changed
)や特定の Resource コンテンツの更新(notifications/resources/updated
)をクライアントに通知できます。
より詳しくは、Resources に関する公式 MCP ドキュメント を参照してください。
MCPServerResources
型
resources
オプションには MCPServerResources
型のオブジェクトを渡します。この型は、サーバーがリソース要求を処理するために用いるコールバックを定義します:
export type MCPServerResources = {
// 利用可能なリソースを一覧するコールバック
listResources: () => Promise<Resource[]>;
// 特定のリソースの内容を取得するコールバック
getResourceContent: ({
uri,
}: {
uri: string;
}) => Promise<MCPServerResourceContent | MCPServerResourceContent[]>;
// 利用可能なリソーステンプレートを一覧する任意のコールバック
resourceTemplates?: () => Promise<ResourceTemplate[]>;
};
export type MCPServerResourceContent = { text?: string } | { blob?: string };
例:
import { MCPServer } from "@mastra/mcp";
import type {
MCPServerResourceContent,
Resource,
ResourceTemplate,
} from "@mastra/mcp";
// リソースやリソーステンプレートは、通常は動的に取得されます。
const myResources: Resource[] = [
{ uri: "file://data/123.txt", name: "Data File", mimeType: "text/plain" },
];
const myResourceContents: Record<string, MCPServerResourceContent> = {
"file://data.txt/123": { text: "This is the content of the data file." },
};
const myResourceTemplates: ResourceTemplate[] = [
{
uriTemplate: "file://data/{id}",
name: "Data File",
description: "A file containing data.",
mimeType: "text/plain",
},
];
const myResourceHandlers: MCPServerResources = {
listResources: async () => myResources,
getResourceContent: async ({ uri }) => {
if (myResourceContents[uri]) {
return myResourceContents[uri];
}
throw new Error(`Resource content not found for ${uri}`);
},
resourceTemplates: async () => myResourceTemplates,
};
const serverWithResources = new MCPServer({
name: "Resourceful Server",
version: "1.0.0",
tools: {
/* ... your tools ... */
},
resources: myResourceHandlers,
});
リソース変更のクライアントへの通知
利用可能なリソースやその内容が変更された場合、サーバーはそのリソースを購読している接続中のクライアントに通知できます。
server.resources.notifyUpdated({ uri: string })
特定のリソース(uri
で識別される)の内容が更新されたときに、このメソッドを呼び出します。いずれかのクライアントがこの URI を購読している場合、notifications/resources/updated
メッセージを受信します。
async server.resources.notifyUpdated({ uri: string }): Promise<void>
例:
// 'file://data.txt' の内容を更新した後
await serverWithResources.resources.notifyUpdated({ uri: "file://data.txt" });
server.resources.notifyListChanged()
利用可能なリソースの一覧全体に変更があったとき(例: リソースが追加または削除されたとき)に、このメソッドを呼び出します。これによりクライアントに notifications/resources/list_changed
メッセージが送信され、リソース一覧の再取得を促します。
async server.resources.notifyListChanged(): Promise<void>
例:
// 'myResourceHandlers.listResources' が管理する一覧に新しいリソースを追加した後
await serverWithResources.resources.notifyListChanged();
プロンプトの取り扱い
MCP プロンプトとは?
プロンプトは、MCP サーバーがクライアントに公開する再利用可能なテンプレートまたはワークフローです。引数の受け取り、リソースコンテキストの取り込み、バージョン管理のサポートが可能で、LLM とのやり取りを標準化するために使えます。
プロンプトは一意の名前(必要に応じてバージョン)で識別され、動的にも静的にもなり得ます。
MCPServerPrompts
型
prompts
オプションには MCPServerPrompts
型のオブジェクトを渡します。この型は、サーバーがプロンプト要求を処理するために使用するコールバックを定義します。
export type MCPServerPrompts = {
// 利用可能なプロンプトを一覧するコールバック
listPrompts: () => Promise<Prompt[]>;
// 特定のプロンプトのメッセージ/コンテンツを取得するコールバック
getPromptMessages?: ({
name,
version,
args,
}: {
name: string;
version?: string;
args?: any;
}) => Promise<{ prompt: Prompt; messages: PromptMessage[] }>;
};
例:
import { MCPServer } from "@mastra/mcp";
import type { Prompt, PromptMessage, MCPServerPrompts } from "@mastra/mcp";
const prompts: Prompt[] = [
{
name: "analyze-code",
description: "Analyze code for improvements",
version: "v1"
},
{
name: "analyze-code",
description: "Analyze code for improvements (new logic)",
version: "v2"
}
];
const myPromptHandlers: MCPServerPrompts = {
listPrompts: async () => prompts,
getPromptMessages: async ({ name, version, args }) => {
if (name === "analyze-code") {
if (version === "v2") {
const prompt = prompts.find(p => p.name === name && p.version === "v2");
if (!prompt) throw new Error("Prompt version not found");
return {
prompt,
messages: [
{
role: "user",
content: { type: "text", text: `Analyze this code with the new logic: ${args.code}` }
}
]
};
}
// デフォルトまたは v1
const prompt = prompts.find(p => p.name === name && p.version === "v1");
if (!prompt) throw new Error("Prompt version not found");
return {
prompt,
messages: [
{
role: "user",
content: { type: "text", text: `Analyze this code: ${args.code}` }
}
]
};
}
throw new Error("Prompt not found");
}
};
const serverWithPrompts = new MCPServer({
name: "Promptful Server",
version: "1.0.0",
tools: { /* ... */ },
prompts: myPromptHandlers,
});
プロンプトの変更をクライアントに通知する
利用可能なプロンプトが変更された場合、サーバーは接続中のクライアントに通知できます。
server.prompts.notifyListChanged()
利用可能なプロンプトの一覧に変更があった場合(例:プロンプトが追加または削除された場合)に、このメソッドを呼び出してください。これにより、クライアントに notifications/prompts/list_changed
メッセージが送信され、プロンプト一覧の再取得を促します。
await serverWithPrompts.prompts.notifyListChanged();
プロンプト処理のベストプラクティス
- わかりやすく具体的なプロンプト名と説明を付ける。
getPromptMessages
で必須引数をすべて検証する。- 互換性のない変更を行う可能性がある場合は
version
フィールドを含める。 - 適切なプロンプトロジックを選択するために
version
パラメータを使用する。 - プロンプト一覧に変更があった場合はクライアントに通知する。
- わかりやすいメッセージでエラーを処理する。
- 引数の要件と利用可能なバージョンを文書化する。
例
MCPServer のセットアップとデプロイの実用的な例については、Deploying an MCPServer Example を参照してください。
このページ冒頭の例では、ツールとエージェントの両方を使って MCPServer
をインスタンス化する方法も示しています。
要求整理
Elicitation とは?
Elicitation は Model Context Protocol (MCP) の機能で、サーバーがユーザーに対して構造化された情報の提供を求められるようにします。これにより、サーバーが動的に追加データを収集できる双方向型のワークフローが可能になります。
MCPServer
クラスには Elicitation 機能が自動的に組み込まれています。ツールは execute
関数で options
パラメータを受け取り、その中の elicitation.sendRequest()
メソッドを使ってユーザー入力を要求できます。
ツール実行シグネチャ
ツールが MCP サーバーのコンテキスト内で実行されると、追加の options
パラメータを受け取ります:
execute: async ({ context }, options) => {
// context にはツールの入力パラメータが含まれます
// options にはエリシテーションや認証情報などのサーバー機能が含まれます
// 認証情報にアクセス(利用可能な場合)
if (options.extra?.authInfo) {
console.log('Authenticated request from:', options.extra.authInfo.clientId);
}
// エリシテーション機能を使用
const result = await options.elicitation.sendRequest({
message: "Please provide information",
requestedSchema: { /* schema */ }
});
return result;
}
Elicitation の仕組み
一般的なユースケースはツールの実行中です。ツールがユーザー入力を必要とする場合は、ツールの実行オプションで提供されている elicitation 機能を利用します:
- ツールはメッセージとスキーマを指定して
options.elicitation.sendRequest()
を呼び出します - リクエストは接続中の MCP クライアントに送信されます
- クライアントがユーザーにリクエストを提示します(UI、コマンドラインなど)
- ユーザーは入力を行うか、辞退するか、リクエストをキャンセルします
- クライアントがレスポンスをサーバーに返送します
- ツールがレスポンスを受け取り、実行を続行します
ツールでのエリシテーションの活用
以下は、エリシテーションを用いてユーザーの連絡先情報を収集するツールの例です:
import { MCPServer } from "@mastra/mcp";
import { createTool } from "@mastra/core/tools";
import { z } from "zod";
const server = new MCPServer({
name: "Interactive Server",
version: "1.0.0",
tools: {
collectContactInfo: createTool({
id: "collectContactInfo",
description: "エリシテーションを通じてユーザーの連絡先情報を収集します",
inputSchema: z.object({
reason: z.string().optional().describe("連絡先情報を収集する理由"),
}),
execute: async ({ context }, options) => {
const { reason } = context;
// セッション情報があればログに記録
console.log('Request from session:', options.extra?.sessionId);
try {
// エリシテーションでユーザー入力を要求
const result = await options.elicitation.sendRequest({
message: reason
? `連絡先情報をご提供ください。${reason}`
: '連絡先情報をご提供ください',
requestedSchema: {
type: 'object',
properties: {
name: {
type: 'string',
title: '氏名',
description: 'フルネーム',
},
email: {
type: 'string',
title: 'メールアドレス',
description: 'あなたのメールアドレス',
format: 'email',
},
phone: {
type: 'string',
title: '電話番号',
description: 'あなたの電話番号(任意)',
},
},
required: ['name', 'email'],
},
});
// ユーザーの応答を処理
if (result.action === 'accept') {
return `連絡先情報を収集しました: ${JSON.stringify(result.content, null, 2)}`;
} else if (result.action === 'decline') {
return 'ユーザーが連絡先情報の収集を拒否しました。';
} else {
return 'ユーザーが連絡先情報の収集をキャンセルしました。';
}
} catch (error) {
return `連絡先情報の収集中にエラーが発生しました: ${error}`;
}
},
}),
},
});
取得リクエスト用スキーマ
requestedSchema
はプリミティブなプロパティのみを持つフラットなオブジェクトである必要があります。サポートされる型は次のとおりです:
- String:
{ type: 'string', title: 'Display Name', description: 'Help text' }
- Number:
{ type: 'number', minimum: 0, maximum: 100 }
- Boolean:
{ type: 'boolean', default: false }
- Enum:
{ type: 'string', enum: ['option1', 'option2'] }
スキーマの例:
{
type: 'object',
properties: {
name: {
type: 'string',
title: 'Full Name',
description: 'Your complete name',
},
age: {
type: 'number',
title: 'Age',
minimum: 18,
maximum: 120,
},
newsletter: {
type: 'boolean',
title: 'Subscribe to Newsletter',
default: false,
},
},
required: ['name'],
}
レスポンスアクション
ユーザーは引き出し要求に対して次の3つの方法で応答できます:
- Accept (
action: 'accept'
): ユーザーがデータを提供し、送信を確定した- 送信したデータを保持する
content
フィールドがある
- 送信したデータを保持する
- Decline (
action: 'decline'
): ユーザーが情報提供を明示的に拒否したcontent
フィールドはない
- Cancel (
action: 'cancel'
): ユーザーが判断せずにリクエストを閉じたcontent
フィールドはない
ツールは3種類すべてのレスポンスタイプを適切に処理する必要があります。
セキュリティに関する留意事項
- パスワード、社会保障番号(SSN)、クレジットカード番号などの機密情報を絶対に要求しない
- すべてのユーザー入力を提供されたスキーマに基づいて検証する
- 辞退やキャンセルを丁寧かつ円滑に処理する
- データ収集の目的を明確に説明する
- ユーザーのプライバシーと設定・選好を尊重する
ツール実行 API
エリシテーション機能は、ツール実行時の options
パラメータから利用できます:
// ツールの execute 関数内
execute: async ({ context }, options) => {
// ユーザー入力にエリシテーションを使用
const result = await options.elicitation.sendRequest({
message: string, // ユーザーに表示するメッセージ
requestedSchema: object // 期待される応答構造を定義する JSON スキーマ
}): Promise<ElicitResult>
// 必要に応じて認証情報にアクセス
if (options.extra?.authInfo) {
// options.extra.authInfo.token などを使用
}
}
HTTP ベースのトランスポート(SSE または HTTP)を使用する場合、エリシテーションはセッション認識であることに注意してください。これは、複数のクライアントが同じサーバーに接続されているとき、エリシテーションのリクエストが、ツール実行を開始した正しいクライアントセッションにルーティングされることを意味します。
ElicitResult
型:
type ElicitResult = {
action: 'accept' | 'decline' | 'cancel';
content?: any; // action が 'accept' の場合にのみ存在
}
認証コンテキスト
HTTP ベースのトランスポートを使用する場合、ツールは options.extra
を通じてリクエストのメタデータにアクセスできます:
execute: async ({ context }, options) => {
if (!options.extra?.authInfo?.token) {
return "Authentication required";
}
// 認証トークンを使用
const response = await fetch('/api/data', {
headers: { Authorization: `Bearer ${options.extra.authInfo.token}` },
signal: options.extra.signal,
});
return response.json();
}
extra
オブジェクトには次が含まれます:
authInfo
: 認証情報(サーバーのミドルウェアにより提供される場合)sessionId
: セッション IDsignal
: キャンセル用の AbortSignalsendNotification
/sendRequest
: MCP プロトコル関数
注: 認証を有効にするには、
server.startHTTP()
を呼び出す前にreq.auth
を設定するミドルウェアを HTTP サーバーに用意する必要があります。例:httpServer.createServer((req, res) => { // 認証ミドルウェアを追加 req.auth = validateAuthToken(req.headers.authorization); // その後 MCP サーバーに渡す await server.startHTTP({ url, httpPath, req, res }); });
関連情報
- Mastra で MCP サーバーに接続する方法については、MCPClient のドキュメントをご参照ください。
- Model Context Protocol の詳細については、@modelcontextprotocol/sdk のドキュメント をご参照ください。