Skip to content

Laravel MCP

Giới thiệu (Introduction)

Laravel MCP cung cấp cách đơn giản và thanh lịch để AI client tương tác với ứng dụng Laravel thông qua Model Context Protocol. Package này cung cấp interface fluent để định nghĩa server, tool, resource và prompt cho các tương tác AI-powered.

Cài đặt (Installation)

bash
composer require laravel/mcp

Phát hành Routes (Publishing Routes)

Laravel MCP sử dụng file routes/ai.php để đăng ký server. Nếu file chưa tồn tại, chạy:

bash
php artisan install:mcp

Tạo Server (Creating Servers)

Tạo MCP server bằng lệnh Artisan:

bash
php artisan make:mcp-server WeatherServer

Server class mới sẽ nằm trong app/Mcp/Servers, kế thừa Laravel\Mcp\Server:

php
<?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('Server cung cấp thông tin và dự báo thời tiết.')]
class WeatherServer extends Server
{
    /**
     * Các tool đăng ký với server.
     *
     * @var array<int, class-string<\Laravel\Mcp\Server\Tool>>
     */
    protected array $tools = [
        // GetCurrentWeatherTool::class,
    ];

    /**
     * Các resource đăng ký với server.
     *
     * @var array<int, class-string<\Laravel\Mcp\Server\Resource>>
     */
    protected array $resources = [
        // WeatherGuidelinesResource::class,
    ];

    /**
     * Các prompt đăng ký với server.
     *
     * @var array<int, class-string<\Laravel\Mcp\Server\Prompt>>
     */
    protected array $prompts = [
        // DescribeWeatherPrompt::class,
    ];
}

Đăng ký Server (Server Registration)

Đăng ký server trong file routes/ai.php. Laravel MCP cung cấp 2 phương thức: web cho HTTP server và local cho server command-line.

Web Servers

Server web truy cập qua HTTP POST requests — phù hợp cho remote AI client:

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

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

Áp dụng middleware:

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

Local Servers

Server local chạy như Artisan command — phù hợp cho tích hợp AI assistant cục bộ:

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

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

Tools

Tools cho phép server expose chức năng mà AI client có thể gọi — cho phép language model thực hiện hành động, chạy code, hoặc tương tác hệ thống bên ngoài:

php
<?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('Lấy dự báo thời tiết hiện tại cho một địa điểm.')]
class CurrentWeatherTool extends Tool
{
    /**
     * Xử lý tool request.
     */
    public function handle(Request $request): Response
    {
        $location = $request->get('location');

        // Lấy thời tiết...

        return Response::text('Thời tiết hiện tại là...');
    }

    /**
     * Lấy input schema của tool.
     *
     * @return array<string, \Illuminate\JsonSchema\Types\Type>
     */
    public function schema(JsonSchema $schema): array
    {
        return [
            'location' => $schema->string()
                ->description('Địa điểm cần lấy thời tiết.')
                ->required(),
        ];
    }
}

Tạo Tools

bash
php artisan make:mcp-tool CurrentWeatherTool

Đăng ký tool trong server:

php
<?php

namespace App\Mcp\Servers;

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

class WeatherServer extends Server
{
    protected array $tools = [
        CurrentWeatherTool::class,
    ];
}

Tên, tiêu đề và mô tả Tool

Mặc định, tên và tiêu đề tool được suy ra từ class name. Ví dụ CurrentWeatherTool sẽ có name current-weather và title Current Weather Tool. Tùy chỉnh bằng attribute:

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

#[Name('get-optimistic-weather')]
#[Title('Get Optimistic Weather Forecast')]
#[Description('Lấy dự báo thời tiết lạc quan cho một địa điểm.')]
class CurrentWeatherTool extends Tool
{
    // ...
}

Tool Input Schemas

Định nghĩa input schema cho tool bằng method schema:

php
public function schema(JsonSchema $schema): array
{
    return [
        'location' => $schema->string()
            ->description('Địa điểm cần lấy thời tiết.')
            ->required(),
        'unit' => $schema->enum(['celsius', 'fahrenheit'])
            ->description('Đơn vị nhiệt độ.')
            ->default('celsius'),
    ];
}

Tool Annotations

Annotations cung cấp metadata mô tả hành vi của tool:

php
use Laravel\Mcp\Server\Attributes\ReadOnlyHint;
use Laravel\Mcp\Server\Attributes\IdempotentHint;

#[ReadOnlyHint]
#[IdempotentHint]
class CurrentWeatherTool extends Tool
{
    // ...
}

Tool Responses

Trả về response từ tool:

php
// Trả về text
return Response::text('Thời tiết hiện tại là nắng.');

// Trả về JSON
return Response::json(['temperature' => 25, 'condition' => 'sunny']);

// Trả về image
return Response::image($imageContent, 'image/png');

// Trả về lỗi
return Response::error('Không tìm thấy dữ liệu thời tiết.');

Prompts

Prompts cho phép server chia sẻ prompt template tái sử dụng. Chúng cung cấp cách chuẩn hóa để cấu trúc các query và tương tác phổ biến.

Tạo Prompts

bash
php artisan make:mcp-prompt DescribeWeatherPrompt

Prompt Arguments

Prompt có thể nhận arguments từ AI client.

Prompt Responses

Prompt trả về danh sách message cho AI model sử dụng.

Resources

Resources cho phép server expose dữ liệu và nội dung mà AI client có thể đọc. Chúng cung cấp cách chia sẻ thông tin tĩnh hoặc động như tài liệu, cấu hình, hoặc bất kỳ dữ liệu nào giúp AI responses chính xác hơn.

Tạo Resources

bash
php artisan make:mcp-resource WeatherGuidelinesResource

Resource Templates

Resource template cho phép tạo resource với URI pattern động.

Authentication

Tương tự route, bạn có thể xác thực web MCP server bằng middleware. Hai cách:

  • Sanctum — Token-based authentication qua header Authorization
  • OAuth 2.1 — Xác thực qua Laravel Passport

Authorization

Truy cập user đã xác thực qua $request->user():

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

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

    // ...
}

Kiểm thử Servers (Testing Servers)

MCP Inspector

Laravel MCP bao gồm MCP Inspector tích hợp để test server trực quan:

bash
php artisan mcp:inspect

Unit Tests

Viết unit test cho MCP tools, resources và prompts.

Metadata

Server có thể cung cấp metadata bổ sung cho AI client.