Skip to content

Laravel MCP

简介

Laravel MCP 通过 Model Context Protocol 为 AI 客户端与 Laravel 应用程序交互提供了一种简单优雅的方式。它提供了一个表达性强、流畅的接口来定义服务器、工具、资源和提示,从而实现与应用程序的 AI 驱动交互。

安装

首先,使用 Composer 包管理器将 Laravel MCP 安装到你的项目中:

shell
composer require laravel/mcp

发布路由

安装 Laravel MCP 后,执行 vendor:publish Artisan 命令发布 routes/ai.php 文件,你将在其中定义 MCP 服务器:

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

此命令在应用程序的 routes 目录中创建 routes/ai.php 文件,你将使用它来注册 MCP 服务器。

创建服务器

你可以使用 make:mcp-server Artisan 命令创建 MCP 服务器。服务器充当向 AI 客户端公开工具、资源和提示等 MCP 功能的中心通信点:

shell
php artisan make:mcp-server WeatherServer

此命令将在 app/Mcp/Servers 目录中创建一个新的服务器类。生成的服务器类继承 Laravel MCP 的基础 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('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 = [