メインコンテンツまでスキップ
Laravel MCP
Laravel 13.x · 日本語ドキュメントhttps://laravel.com/php/docs/13.x/mcp

Laravel MCP

Introduction​

Laravel MCP は、AI クライアントが Model Context Protocol を通じて Laravel アプリケーションと対話するためのシンプルかつエレガントな方法を提供します。サーバー、ツール、リソース、プロンプトを定義するための表現力豊かで Fluent なインターフェイスを提供し、AI を活用したアプリケーションとの対話を可能にします。

Installation​

まず、Composer パッケージ マネージャーを使用して Laravel MCP をプロジェクトにインストールします。

composer require laravel/mcp

Publishing Routes​

Laravel MCP をインストールした後、vendor:publish Artisan コマンドを実行して、MCP サーバーを定義する routes/ai.php ファイルを公開します。

php artisan vendor:publish --tag=ai-routes

このコマンドは、アプリケーションの routes ディレクトリに routes/ai.php ファイルを作成します。このファイルは、MCP サーバーの登録に使用されます。

Creating Servers​

make:mcp-server Artisan コマンドを使用して MCP サーバーを作成できます。サーバーは、ツール、リソース、プロンプトなどの MCP 機能を AI クライアントに公開する中央の通信ポイントとして機能します。

php artisan make:mcp-server WeatherServer

このコマンドは、app/Mcp/Servers ディレクトリに新しいサーバー クラスを作成します。生成されたサーバークラスは、Laravel MCP の基本 Laravel\Mcp\Server クラスを拡張し、サーバーを構成し、ツール、リソース、プロンプトを登録するための属性とプロパティを提供します。

<?php

namespace App\Mcp\Servers;

use Laravel\Mcp\Server\Attributes\Instructions;
use Laravel\Mcp\Server\Attributes\Name;
use Laravel\Mcp\Server\Attributes\Version;
use Laravel\Mcp\Server;

#[Name('Weather Server')]
#[Version('1.0.0')]
#[Instructions('This server provides weather information and forecasts.')]
class WeatherServer extends Server
{
/**
* The tools registered with this MCP server.
*
* @var array<int, class-string<\Laravel\Mcp\Server\Tool>>
*/
protected array $tools = [
// GetCurrentWeatherTool::class,
];

/**
* The resources registered with this MCP server.
*
* @var array<int, class-string<\Laravel\Mcp\Server\Resource>>
*/
protected array $resources = [
// WeatherGuidelinesResource::class,
];

/**
* The prompts registered with this MCP server.
*
* @var array<int, class-string<\Laravel\Mcp\Server\Prompt>>
*/
protected array $prompts = [
// DescribeWeatherPrompt::class,
];
}

Server Registration​

サーバーを作成したら、それを routes/ai.php ファイルに登録してアクセスできるようにする必要があります。 Laravel MCP は、サーバーを登録するための 2 つの方法を提供します。HTTP アクセス可能なサーバー用の web と、コマンドライン サーバー用の local です。

Web Servers​

Web サーバーは最も一般的なタイプのサーバーであり、HTTP POST リクエスト経由でアクセスできるため、リモート AI クライアントまたは Web ベースの統合に最適です。 web メソッドを使用して Web サーバーを登録します。

use App\Mcp\Servers\WeatherServer;
use Laravel\Mcp\Facades\Mcp;

Mcp::web('/mcp/weather', WeatherServer::class);

通常のルートと同様に、ミドルウェアを適用して Web サーバーを保護できます。

Mcp::web('/mcp/weather', WeatherServer::class)
->middleware(['throttle:mcp']);

Local Servers​

ローカル サーバーは Artisan コマンドとして実行され、Laravel Boost のようなローカル AI アシスタント統合の構築に最適です。 local メソッドを使用してローカル サーバーを登録します。

use App\Mcp\Servers\WeatherServer;
use Laravel\Mcp\Facades\Mcp;

Mcp::local('weather', WeatherServer::class);

一度登録すると、通常は mcp:start Artisan コマンドを自分で手動で実行する必要はありません。代わりに、MCP クライアント (AI エージェント) がサーバーを起動するように構成するか、MCP Inspector を使用します。

Cache Hints​

Laravel MCP は、サーバーの検出、プリミティブの一覧表示、リソースの読み取りなど、キャッシュされる可能性があるレスポンスにキャッシュヒントを付与します。デフォルトでは、これらのレスポンスは有効期間 0 ミリ秒のプライベートとして扱われます。

Cacheable 属性を使用して、サーバーのデフォルトのキャッシュヒントをカスタマイズできます。

use Laravel\Mcp\Enums\CacheScope;
use Laravel\Mcp\Server\Attributes\Cacheable;

#[Cacheable(ttlMs: 60_000, scope: CacheScope::Public)]
class WeatherServer extends Server
{
/**
* Get the cache hints for individual MCP methods.
*
* @return array<string, \Laravel\Mcp\Server\Attributes\Cacheable>
*/
protected function cacheHints(): array
{
return [
'tools/list' => new Cacheable(ttlMs: 30_000, scope: CacheScope::Public),
];
}
}

CacheScope::Private スコープでは、キャッシュされたレスポンスを同じ認可コンテキスト内に制限します。一方、CacheScope::Public を指定すると、ユーザー間でレスポンスを共有できます。キャッシュヒントはあくまで参考情報であり、レスポンスを実際にキャッシュするかどうかは MCP クライアントまたはホストが決定します。cacheHints が返すメソッド固有のヒントは、サーバーの Cacheable 属性よりも優先されます。

リソースクラスに Cacheable 属性を付与すると、個別のリソースについてサーバーのキャッシュヒントを上書きできます。

#[Cacheable(ttlMs: 300_000, scope: CacheScope::Public)]
class WeatherGuidelinesResource extends Resource
{
// ...
}

リソースの Cacheable 属性は、メソッド固有のヒントとサーバーのデフォルトヒントの両方よりも優先されます。

Tools​

ツールを使用すると、サーバーは AI クライアントが呼び出すことができる機能を公開できます。これらにより、言語モデルがアクションを実行したり、コードを実行したり、外部システムと対話したりできるようになります。

<?php

namespace App\Mcp\Tools;

use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Attributes\Description;
use Laravel\Mcp\Server\Tool;

#[Description('Fetches the current weather forecast for a specified location.')]
class CurrentWeatherTool extends Tool
{
/**
* Handle the tool request.
*/
public function handle(Request $request): Response
{
$location = $request->get('location');

// Get weather...

return Response::text('The weather is...');
}

/**
* Get the tool's input schema.
*
* @return array<string, \Illuminate\JsonSchema\Types\Type>
*/
public function schema(JsonSchema $schema): array
{
return [
'location' => $schema->string()
->description('The location to get the weather for.')
->required(),
];
}
}

Creating Tools​

ツールを作成するには、make:mcp-tool Artisan コマンドを実行します。

php artisan make:mcp-tool CurrentWeatherTool

ツールを作成したら、それをサーバーの $tools プロパティに登録します。

<?php

namespace App\Mcp\Servers;

use App\Mcp\Tools\CurrentWeatherTool;
use Laravel\Mcp\Server;

class WeatherServer extends Server
{
/**
* The tools registered with this MCP server.
*
* @var array<int, class-string<\Laravel\Mcp\Server\Tool>>
*/
protected array $tools = [
CurrentWeatherTool::class,
];
}

Searchable Tool Catalogs​

多数のツールを持つサーバーでは、すべてのツールを AI クライアントに公開する代わりに、一部のツールを検索可能なカタログに配置できます。検索可能なカタログでは、2つのツールを公開します。search_tools はツール名、説明、入力スキーマを条件にカタログを検索し、execute_tools は検索結果として返された1つ以上のツールを呼び出します。

検索可能なカタログを作成するには、サーバーの $tools プロパティで ToolSearch クラスを配列キーとして使用します。

<?php

namespace App\Mcp\Servers;

use App\Mcp\Tools\CurrentWeatherTool;
use App\Mcp\Tools\HistoricalWeatherTool;
use App\Mcp\Tools\WeatherAlertsTool;
use Laravel\Mcp\Server;
use Laravel\Mcp\Server\Tools\ToolSearch;

class WeatherServer extends Server
{
/**
* The tools registered with this MCP server.
*
* @var array<int|string, \Laravel\Mcp\Server\Tool|class-string<\Laravel\Mcp\Server\Tool>|array<int, \Laravel\Mcp\Server\Tool|class-string<\Laravel\Mcp\Server\Tool>>>
*/
protected array $tools = [
CurrentWeatherTool::class,

ToolSearch::class => [
HistoricalWeatherTool::class,
WeatherAlertsTool::class,
],
];
}

この例では、CurrentWeatherTool を直接公開し、過去の天気と気象警報のツールは検索可能なカタログから利用できるようにしています。カタログのツールを検索または実行する場合も、条件付きのツール登録は引き続き適用されます。

1回の execute_tools 呼び出しで実行できるツールの最大数とレスポンスの最大サイズは、mcp.tool_search.max_tool_calls および mcp.tool_search.max_output_bytes の設定値で制御します。

Tool Name, Title, and Description​

デフォルトでは、ツールの名前とタイトルはクラス名から派生します。たとえば、CurrentWeatherTool の名前は current-weather、タイトルは Current Weather Tool になります。これらの値は、Name 属性と Title 属性を使用してカスタマイズできます。

use Laravel\Mcp\Server\Attributes\Name;
use Laravel\Mcp\Server\Attributes\Title;

#[Name('get-optimistic-weather')]
#[Title('Get Optimistic Weather Forecast')]
class CurrentWeatherTool extends Tool
{
// ...
}

ツールの説明は自動生成されません。常に Description 属性を使用して意味のある説明を提供する必要があります。

use Laravel\Mcp\Server\Attributes\Description;

#[Description('Fetches the current weather forecast for a specified location.')]
class CurrentWeatherTool extends Tool
{
//
}

説明はツールのメタデータの重要な要素です。AIモデルがツールをいつ、どのように効果的に使うかを理解する助けになります。

Tool Input Schemas​

ツールは入力スキーマを定義して、AI クライアントから受け入れる引数を指定できます。 Laravel の Illuminate\Contracts\JsonSchema\JsonSchema ビルダを使用して、ツールの入力要件を定義します。

<?php

namespace App\Mcp\Tools;

use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Mcp\Server\Tool;

class CurrentWeatherTool extends Tool
{
/**
* Get the tool's input schema.
*
* @return array<string, \Illuminate\JsonSchema\Types\Type>
*/
public function schema(JsonSchema $schema): array
{
return [
'location' => $schema->string()
->description('The location to get the weather for.')
->required(),

'units' => $schema->string()
->enum(['celsius', 'fahrenheit'])
->description('The temperature units to use.')
->default('celsius'),
];
}
}

Tool Output Schemas​

ツールは output schemas を定義して、応答の構造を指定できます。これにより、解析可能なツール結果を必要とする AI クライアントとの統合が向上します。outputSchema メソッドを使用して、ツールの出力構造を定義してください。

<?php

namespace App\Mcp\Tools;

use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Mcp\Server\Tool;

class CurrentWeatherTool extends Tool
{
/**
* Get the tool's output schema.
*
* @return array<string, \Illuminate\JsonSchema\Types\Type>
*/
public function outputSchema(JsonSchema $schema): array
{
return [
'temperature' => $schema->number()
->description('Temperature in Celsius')
->required(),

'conditions' => $schema->string()
->description('Weather conditions')
->required(),

'humidity' => $schema->integer()
->description('Humidity percentage')
->required(),
];
}
}

Validating Tool Arguments​

JSON スキーマ定義はツール引数の基本構造を提供しますが、より複雑な検証ルールを強制することもできます。

Laravel MCP は、Laravel の validation features とシームレスに統合されます。ツールの handle メソッド内で受信ツール引数を検証できます。

<?php

namespace App\Mcp\Tools;

use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Tool;

class CurrentWeatherTool extends Tool
{
/**
* Handle the tool request.
*/
public function handle(Request $request): Response
{
$validated = $request->validate([
'location' => 'required|string|max:100',
'units' => 'in:celsius,fahrenheit',
]);

// Fetch weather data using the validated arguments...
}
}

バリデーションに失敗すると、AI クライアントは提供されたエラーメッセージに基づいて動作します。そのため、明確で対応につなげやすいエラーメッセージを提供することが重要です。

$validated = $request->validate([
'location' => ['required','string','max:100'],
'units' => 'in:celsius,fahrenheit',
],[
'location.required' => 'You must specify a location to get the weather for. For example, "New York City" or "Tokyo".',
'units.in' => 'You must specify either "celsius" or "fahrenheit" for the units.',
]);

Tool Dependency Injection​

Laravel service container は、すべてのツールを解決するために使用されます。その結果、ツールのコンストラクターで必要な依存関係をタイプヒントで指定できるようになります。宣言された依存関係は自動的に解決され、ツール インスタンスに注入されます。

<?php

namespace App\Mcp\Tools;

use App\Repositories\WeatherRepository;
use Laravel\Mcp\Server\Tool;

class CurrentWeatherTool extends Tool
{
/**
* Create a new tool instance.
*/
public function __construct(
protected WeatherRepository $weather,
) {}

// ...
}

コンストラクターの注入に加えて、ツールの handle() メソッドでタイプヒントの依存関係を指定することもできます。サービスコンテナーは、メソッドが呼び出されるときに依存関係を自動的に解決して注入します。

<?php

namespace App\Mcp\Tools;

use App\Repositories\WeatherRepository;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Tool;

class CurrentWeatherTool extends Tool
{
/**
* Handle the tool request.
*/
public function handle(Request $request, WeatherRepository $weather): Response
{
$location = $request->get('location');

$forecast = $weather->getForecastFor($location);

// ...
}
}

Tool Annotations​

annotations を使用してツールを拡張し、AI クライアントに追加のメタデータを提供できます。これらの注釈は、AI モデルがツールの動作と機能を理解するのに役立ちます。注釈は属性を介してツールに追加されます。

<?php

namespace App\Mcp\Tools;

use Laravel\Mcp\Server\Tools\Annotations\IsIdempotent;
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
use Laravel\Mcp\Server\Tool;

#[IsIdempotent]
#[IsReadOnly]
class CurrentWeatherTool extends Tool
{
//
}

利用できる注釈は次のとおりです:

注釈タイプ説明
#[IsReadOnly]ブール値ツールが環境を変更しないことを示します。
#[IsDestructive]ブール値ツールが破壊的な更新を実行する可能性があることを示します (読み取り専用でない場合にのみ意味があります)。
#[IsIdempotent]ブール値同じ引数で繰り返し呼び出しても追加の効果がないことを示します (読み取り専用でない場合)。
#[IsOpenWorld]ブール値ツールが外部エンティティと対話する可能性があることを示します。

注釈値は、ブール引数を使用して明示的に設定できます。

use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;
use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;
use Laravel\Mcp\Server\Tools\Annotations\IsIdempotent;
use Laravel\Mcp\Server\Tool;

#[IsReadOnly(true)]
#[IsDestructive(false)]
#[IsOpenWorld(false)]
#[IsIdempotent(true)]
class CurrentWeatherTool extends Tool
{
//
}

Conditional Tool Registration​

ツール クラスに shouldRegister メソッドを実装することで、実行時に条件付きでツールを登録できます。この方法を使用すると、アプリケーションの状態、構成、またはリクエスト パラメーターに基づいてツールを使用可能にするかどうかを決定できます。

<?php

namespace App\Mcp\Tools;

use Laravel\Mcp\Request;
use Laravel\Mcp\Server\Tool;

class CurrentWeatherTool extends Tool
{
/**
* Determine if the tool should be registered.
*/
public function shouldRegister(Request $request): bool
{
return $request?->user()?->subscribed() ?? false;
}
}

ツールの shouldRegister メソッドが false を返した場合、そのツールは使用可能なツールのリストに表示されず、AI クライアントから呼び出すことはできません。

Tool Responses​

ツールは Laravel\Mcp\Response のインスタンスを返す必要があります。 Response クラスには、さまざまな種類の応答を作成するための便利なメソッドがいくつか用意されています。

単純なテキスト応答の場合は、text メソッドを使用します。

use Laravel\Mcp\Request;
use Laravel\Mcp\Response;

/**
* Handle the tool request.
*/
public function handle(Request $request): Response
{
// ...

return Response::text('Weather Summary: Sunny, 72°F');
}

ツールの実行中にエラーが発生したことを示すには、error メソッドを使用します。

return Response::error('Unable to fetch weather data. Please try again.');

画像または音声コンテンツを返すには、image メソッドと audio メソッドを使用します。

return Response::image(file_get_contents(storage_path('weather/radar.png')), 'image/png');

return Response::audio(file_get_contents(storage_path('weather/alert.mp3')), 'audio/mp3');

fromStorage メソッドを使用して、Laravel ファイルシステム ディスクから画像と音声のコンテンツを直接ロードすることもできます。 MIME タイプはファイルから自動的に検出されます。

return Response::fromStorage('weather/radar.png');

必要に応じて、特定のディスクを指定するか、MIME タイプをオーバーライドできます。

return Response::fromStorage('weather/radar.png', disk: 's3');

return Response::fromStorage('weather/radar.png', mimeType: 'image/webp');

Multiple Content Responses​

ツールは、Response インスタンスの配列を返すことで、複数のコンテンツを返すことができます。

use Laravel\Mcp\Request;
use Laravel\Mcp\Response;

/**
* Handle the tool request.
*
* @return array<int, \Laravel\Mcp\Response>
*/
public function handle(Request $request): array
{
// ...

return [
Response::text('Weather Summary: Sunny, 72°F'),
Response::text("**Detailed Forecast**\n- Morning: 65°F\n- Afternoon: 78°F\n- Evening: 70°F")
];
}

Structured Responses​

ツールは、structured メソッドを使用して structured content を返せます。これにより、JSON エンコードされたテキスト表現との下位互換性を維持しながら、AI クライアントに解析可能なデータを提供できます。

return Response::structured([
'temperature' => 22.5,
'conditions' => 'Partly cloudy',
'humidity' => 65,
]);

構造化コンテンツと一緒にカスタム テキストを提供する必要がある場合は、レスポンス ファクトリで withStructuredContent メソッドを使用します。

return Response::make(
Response::text('Weather is 22.5°C and sunny')
)->withStructuredContent([
'temperature' => 22.5,
'conditions' => 'Sunny',
]);

Streaming Responses​

長時間実行される操作またはリアルタイム データ ストリーミングの場合、ツールは handle メソッドから generator を返すことができます。これにより、最終応答の前に中間更新をクライアントに送信できるようになります。

<?php

namespace App\Mcp\Tools;

use Generator;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Tool;

class CurrentWeatherTool extends Tool
{
/**
* Handle the tool request.
*
* @return \Generator<int, \Laravel\Mcp\Response>
*/
public function handle(Request $request): Generator
{
$locations = $request->array('locations');

foreach ($locations as $index => $location) {
yield Response::notification('processing/progress', [
'current' => $index + 1,
'total' => count($locations),
'location' => $location,
]);

yield Response::text($this->forecastFor($location));
}
}
}

Web ベースのサーバーを使用する場合、ストリーミング応答は自動的に SSE (Server-Sent Events) ストリームを開き、生成された各メッセージをイベントとしてクライアントに送信します。

標準の MCP 進捗通知(notifications/progress)を送信するには、ジェネレータから Response::progress を yield します。現在の進捗値に加えて、任意で total と message 引数を指定できます。

<?php

namespace App\Mcp\Tools;

use Generator;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Tool;

class ImportFilesTool extends Tool
{
/**
* Handle the tool request.
*
* @return \Generator<int, \Laravel\Mcp\Response>
*/
public function handle(Request $request): Generator
{
$files = $request->array('files');

foreach ($files as $index => $file) {
yield Response::progress(
$index + 1,
total: count($files),
message: "Importing {$file}...",
);

$this->import($file);
}

yield Response::text('All files imported.');
}
}

サーバーは各進捗通知に、リクエストの _meta.progressToken を自動的に付与します。クライアントがリクエストに progressToken を含めなかった場合、進捗通知は送信されません。

Prompts​

Prompts を使用すると、AI クライアントが言語モデルと対話するために利用できる再利用可能なプロンプトテンプレートをサーバーで共有できます。一般的なクエリや対話を構造化するための標準的な方法を提供します。

Creating Prompts​

プロンプトを作成するには、make:mcp-prompt Artisan コマンドを実行します。

php artisan make:mcp-prompt DescribeWeatherPrompt

プロンプトを作成したら、それをサーバーの $prompts プロパティに登録します。

<?php

namespace App\Mcp\Servers;

use App\Mcp\Prompts\DescribeWeatherPrompt;
use Laravel\Mcp\Server;

class WeatherServer extends Server
{
/**
* The prompts registered with this MCP server.
*
* @var array<int, class-string<\Laravel\Mcp\Server\Prompt>>
*/
protected array $prompts = [
DescribeWeatherPrompt::class,
];
}

Prompt Name, Title, and Description​

デフォルトでは、プロンプトの名前とタイトルはクラス名から派生します。たとえば、DescribeWeatherPrompt の名前は describe-weather、タイトルは Describe Weather Prompt になります。これらの値は、Name 属性と Title 属性を使用してカスタマイズできます。

use Laravel\Mcp\Server\Attributes\Name;
use Laravel\Mcp\Server\Attributes\Title;

#[Name('weather-assistant')]
#[Title('Weather Assistant Prompt')]
class DescribeWeatherPrompt extends Prompt
{
// ...
}

プロンプトの説明は自動的には生成されません。常に Description 属性を使用して意味のある説明を提供する必要があります。

use Laravel\Mcp\Server\Attributes\Description;

#[Description('Generates a natural-language explanation of the weather for a given location.')]
class DescribeWeatherPrompt extends Prompt
{
//
}

説明はプロンプトのメタデータの重要な要素です。AI モデルが、いつ、どのようにプロンプトを活用すればよいかを理解するのに役立ちます。

Prompt Arguments​

プロンプトでは、AI クライアントが特定の値を使用してプロンプト テンプレートをカスタマイズできるようにする引数を定義できます。 arguments メソッドを使用して、プロンプトが受け入れる引数を定義します。

<?php

namespace App\Mcp\Prompts;

use Laravel\Mcp\Server\Prompt;
use Laravel\Mcp\Server\Prompts\Argument;

class DescribeWeatherPrompt extends Prompt
{
/**
* Get the prompt's arguments.
*
* @return array<int, \Laravel\Mcp\Server\Prompts\Argument>
*/
public function arguments(): array
{
return [
new Argument(
name: 'tone',
description: 'The tone to use in the weather description (e.g., formal, casual, humorous).',
required: true,
),
];
}
}

Validating Prompt Arguments​

プロンプト引数はその定義に基づいて自動的に検証されますが、より複雑な検証ルールを適用することもできます。

Laravel MCP は、Laravel の validation features とシームレスに統合されます。プロンプトの handle メソッド内で受信プロンプト引数を検証できます。

<?php

namespace App\Mcp\Prompts;

use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Prompt;

class DescribeWeatherPrompt extends Prompt
{
/**
* Handle the prompt request.
*/
public function handle(Request $request): Response
{
$validated = $request->validate([
'tone' => 'required|string|max:50',
]);

$tone = $validated['tone'];

// Generate the prompt response using the given tone...
}
}

バリデーションに失敗すると、AIクライアントは提示されたエラーメッセージに基づいて動作します。そのため、明確で具体的な対応方法が分かるエラーメッセージを提示することが重要です。

$validated = $request->validate([
'tone' => ['required','string','max:50'],
],[
'tone.*' => 'You must specify a tone for the weather description. Examples include "formal", "casual", or "humorous".',
]);

Prompt Dependency Injection​

Laravel service container は、すべてのプロンプトを解決するために使用されます。その結果、プロンプトのコンストラクターで必要な依存関係をタイプヒントで指定できるようになります。宣言された依存関係は自動的に解決され、プロンプト インスタンスに注入されます。

<?php

namespace App\Mcp\Prompts;

use App\Repositories\WeatherRepository;
use Laravel\Mcp\Server\Prompt;

class DescribeWeatherPrompt extends Prompt
{
/**
* Create a new prompt instance.
*/
public function __construct(
protected WeatherRepository $weather,
) {}

//
}

コンストラクターの注入に加えて、プロンプトの handle メソッドでタイプヒントの依存関係を使用することもできます。サービスコンテナーは、メソッドが呼び出されるときに依存関係を自動的に解決して注入します。

<?php

namespace App\Mcp\Prompts;

use App\Repositories\WeatherRepository;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Prompt;

class DescribeWeatherPrompt extends Prompt
{
/**
* Handle the prompt request.
*/
public function handle(Request $request, WeatherRepository $weather): Response
{
$isAvailable = $weather->isServiceAvailable();

// ...
}
}

Conditional Prompt Registration​

プロンプト クラスに shouldRegister メソッドを実装することで、実行時にプロンプトを条件付きで登録できます。この方法を使用すると、アプリケーションの状態、構成、または要求パラメーターに基づいてプロンプトを使用可能にするかどうかを決定できます。

<?php

namespace App\Mcp\Prompts;

use Laravel\Mcp\Request;
use Laravel\Mcp\Server\Prompt;

class CurrentWeatherPrompt extends Prompt
{
/**
* Determine if the prompt should be registered.
*/
public function shouldRegister(Request $request): bool
{
return $request?->user()?->subscribed() ?? false;
}
}

プロンプトの shouldRegister メソッドが false を返す場合、そのプロンプトは使用可能なプロンプトのリストに表示されず、AI クライアントによって呼び出すことはできません。

Prompt Responses​

プロンプトは、単一の Laravel\Mcp\Response または Laravel\Mcp\Response インスタンスを要素とする iterable を返せます。これらの応答は、AI クライアントに送信されるコンテンツをカプセル化します。

<?php

namespace App\Mcp\Prompts;

use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Prompt;

class DescribeWeatherPrompt extends Prompt
{
/**
* Handle the prompt request.
*
* @return array<int, \Laravel\Mcp\Response>
*/
public function handle(Request $request): array
{
$tone = $request->string('tone');

$systemMessage = "You are a helpful weather assistant. Please provide a weather description in a {$tone} tone.";

$userMessage = "What is the current weather like in New York City?";

return [
Response::text($systemMessage)->asAssistant(),
Response::text($userMessage),
];
}
}

asAssistant() メソッドを使用すると、通常のメッセージがユーザー入力として扱われる一方で、応答メッセージが AI アシスタントから送信されたものとして扱われる必要があることを示すことができます。

Resources​

Resources を使用すると、サーバーが AI クライアントに対して、言語モデルとの対話時にコンテキストとして読み取り、利用できるデータやコンテンツを公開できるようになります。ドキュメントや設定、AI の応答に役立つあらゆるデータなど、静的または動的な情報を共有できます。

Creating Resources​

リソースを作成するには、make:mcp-resource Artisan コマンドを実行します。

php artisan make:mcp-resource WeatherGuidelinesResource

リソースを作成したら、それをサーバーの $resources プロパティに登録します。

<?php

namespace App\Mcp\Servers;

use App\Mcp\Resources\WeatherGuidelinesResource;
use Laravel\Mcp\Server;

class WeatherServer extends Server
{
/**
* The resources registered with this MCP server.
*
* @var array<int, class-string<\Laravel\Mcp\Server\Resource>>
*/
protected array $resources = [
WeatherGuidelinesResource::class,
];
}

Resource Name, Title, and Description​

デフォルトでは、リソースの名前とタイトルはクラス名から派生します。たとえば、WeatherGuidelinesResource の名前は weather-guidelines、タイトルは Weather Guidelines Resource になります。これらの値は、Name 属性と Title 属性を使用してカスタマイズできます。

use Laravel\Mcp\Server\Attributes\Name;
use Laravel\Mcp\Server\Attributes\Title;

#[Name('weather-api-docs')]
#[Title('Weather API Documentation')]
class WeatherGuidelinesResource extends Resource
{
// ...
}

リソースの説明は自動的には生成されません。常に Description 属性を使用して意味のある説明を提供する必要があります。

use Laravel\Mcp\Server\Attributes\Description;

#[Description('Comprehensive guidelines for using the Weather API.')]
class WeatherGuidelinesResource extends Resource
{
//
}

説明はリソースのメタデータの重要な要素です。AIモデルがリソースをいつ、どのように使えば効果的かを理解するうえで役立ちます。

Resource Templates​

Resource templates を使用すると、サーバーで変数を含む URI パターンに一致する動的リソースを公開できます。リソースごとに静的 URI を定義する代わりに、テンプレートパターンに基づいて複数の URI を処理する単一のリソースを作成できます。

Creating Resource Templates​

リソース テンプレートを作成するには、リソース クラスに HasUriTemplate インターフェイスを実装し、UriTemplate インスタンスを返す uriTemplate メソッドを定義します。

<?php

namespace App\Mcp\Resources;

use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Attributes\Description;
use Laravel\Mcp\Server\Attributes\MimeType;
use Laravel\Mcp\Server\Contracts\HasUriTemplate;
use Laravel\Mcp\Server\Resource;
use Laravel\Mcp\Support\UriTemplate;

#[Description('Access user files by ID')]
#[MimeType('text/plain')]
class UserFileResource extends Resource implements HasUriTemplate
{
/**
* Get the URI template for this resource.
*/
public function uriTemplate(): UriTemplate
{
return new UriTemplate('file://users/{userId}/files/{fileId}');
}

/**
* Handle the resource request.
*/
public function handle(Request $request): Response
{
$userId = $request->get('userId');
$fileId = $request->get('fileId');

// Fetch and return the file content...

return Response::text($content);
}
}

リソースが HasUriTemplate インターフェイスを実装すると、静的リソースではなくリソース テンプレートとして登録されます。 AI クライアントは、テンプレート パターンに一致する URI を使用してリソースをリクエストできるようになり、URI からの変数が自動的に抽出され、リソースの handle メソッドで使用できるようになります。

URI Template Syntax​

URI テンプレートは、中括弧で囲まれたプレースホルダーを使用して、URI 内の変数セグメントを定義します。

new UriTemplate('file://users/{userId}');
new UriTemplate('file://users/{userId}/files/{fileId}');
new UriTemplate('https://api.example.com/{version}/{resource}/{id}');

Accessing Template Variables​

URI がリソース テンプレートと一致すると、抽出された変数は自動的にリクエストにマージされ、get メソッドを使用してアクセスできるようになります。

<?php

namespace App\Mcp\Resources;

use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Contracts\HasUriTemplate;
use Laravel\Mcp\Server\Resource;
use Laravel\Mcp\Support\UriTemplate;

class UserProfileResource extends Resource implements HasUriTemplate
{
public function uriTemplate(): UriTemplate
{
return new UriTemplate('file://users/{userId}/profile');
}

public function handle(Request $request): Response
{
// Access the extracted variable
$userId = $request->get('userId');

// Access the full URI if needed
$uri = $request->uri();

// Fetch user profile...

return Response::text("Profile for user {$userId}");
}
}

Request オブジェクトは、抽出された変数と要求された元の URI の両方を提供し、リソース要求を処理するための完全なコンテキストを提供します。

Resource URI and MIME Type​

各リソースは一意の URI によって識別され、AI クライアントがリソースの形式を理解するのに役立つ MIME タイプが関連付けられています。

デフォルトでは、リソースの URI はリソース名に基づいて生成されるため、WeatherGuidelinesResource の URI は weather://resources/weather-guidelines になります。デフォルトの MIME タイプは text/plain です。

これらの値は、Uri 属性と MimeType 属性を使用してカスタマイズできます。

<?php

namespace App\Mcp\Resources;

use Laravel\Mcp\Server\Attributes\MimeType;
use Laravel\Mcp\Server\Attributes\Uri;
use Laravel\Mcp\Server\Resource;

#[Uri('weather://resources/guidelines')]
#[MimeType('application/pdf')]
class WeatherGuidelinesResource extends Resource
{
}

URI と MIME タイプは、AI クライアントがリソース コンテンツを適切に処理および解釈する方法を決定するのに役立ちます。

Resource Request​

ツールやプロンプトとは異なり、リソースは入力スキーマや引数を定義できません。ただし、リソースの handle メソッド内で request オブジェクトを扱うことはできます。

<?php

namespace App\Mcp\Resources;

use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Resource;

class WeatherGuidelinesResource extends Resource
{
/**
* Handle the resource request.
*/
public function handle(Request $request): Response
{
// ...
}
}

Resource Dependency Injection​

Laravel service container は、すべてのリソースを解決するために使用されます。その結果、リソースがコンストラクターで必要とする依存関係をタイプヒントで指定できるようになります。宣言された依存関係は自動的に解決され、リソース インスタンスに注入されます。

<?php

namespace App\Mcp\Resources;

use App\Repositories\WeatherRepository;
use Laravel\Mcp\Server\Resource;

class WeatherGuidelinesResource extends Resource
{
/**
* Create a new resource instance.
*/
public function __construct(
protected WeatherRepository $weather,
) {}

// ...
}

コンストラクターのインジェクションに加えて、リソースの handle メソッドでタイプヒントの依存関係を指定することもできます。サービスコンテナーは、メソッドが呼び出されるときに依存関係を自動的に解決して注入します。

<?php

namespace App\Mcp\Resources;

use App\Repositories\WeatherRepository;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Resource;

class WeatherGuidelinesResource extends Resource
{
/**
* Handle the resource request.
*/
public function handle(WeatherRepository $weather): Response
{
$guidelines = $weather->guidelines();

return Response::text($guidelines);
}
}

Resource Annotations​

annotations を使用してリソースを拡張し、AI クライアントに追加のメタデータを提供できます。注釈は属性を介してリソースに追加されます。

<?php

namespace App\Mcp\Resources;

use Laravel\Mcp\Enums\Role;
use Laravel\Mcp\Server\Annotations\Audience;
use Laravel\Mcp\Server\Annotations\LastModified;
use Laravel\Mcp\Server\Annotations\Priority;
use Laravel\Mcp\Server\Resource;

#[Audience(Role::User)]
#[LastModified('2025-01-12T15:00:58Z')]
#[Priority(0.9)]
class UserDashboardResource extends Resource
{
//
}

利用できる注釈には、次のものがあります:

注釈タイプ説明
#[Audience]Role または配列対象読者 (Role::User、Role::Assistant、または両方) を指定します。
#[Priority]フロートリソースの重要性を示す 0.0 ~ 1.0 の数値スコア。
#[LastModified]文字列リソースが最後に更新された時間を示す ISO 8601 タイムスタンプ。

Conditional Resource Registration​

リソース クラスに shouldRegister メソッドを実装することで、実行時に条件付きでリソースを登録できます。このメソッドを使用すると、アプリケーションの状態、構成、またはリクエスト パラメーターに基づいてリソースを利用可能にするかどうかを決定できます。

<?php

namespace App\Mcp\Resources;

use Laravel\Mcp\Request;
use Laravel\Mcp\Server\Resource;

class WeatherGuidelinesResource extends Resource
{
/**
* Determine if the resource should be registered.
*/
public function shouldRegister(Request $request): bool
{
return $request?->user()?->subscribed() ?? false;
}
}

リソースの shouldRegister メソッドが false を返すと、そのリソースは使用可能なリソースのリストに表示されず、AI クライアントはアクセスできません。

Resource Responses​

リソースは Laravel\Mcp\Response のインスタンスを返す必要があります。 Response クラスには、さまざまな種類の応答を作成するための便利なメソッドがいくつか用意されています。

単純なテキスト コンテンツの場合は、text メソッドを使用します。

use Laravel\Mcp\Request;
use Laravel\Mcp\Response;

/**
* Handle the resource request.
*/
public function handle(Request $request): Response
{
// ...

return Response::text($weatherData);
}

リソース リンクを返すには、resourceLink メソッドを使用して、URI と名前を指定します。埋め込みリソースとは異なり、リソース リンクは、AI クライアントが独自にフェッチする URI ポインターを返します。

return Response::resourceLink(
uri: 'file:///data/report.json',
name: 'monthly-report',
mimeType: 'application/json',
);

登録されたリソース クラスまたはインスタンスを渡すこともできます。これにより、リソースの URI、名前、タイトル、説明、および MIME タイプが自動的に継承されます。

return Response::resourceLink(new WeatherForecastResource);

Blob Responses​

BLOB コンテンツを返すには、blob メソッドを使用して、BLOB コンテンツを指定します。

return Response::blob(file_get_contents(storage_path('weather/radar.png')));

BLOB コンテンツを返すとき、MIME タイプはリソースに構成されている MIME タイプによって決まります。

<?php

namespace App\Mcp\Resources;

use Laravel\Mcp\Server\Attributes\MimeType;
use Laravel\Mcp\Server\Resource;

#[MimeType('image/png')]
class WeatherGuidelinesResource extends Resource
{
//
}

Error Responses​

リソースの取得中にエラーが発生したことを示すには、error() メソッドを使用します。

return Response::error('Unable to fetch weather data for the specified location.');

Apps​

Laravel MCP は、サポートされているホストのサンドボックス iframe 内でツールがインタラクティブな HTML アプリケーションをレンダリングできるようにするモデル コンテキスト プロトコルの拡張機能である MCP Apps をサポートしています。これにより、プレーン テキストの応答を超えたダッシュボード、フォーム、ビジュアライゼーション、その他の豊富なエクスペリエンスを構築できます。

MCP アプリは、連携して動作する 2 つの部分で構成されます。

  • アプリケーションの自己完結型 HTML を返す アプリ リソース。
  • #[RendersApp] 属性を使用してアプリ リソースにリンクされる ツール。ツールが呼び出されると、ホストはリンクされたリソースをフェッチしてレンダリングします。

Creating App Resources​

make:mcp-app-resource Artisan コマンドを使用してアプリ リソースを作成できます。

php artisan make:mcp-app-resource WeatherDashboardApp

このコマンドは、app/Mcp/Resources の PHP クラスと resources/views/mcp のBlade ビューの 2 つのファイルを作成します。ビュー名はクラス名から自動的に推測されます。たとえば、WeatherDashboardApp は mcp.weather-dashboard-app にマップされます。

<?php

namespace App\Mcp\Resources;

use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Attributes\AppMeta;
use Laravel\Mcp\Server\Attributes\Description;
use Laravel\Mcp\Server\AppResource;

#[Description('An interactive weather dashboard.')]
#[AppMeta]
class WeatherDashboardApp extends AppResource
{
/**
* Handle the app resource request.
*/
public function handle(Request $request): Response
{
return Response::view('mcp.weather-dashboard-app', [
'title' => $this->title(),
]);
}
}

AppResource は、基本 Resource クラスを拡張し、MCP アプリ仕様で必要な ui:// URI スキームと text/html;profile=mcp-app MIME タイプを自動的に構成します。他のリソースと同様に、サーバーの $resources 配列に登録する必要があります。

生成されたBlade ビューは、<x-mcp::app> コンポーネントを使用します。これにより、クライアント側 MCP SDK がバンドルされてすぐに使用できる完全な HTML ドキュメントがレンダリングされます。

<x-mcp::app :title="$title">
<x-slot:head>
<script type="module">
createMcpApp(async (app) => {
document.getElementById('run-btn').addEventListener('click', async () => {
const result = await app.callServerTool('get-weather-data', {});
document.getElementById('output').textContent = result.content[0]?.text ?? '';
});
});
</script>
</x-slot:head>

<div id="app">
<button id="run-btn">Refresh</button>
<p id="output"></p>
</div>
</x-mcp::app>

createMcpApp グローバルはバンドルされた SDK によって提供され、iframe のサーバーへの接続、ホスト テーマの適用、callServerTool、sendMessage、openLink などのヘルパの公開、およびイベント コールバックを処理します。完全なクライアント側 API については、MCP Apps specification を参照してください。

Rendering Apps From Tools​

アプリ リソースを表示するには、#[RendersApp] 属性を使用してツールをリソースにリンクします。ツールが呼び出されると、Laravel MCP はツールのメタデータにリソースの URI を含めるため、ホストはサンドボックス化された iframe でアプリをレンダリングできます。

<?php

namespace App\Mcp\Tools;

use App\Mcp\Resources\WeatherDashboardApp;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Attributes\RendersApp;
use Laravel\Mcp\Server\Tool;

#[RendersApp(resource: WeatherDashboardApp::class)]
class ShowWeatherDashboard extends Tool
{
/**
* Handle the tool request.
*/
public function handle(Request $request): Response
{
return Response::text('Weather dashboard loaded.');
}
}

Laravel MCP は、いずれかの AppResource が登録されていれば、サーバーの extensions 機能内で io.modelcontextprotocol/ui 拡張機能のサポートを自動的に公開するため、追加のサーバー設定は必要ありません。

App Tool Visibility​

各 #[RendersApp] ツールは、visibility 引数を介して呼び出し元を制限できます。これは、UI がデータをロードまたは更新するために呼び出すプライベートなアプリ専用ツールを、モデルに表示せずに公開する場合に便利です。

use Laravel\Mcp\Server\Attributes\RendersApp;
use Laravel\Mcp\Server\Ui\Enums\Visibility;

#[RendersApp(resource: WeatherDashboardApp::class, visibility: [Visibility::App])]
class GetWeatherData extends Tool
{
// ...
}

Visibility 列挙型には、Model と App の 2 つのケースがあり、デフォルトは両方です。 UI が直接呼び出すバックエンド アクションには [Visibility::App] を使用し、UI でツールを使用できないようにするには [Visibility::Model] を使用します。

App Configuration​

アプリ リソースの #[AppMeta] 属性は、iframe のコンテンツ セキュリティ ポリシー、ブラウザーのアクセス許可、およびビューの <head> に含める必要があるライブラリ スクリプトを構成します。

use Laravel\Mcp\Server\Attributes\AppMeta;
use Laravel\Mcp\Server\Ui\Enums\Library;
use Laravel\Mcp\Server\Ui\Enums\Permission;

#[AppMeta(
connectDomains: ['https://api.weather.com'],
permissions: [Permission::Geolocation],
libraries: [Library::Tailwind, Library::Alpine],
)]
class WeatherDashboardApp extends AppResource
{
// ...
}

Library 列挙には、Library::Tailwind や Library::Alpine などの一般的なフロントエンド ライブラリ用の事前構成された CDN スクリプトが含まれており、それらの CDN オリジンは自動的に CSP にマージされます。 Permission 列挙型は、Camera、Microphone、Geolocation、ClipboardWrite などのブラウザー権限をカバーします。

計算構成または動的構成の場合は、Laravel\Mcp\Server\Ui 名前空間の Fluent な AppMeta、Csp、および Permissions ビルダを使用して、リソースの appMeta メソッドをオーバーライドします。

Building Apps With Boost​

Laravel MCP には、MCP アプリを構築するための専用の Boost スキル リファレンスが含まれています。 Laravel Boost がインストールされている場合、AI コーディング エージェントは mcp-development スキルを呼び出し、アプリ リソース、Blade ビュー、およびリンクされたツールをスキャフォールディングするように依頼できます。

完全なクライアント側 API とスキーマの詳細を含む完全なプロトコル リファレンスについては、公式 MCP Apps documentation を参照してください。

Skills​

Laravel MCP では、MCP Skills extension(io.modelcontextprotocol/skills)を通じて Agent Skills を提供できます。クライアントは skills/list と skills/get でスキルを検出し、resources/read でそのファイルを読み取ります。

各スキルは、YAML frontmatter(ディレクトリ名と一致する name と description)を含む SKILL.md ファイルと、必要に応じて補助ファイルを格納したディレクトリに配置します。

---
name: release-checklist
description: Prepare a release using the bundled checklist.
---

# Release Checklist

Read [the checklist](references/checklist.md) before preparing a release.

$skills プロパティを使って、スキルのディレクトリをサーバーに直接登録できます。相対パスは resource_path() を基準に解決されます。また、$skills を定義すると、skills 拡張と resources capability が自動的に通知されます。

use App\Mcp\Skills\ReleaseChecklist;
use Laravel\Mcp\Server;

class ProjectServer extends Server
{
protected array $skills = [
'skills/house-style',
ReleaseChecklist::class,
];
}

スキルを条件付きで登録したい場合やカスタム URI が必要な場合は、Artisan コマンド make:mcp-skill を使って Skill クラスと SKILL.md ファイルのひな形を作成します。

php artisan make:mcp-skill ReleaseChecklist

shouldRegister メソッド(コンテナ経由で解決されます)を定義すると、戻り値が false の場合に、すべてのスキルおよびリソースのエンドポイントからそのスキルを非表示にできます。また、#[Uri] 属性を使って URI を変更できます(デフォルトは skill://{name}/SKILL.md です)。

<?php

namespace App\Mcp\Skills;

use Laravel\Mcp\Request;
use Laravel\Mcp\Server\Attributes\Uri;
use Laravel\Mcp\Server\Skill;

#[Uri('skill://engineering/release-checklist/SKILL.md')]
class ReleaseChecklist extends Skill
{
public function path(): string
{
return 'skills/release-checklist';
}

public function shouldRegister(Request $request): bool
{
return $request->user()?->can('prepare-releases') ?? false;
}
}

resources/list に表示されるのは SKILL.md だけですが、ディレクトリ内の補助ファイルはすべて resources/read で読み取れます。ドットファイルとシンボリックリンクはスキップされ、各スキルのファイル数は 512 個、サイズは 16 MiB までに制限されます。

Metadata​

Laravel MCP は、MCP specification で定義された _meta フィールドもサポートしています。このフィールドは、特定の MCP クライアントや統合で必要とされます。メタデータは、ツール、リソース、プロンプトを含むすべての MCP プリミティブと、それらのレスポンスに適用できます。

withMeta メソッドを使用して、個々の応答コンテンツにメタデータを添付できます。

use Laravel\Mcp\Request;
use Laravel\Mcp\Response;

/**
* Handle the tool request.
*/
public function handle(Request $request): Response
{
return Response::text('The weather is sunny.')
->withMeta(['source' => 'weather-api', 'cached' => true]);
}

応答エンベロープ全体に適用される結果レベルのメタデータの場合、応答を Response::make でラップし、返された応答ファクトリ インスタンスで withMeta を呼び出します。

use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\ResponseFactory;

/**
* Handle the tool request.
*/
public function handle(Request $request): ResponseFactory
{
return Response::make(
Response::text('The weather is sunny.')
)->withMeta(['request_id' => '12345']);
}

メタデータをツール、リソース、またはプロンプト自体に添付するには、クラスで $meta プロパティを定義します。

use Laravel\Mcp\Server\Attributes\Description;
use Laravel\Mcp\Server\Tool;

#[Description('Fetches the current weather forecast.')]
class CurrentWeatherTool extends Tool
{
protected ?array $meta = [
'version' => '2.0',
'author' => 'Weather Team',
];

// ...
}

Icons​

MCP クライアントは、サーバーとそのプリミティブのアイコンを表示できます。Icon 属性を使用して、サーバー、ツール、リソース、またはプロンプトにアイコンを宣言できます。

use Laravel\Mcp\Enums\IconTheme;
use Laravel\Mcp\Server\Attributes\Icon;

#[Icon('mcp/server.png', mimeType: 'image/png', sizes: ['48x48'])]
#[Icon('mcp/server-dark.svg', theme: IconTheme::Dark)]
class WeatherServer extends Server
{
// ...
}

Icon 属性は繰り返し指定できるため、複数のアイコンを宣言して、異なるサイズやライト・ダークテーマのバリエーションを提供できます。

あるいは、icons メソッドをオーバーライドしてアイコンをプログラムで定義することもできます。これは、アイコンが実行時の条件に依存する場合に便利です。

use Laravel\Mcp\Schema\Icon;

class CurrentWeatherTool extends Tool
{
/**
* Get the tool's icons.
*
* @return array<int, Icon>
*/
public function icons(): array
{
return [
Icon::from('mcp/tool.png', mimeType: 'image/png'),
];
}
}

属性で定義したアイコンと icons メソッドで定義したアイコンは自動的に統合されます。アイコンのパスは次のように解決されます。

  • https: や data: などの URI スキームを持つパスは、そのまま使用されます。
  • 相対パスは、Laravel の asset ヘルパを使用して URL に解決されます。

Client Capabilities​

MCP クライアントは初期化時に自身のケイパビリティを通知し、リクエストにもその情報を含めます。ツール、プロンプト、リソースの各ハンドラ内では、Laravel\Mcp\Request インスタンスの clientSupports メソッドを使い、接続中のクライアントが特定のケイパビリティを宣言しているか確認できます。ネストされたケイパビリティは「ドット」記法で指定します。

use Laravel\Mcp\Request;
use Laravel\Mcp\Response;

/**
* Handle the tool request.
*/
public function handle(Request $request): Response
{
if ($request->clientSupports('sampling.tools')) {
// ...
}

return Response::text('Done.');
}

配列として宣言されたケイパビリティオブジェクトは、['sampling' => ['tools' => []]] のような空のオブジェクトも含め、true として評価されます。ブール値のケイパビリティフラグは宣言された値のまま返されるため、['roots' => ['listChanged' => true]] の場合、roots.listChanged は true を返し、['sampling' => ['enabled' => false]] の場合、sampling.enabled は false を返します。

Authentication​

ルートと同様に、ミドルウェアを使用して Web MCP サーバーを認証できます。 MCP サーバーに認証を追加すると、ユーザーはサーバーの機能を使用する前に認証する必要があります。

このセクションでは、外部の AI クライアントがアプリケーションの MCP サーバーにアクセスする方法を説明します。ユーザーの認証情報を使ってアプリケーションを別のサービスの MCP サーバーに接続する方法については、client authenticationを参照してください。

MCP サーバーへのアクセスを認証するには 2 つの方法があります。1 つは、Laravel Sanctum または Authorization HTTP ヘッダーで渡す任意のトークンを使った、シンプルなトークンベースの認証です。もう 1 つは、Laravel Passport を使った OAuth 認証です。

OAuth 2.1​

Web ベースの MCP サーバーを保護する最も堅牢な方法は、Laravel Passport を使用した OAuth を使用することです。

OAuth 経由で MCP サーバーを認証する場合、routes/ai.php ファイル内の Mcp::oauthRoutes メソッドを呼び出して、必要な OAuth2 検出ルートとクライアント登録ルートを登録します。次に、Passport の auth:api ミドルウェアを routes/ai.php ファイル内の Mcp::web ルートに適用します。

use App\Mcp\Servers\WeatherExample;
use Laravel\Mcp\Facades\Mcp;

Mcp::oauthRoutes();

Mcp::web('/mcp/weather', WeatherExample::class)
->middleware('auth:api');

New Passport Installation​

アプリケーションがまだ Laravel Passport を使用していない場合は、Passport の installation and deployment guide に従って、Passport をアプリケーションに追加します。次に進む前に、OAuthenticatable モデル、新しい認証ガード、Passport のキーを用意しておく必要があります。

次に、Laravel MCP が提供する Passport 認可ビューを公開する必要があります。

php artisan vendor:publish --tag=mcp-views

次に、Passport::authorizationView メソッドを使用して、このビューを使用するように Passport に指示します。通常、このメソッドはアプリケーションの AppServiceProvider の boot メソッドで呼び出す必要があります。

use Laravel\Passport\Passport;

/**
* Bootstrap any application services.
*/
public function boot(): void
{
Passport::authorizationView(function ($parameters) {
return view('mcp.authorize', $parameters);
});
}

このビューは、AI エージェントの認証試行を拒否または承認するための認証中にエンドユーザーに表示されます。

認可画面例

このシナリオでは、基盤となる認証可能モデルへの変換レイヤーとして OAuth を単純に使用しています。スコープなど、OAuth の多くの側面は考慮していません。

Using an Existing Passport Installation​

アプリケーションがすでに Laravel Passport を使用している場合、Laravel MCP は既存の Passport インストール内でシームレスに動作するはずですが、OAuth は主に基盤となる認証可能なモデルへの変換レイヤーとして使用されるため、カスタム スコープは現在サポートされていません。

Laravel MCP は、上で説明した Mcp::oauthRoutes メソッドを介して、単一の mcp:use スコープを追加、アドバタイズ、および使用します。

Passport vs. Sanctum​

OAuth2.1 はモデル コンテキスト プロトコル仕様で文書化された認証メカニズムであり、MCP クライアント間で最も広くサポートされています。そのため、可能な限りPassportを使用することをお勧めします。

アプリケーションがすでに Sanctum を使用している場合、Passport の追加は面倒な場合があります。この場合、OAuth のみをサポートする MCP クライアントを使用するための明確な必要な要件が得られるまで、Passport なしで Sanctum を使用することをお勧めします。

Rate Limiting OAuth Routes​

MCP の仕様および RFC 7591 が想定しているとおり、Mcp::oauthRoutes が登録する動的なクライアント登録ルートは、すべての MCP クライアントが認証なしで自身を登録できるよう、公開されています。登録のたびにデータベースに新しい OAuth クライアントが作成されるため、アプリケーションのトラフィックに応じたレート制限を適用して、これらのルートを保護してください。Laravel の throttle ミドルウェアを適用するルートグループ内でルートを登録すると、レート制限を設定できます。

use Illuminate\Support\Facades\Route;
use Laravel\Mcp\Facades\Mcp;

Route::middleware('throttle:10,1')->group(function () {
Mcp::oauthRoutes();
});

MCP クライアントが自身を動的に登録する必要がない場合は、registration 引数に false を渡して、クライアント登録ルートを無効にできます。

Mcp::oauthRoutes(registration: false);

Sanctum​

Sanctum を使用して MCP サーバーを保護したい場合は、routes/ai.php ファイルで Sanctum の認証ミドルウェアをサーバーに追加するだけです。次に、認証が成功するように、MCP クライアントが Authorization: Bearer <token> ヘッダーを提供していることを確認します。

use App\Mcp\Servers\WeatherExample;
use Laravel\Mcp\Facades\Mcp;

Mcp::web('/mcp/demo', WeatherExample::class)
->middleware('auth:sanctum');

Custom MCP Authentication​

アプリケーションが独自のカスタム API トークンを発行する場合、必要なミドルウェアを Mcp::web ルートに割り当てることで、MCP サーバーを認証できます。カスタム ミドルウェアは、Authorization ヘッダーを手動で検査して、受信 MCP リクエストを認証できます。

Authorization​

$request->user() メソッドを介して現在認証されているユーザーにアクセスすると、MCP ツールおよびリソース内で authorization checks を実行できるようになります。

use Laravel\Mcp\Request;
use Laravel\Mcp\Response;

/**
* Handle the tool request.
*/
public function handle(Request $request): Response
{
if (! $request->user()->can('read-weather')) {
return Response::error('Permission denied.');
}

// ...
}

MCP クライアントとサーバーのセキュリティ対策については、MCP の Security Best Practices を参照してください。

MCP Client​

Laravel MCP は、サーバーの構築に加えて、ファーストパーティかサードパーティかを問わず、他の MCP サーバーへ接続するためのクライアントも備えています。クライアントを使うと、アプリケーションは MCP サーバーが公開するツールを検出して呼び出せます。これは、AI agents に外部 MCP サーバーが提供する機能へのアクセスを与えたい場合に特に便利です。

たとえば、チャットアプリケーションが各ユーザーの GitHub トークンを使って GitHub の MCP サーバーに接続すれば、エージェントがそのユーザーのリポジトリに関する質問に回答できます。この場合、アプリケーションは MCP クライアントとして動作するため、MCP サーバーを作成したり、Mcp::web ルートを登録したりする必要はありません。

Connecting to Servers​

HTTP でアクセスできる MCP サーバーへは、サーバーの URL を渡して Client::web メソッドで接続できます。

use Laravel\Mcp\Client;

$client = Client::web('https://api.githubcopilot.com/mcp/');

コマンドとして実行されるローカルの MCP サーバーへ接続するには、Client::local メソッドを使用し、サーバーを起動するためのコマンドと必要な引数を指定します。

use Laravel\Mcp\Client;

$client = Client::local('php', ['artisan', 'mcp:start']);

クライアントは遅延接続を行い、ツールを初めて一覧表示または呼び出ししたときに自動的に接続を確立します。接続を手動で管理する必要がある場合は、connect、connected、disconnect メソッドを使用できます。

$client->connect();

if ($client->connected()) {
$capabilities = $client->capabilities();
$server = $client->serverInfo();
}

$client->disconnect();

withTimeout メソッドを使用して、リクエストのタイムアウトをカスタマイズできます。

$client = Client::web('https://api.githubcopilot.com/mcp/')->withTimeout(30);

Named Clients​

クライアントが必要になるたびに作成する代わりに、再利用可能な名前付きクライアントを登録することもできます。registerClient メソッドは送信接続に名前を付けるものであり、MCP サーバーを公開したり、ユーザーを認可したりするものではありません。通常、サービスプロバイダの boot メソッドで Mcp ファサードを使って登録します。

use Laravel\Mcp\Client;
use Laravel\Mcp\Facades\Mcp;

Mcp::registerClient('github', fn () => Client::web('https://api.githubcopilot.com/mcp/'));

登録すると、アプリケーションのどこからでも名前でクライアントを解決できます。

use Laravel\Mcp\Facades\Mcp;

$client = Mcp::client('github');

名前付きクライアントはリクエストごとに一度だけ解決され、リクエストのライフサイクル終了時に自動的に切断されます。

Client Authentication​

Bearer Tokens​

ベアラートークンで保護されたウェブ MCP サーバーへ接続するには、withToken メソッドを使用します。トークン文字列、またはトークンを遅延的に解決するクロージャを渡せます。

use Illuminate\Support\Facades\Auth;
use Laravel\Mcp\Client;

$client = Client::web('https://api.githubcopilot.com/mcp/')->withToken(
config('services.github_mcp.token'),
);

$client = Client::web('https://api.githubcopilot.com/mcp/')->withToken(
fn () => Auth::user()->github_mcp_token,
);

Socialite などのアカウント連携フローですでに適切なトークンを取得している場合は、そのトークンを withToken に渡してください。MCP OAuth ルートを登録する必要はありません。

Linking User Accounts With OAuth​

チャットアプリケーションで、ユーザーがプロジェクト管理サービスに接続し、「期限を過ぎているタスクはどれですか?」といった質問をエージェントにする場面を考えてみましょう。外部のプロジェクト管理サービスは、OAuthで保護されたMCPサーバーを公開しています。アプリケーションは各ユーザーをサービスの同意画面にリダイレクトし、ユーザーの承認と引き換えにトークンを取得して、今後のツール呼び出しに備えて保存する必要があります。

Laravel MCP では withOAuth と Mcp::oAuthRoutesFor を使って、このアカウント連携フローを処理します。まず、サービスプロバイダに名前付きクライアントを登録します。OAuth クライアントの認証情報はサービスに対してアプリケーションを識別するために使われ、withToken はツールの呼び出し時に接続済みユーザーが保存したアクセストークンを渡します。

use Illuminate\Support\Facades\Auth;
use Laravel\Mcp\Client;
use Laravel\Mcp\Facades\Mcp;

Mcp::registerClient('projects', fn () => Client::web('https://projects.example.com/mcp')
->withOAuth(
clientId: config('services.projects.client_id'),
clientSecret: config('services.projects.client_secret'),
)
->withToken(fn () => Auth::user()->projects_token));

clientId 引数と clientSecret 引数は省略できます。認可サーバが対応している場合、Laravel は Client ID Metadata Document を使用し、従来のサーバでは dynamic client registration にフォールバックします。

認可サーバーは、認可サーバーのメタデータで S256 PKCE コードチャレンジ方式のサポートを明示する必要があります。PKCE のサポートが明示されていない場合、Laravel は認可試行を拒否します。

次に、routes/ai.php ファイルにアカウント連携用のルートを登録します。コールバックにはクライアント名と生成された TokenSet が渡されるため、サインイン中のユーザーのトークンを保存できます。

use Illuminate\Support\Facades\Auth;
use Laravel\Mcp\Client\OAuth\TokenSet;
use Laravel\Mcp\Facades\Mcp;

Mcp::oAuthRoutesFor('projects', function (string $client, TokenSet $token) {
Auth::user()->update([
'projects_token' => $token->accessToken,
]);

return redirect('/chat');
}, middleware: ['web', 'auth']);

oAuthRoutesFor メソッドは、名前付きルートを3つ登録します。認可サーバーへユーザーをリダイレクトする接続ルート (mcp.oauth.{client}.connect)、認可コードを交換してハンドラを呼び出すコールバックルート (mcp.oauth.{client}.callback)、および公開 Client ID Metadata Document ルート (mcp.oauth.{client}.client-metadata) です。

connect ルートと callback ルートでは、デフォルトで web ミドルウェアグループが使われます。前述のアカウント連携の例では、サインイン済みのユーザーを必須にするため auth を追加しています。metadata ルートでこのミドルウェアを使わないのは、認可サーバーが metadata を取得できる必要があるためです。

「Connect Project Service」ボタンをクリックすると、ユーザーが接続ルートに移動するようにします。

return redirect()->route('mcp.oauth.projects.connect');

Laravel はユーザーをサービスへリダイレクトしてアクセスを承認してもらい、ユーザーが戻ってきた際に認可コードを交換してコールバックを呼び出します。その後のチャットリクエストでは、名前付きクライアントが保存済みのトークンを使用します。たとえば、AI SDK agent がサービスのツールを公開できます。

public function tools(): iterable
{
return [
...Mcp::client('projects')->tools(),
];
}

トークンは encrypted casts を使って保存し、モデルのシリアライズ結果に含まれないようにしてください。サービスが有効期限付きトークンを発行する場合は、TokenSet のリフレッシュトークンと有効期限の情報も保存し、ツールを呼び出す前に更新処理を行ってください。キューで実行するエージェントでは、Auth::user() ではなく、明示的に指定したユーザーから認証情報を取得してください。

Mcp::oAuthRoutesFor は、ユーザーを外部サービスに接続します。一方、Mcp::oauthRoutes を使うと、外部の AI クライアントが Passport を利用して独自の MCP サーバーに認証できます。上記のアカウント連携フローでは、Passport も Mcp::oauthRoutes も必要ありません。

Client Metadata​

メタデータドキュメントはアプリケーションをパブリックな OAuth クライアントとして記述し、アプリケーションの APP_URL を使ってクライアント ID とコールバック URL を生成します。そのため、本番環境では APP_URL 環境変数が正しく設定されていることを確認してください。clientMetadataUri 引数と clientMetadata 引数を使って、メタデータルートをカスタマイズしたり、追加のメタデータを指定したりできます。

use Laravel\Mcp\Client\OAuth\TokenSet;
use Laravel\Mcp\Facades\Mcp;

Mcp::oAuthRoutesFor(
'projects',
function (string $client, TokenSet $token) {
// Store the token...

return redirect('/dashboard');
},
clientMetadataUri: 'oauth/projects/client.json',
clientMetadata: [
'client_name' => 'Acme Dashboard',
'logo_uri' => 'https://acme.com/logo.png',
],
);

Tools​

MCP サーバーが公開するツールは、tools メソッドを使用して取得できます。このメソッドは名前をキーとするツールのコレクションを返します。

use Laravel\Mcp\Facades\Mcp;

$tools = Mcp::client('github')->tools();

foreach ($tools as $tool) {
$tool->name;
$tool->title;
$tool->description;
$tool->inputSchema;
}

クライアントはすべてのページを自動的に取得し、利用可能なツールを返します。limit 引数を使用して、返されるツールの数を制限できます。

$tools = Mcp::client('github')->tools(limit: 10);

ツールを呼び出すには、callTool メソッドにツール名と引数の配列を渡します。返される ToolResult インスタンスからツールの応答にアクセスできます。

use Laravel\Mcp\Facades\Mcp;

$result = Mcp::client('github')->callTool('list_issues', [
'owner' => 'laravel',
'repo' => 'framework',
]);

$result->text(); // The text content of the response...
(string) $result; // Equivalent to calling text()...
$result->isError; // Whether the tool reported an error...
$result->structuredContent; // Structured content, if any...

あるいは、一覧表示したツールインスタンスから直接ツールを呼び出すこともできます。

$tools = Mcp::client('github')->tools();

$result = $tools['list_issues']->call([
'owner' => 'laravel',
'repo' => 'framework',
]);

Laravel AI SDK でエージェントを構築している場合は、MCP クライアントのツールをエージェントへ直接提供することもでき、モデルがプロンプトに応答しながらそれらを呼び出せます。詳細については、AI SDK ドキュメントの MCP Tools セクションを参照してください。

Prompts​

MCP サーバーが公開するプロンプトは、prompts メソッドを使用して取得できます。このメソッドは名前をキーとするプロンプトのコレクションを返します。

use Laravel\Mcp\Facades\Mcp;

$prompts = Mcp::client('github')->prompts();

foreach ($prompts as $prompt) {
$prompt->name;
$prompt->title;
$prompt->description;
$prompt->arguments;
}

クライアントはすべてのページを自動的に取得し、利用可能なプロンプトを返します。limit 引数を使用して、返されるプロンプトの数を制限できます。

$prompts = Mcp::client('github')->prompts(limit: 10);

プロンプトを取得するには、getPrompt メソッドにプロンプト名と引数の配列を渡します。返される PromptResult インスタンスから生成されたメッセージにアクセスできます。

use Laravel\Mcp\Facades\Mcp;

$result = Mcp::client('github')->getPrompt('issue_to_fix_workflow', [
'owner' => 'laravel',
'repo' => 'framework',
'title' => 'Fix typo in README',
'description' => 'The installation section has a typo.',
]);

$result->text(); // The text content of the messages...
(string) $result; // Equivalent to calling text()...
$result->messages; // The raw messages returned by the prompt...
$result->description; // The prompt description, if any...

Resources​

MCP サーバーが公開するリソースは、resources メソッドを使用して取得できます。このメソッドは URI をキーとするリソースのコレクションを返します。

use Laravel\Mcp\Facades\Mcp;

$resources = Mcp::client('github')->resources();

foreach ($resources as $resource) {
$resource->uri;
$resource->name;
$resource->title;
$resource->description;
$resource->mimeType;
$resource->size;
}

クライアントはすべてのページを自動的に取得し、利用可能なリソースを返します。limit 引数を使用して、返されるリソースの数を制限できます。

$resources = Mcp::client('github')->resources(limit: 10);

リソースを読み取るには、readResource メソッドにリソースの URI を渡します。返される ResourceReadResult インスタンスからリソースのコンテンツにアクセスできます。

use Laravel\Mcp\Facades\Mcp;

$result = Mcp::client('github')->readResource('repo://laravel/framework/contents/README.md');

$result->content(); // The content of the resource, decoding base64 blobs as needed...
(string) $result; // Equivalent to calling content()...
$result->mimeType(); // The MIME type of the resource, if any...
$result->contents; // The raw contents returned by the resource...

Testing Servers​

組み込みの MCP インスペクターを使用するか、単体テストを作成することによって、MCP サーバーをテストできます。

MCP Inspector​

MCP Inspector は、MCP サーバーをテストおよびデバッグするための対話型ツールです。これを使用してサーバーに接続し、認証を確認し、ツール、リソース、プロンプトを試します。

登録されている任意のサーバーに対してインスペクタを実行できます。

# Web server...
php artisan mcp:inspector mcp/weather

# Local server named "weather"...
php artisan mcp:inspector weather

このコマンドは MCP インスペクターを起動し、すべてが正しく構成されていることを確認するために MCP クライアントにコピーできるクライアント設定を提供します。 Web サーバーが認証ミドルウェアによって保護されている場合は、接続時に Authorization ベアラー トークンなどの必要なヘッダーを必ず含めてください。

Unit Tests​

MCP サーバー、ツール、リソース、プロンプトの単体テストを作成できます。

まず、新しいテスト ケースを作成し、それを登録するサーバー上で目的のプリミティブを呼び出します。たとえば、WeatherServer でツールをテストするには:

test('tool', function () {
$response = WeatherServer::tool(CurrentWeatherTool::class, [
'location' => 'New York City',
'units' => 'fahrenheit',
]);

$response
->assertOk()
->assertSee('The current weather in New York City is 72°F and sunny.');
});
/**
* Test a tool.
*/
public function test_tool(): void
{
$response = WeatherServer::tool(CurrentWeatherTool::class, [
'location' => 'New York City',
'units' => 'fahrenheit',
]);

$response
->assertOk()
->assertSee('The current weather in New York City is 72°F and sunny.');
}

同様に、プロンプトとリソースをテストできます。

$response = WeatherServer::prompt(...);
$response = WeatherServer::resource(...);

プリミティブを呼び出す前に actingAs メソッドをチェーンすることで、認証されたユーザーとして動作することもできます。

$response = WeatherServer::actingAs($user)->tool(...);

特定の client capabilities を通知するクライアントをシミュレートするには、ツール、プロンプト、リソース、または補完を呼び出す前に withClientCapabilities メソッドをチェーンします。デフォルトでは、テストクライアントは何のケイパビリティも宣言しません。

$response = WeatherServer::withClientCapabilities([
'sampling' => ['tools' => []],
])->tool(CurrentWeatherTool::class);

応答を受信したら、さまざまなアサーション メソッドを使用して、応答の内容とステータスを確認できます。

assertOk メソッドを使用して、応答が成功したことをアサートできます。これにより、応答にエラーがないことがチェックされます。

$response->assertOk();

assertSee メソッドを使用して、応答に特定のテキストが含まれていることをアサートできます。

$response->assertSee('The current weather in New York City is 72°F and sunny.');

structured content を返すツールでは、件数、特定のパスにある値、応答の構造をアサートできます。

$response
->assertStructuredContentCount(2, 'data')
->assertStructuredContentPath('data.0.location', 'New York City')
->assertStructuredContentPaths([
'data.0.temperature' => 72,
'data.1.temperature' => 68,
])
->assertStructuredContentStructure([
'data' => [
'*' => ['location', 'temperature'],
],
]);

パスには「ドット」記法を使えます。また、assertStructuredContentPath メソッドにはクロージャも渡せます。クロージャを使うと、値が指定した真偽条件を満たすかどうかを判定できます。

$response->assertStructuredContentPath('data.0.temperature', fn (int $temperature): bool => $temperature > 70);

次の構造化コンテンツのアサーションを使用できます。

メソッド説明
assertExactStructuredContent($data)構造化コンテンツが指定した配列と完全に一致することをアサートします。
assertSimilarStructuredContent($data)順序を無視して、構造化コンテンツが指定した配列と一致することをアサートします。
assertStructuredContentCount($count, $key = null)項目数をアサートします。必要に応じて、指定したキーの項目数を対象にできます。
assertStructuredContentPath($path, $expect)指定したパスの値をアサートします。
assertStructuredContentPaths($paths)複数のパスと値の組み合わせをアサートします。
assertStructuredContentPathCanonicalizing($path, $expect)順序を無視して、指定したパスの値をアサートします。
assertStructuredContentPathsCanonicalizing($paths)順序を無視して、複数のパスと値の組み合わせをアサートします。
assertStructuredContentFragment($data)構造化コンテンツ内のどこかに指定した断片が含まれることをアサートします。
assertStructuredContentFragments($data)指定した各断片が構造化コンテンツに含まれることをアサートします。
assertStructuredContentMissing($data)指定した断片が構造化コンテンツに含まれないことをアサートします。
assertStructuredContentMissingExact($data)指定した断片と完全に一致するものが構造化コンテンツに含まれないことをアサートします。
assertStructuredContentMissingPath($path)指定したパスが存在しないことをアサートします。
assertStructuredContentMissingPaths($paths)複数のパスが存在しないことをアサートします。
assertStructuredContentStructure($structure)追加のキーを許容しつつ、指定したキーが存在することをアサートします。
assertExactStructuredContentStructure($structure)指定したキーだけが存在することをアサートします。
assertStructuredContentIsArray($key = null)構造化コンテンツが JSON 配列であることをアサートします。必要に応じて、指定したキーの値を対象にできます。
assertStructuredContentIsObject($key = null)構造化コンテンツが JSON オブジェクトであることをアサートします。必要に応じて、指定したキーの値を対象にできます。

assertHasErrors メソッドを使用して、応答にエラーが含まれていることをアサートできます。

$response->assertHasErrors();

$response->assertHasErrors([
'Something went wrong.',
]);

assertHasNoErrors メソッドを使用して、応答にエラーが含まれていないことをアサートできます。

$response->assertHasNoErrors();

JSON-RPC エラー応答に特定のエラーコードと、必要に応じてエラー data が含まれていることをアサートするには、assertErrorCode メソッドを使用します。

$response->assertErrorCode(-32602);

$response->assertErrorCode(-32021, [
'requiredCapabilities' => ['sampling' => []],
]);

assertName()、assertTitle()、および assertDescription() メソッドを使用して、応答に特定のメタデータが含まれていることをアサートできます。

$response->assertName('current-weather');
$response->assertTitle('Current Weather Tool');
$response->assertDescription('Fetches the current weather forecast for a specified location.');

assertSentNotification および assertNotificationCount メソッドを使用して、通知が送信されたことをアサートできます。

$response->assertSentNotification('processing/progress', [
'step' => 1,
'total' => 5,
]);

$response->assertSentNotification('processing/progress', [
'step' => 2,
'total' => 5,
]);

$response->assertNotificationCount(5);

ストリーミングツールが Response::progress を yield する場合は、assertSentProgress メソッドを使って、送信された進捗通知を検証できます。

$response
->assertSentProgress(1, total: 2, message: 'Importing report.csv...')
->assertSentProgress(2, total: 2);

最後に、生の応答コンテンツを検査したい場合は、dd メソッドまたは dump メソッドを使用して、デバッグ目的で応答を出力できます。

$response->dd();
$response->dump();