Model Context Protocol (MCP) est une spécification pour la communication standardisée entre clients IA (Claude, Cursor, GitHub Copilot…) et les applications. En implémentant un serveur MCP, votre agent IA peut accéder aux données de votre app Laravel et déclencher des actions.
Laravel MCP est un package officiel ajouté sous Laravel 13, disponible sous laravel/mcp.
Un serveur MCP fournit trois choses :
Fonctionnalité
Description
Tools
Fonctions appelables par le client IA (recherche, mise à jour, appel d’API externe…)
<?phpnamespace 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{ public function handle(Request $request): Response { $location = $request->get('location'); // Récupérer la météo... return Response::text('The weather is sunny, 22°C.'); } public function schema(JsonSchema $schema): array { return [ 'location' => $schema->string() ->description('The location to get the weather for.') ->required(), ]; }}
schema() définit les paramètres via le builder de schéma JSON.
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'), ];}
Utilisez la validation Laravel standard dans handle().
public function handle(Request $request): Response{ $validated = $request->validate([ 'location' => 'required|string|max:100', 'units' => 'in:celsius,fahrenheit', ], [ 'location.required' => 'You must specify a location. For example, "New York City" or "Tokyo".', 'units.in' => 'You must specify either "celsius" or "fahrenheit" for the units.', ]); // Utilisez les données validées...}
Les messages d’erreur sont retournés au client IA, qui peut alors reformuler l’appel.
Utilisez TestServer pour tester votre serveur MCP.
use App\Mcp\Servers\WeatherServer;use Laravel\Mcp\Testing\TestServer;test('current weather tool returns weather', function () { $server = new TestServer(WeatherServer::class); $response = $server->tool('current-weather', [ 'location' => 'Tokyo', ]); $response->assertSuccessful(); $response->assertContains('sunny');});
Testez schémas et validation :
$server = new TestServer(WeatherServer::class);$response = $server->tool('current-weather', []);$response->assertFailed();$response->assertContains('location is required');