🚀 Laravel MCP 中文文檔
Laravel MCP 是一個強大的包,它允許 Laravel 應用程序藉助標準化 API 與 AI 助手及其他系統進行通信。通過使用該包,開發者能以簡單的方式擴展應用程序功能,實現與外部工具和服務的交互。
🚀 快速開始
Laravel MCP 為 Laravel 應用程序提供了與外部系統通信的能力,下面將詳細介紹其安裝和使用方法。
📦 安裝指南
要安裝 Laravel MCP,只需運行以下命令:
composer require laravel/mcp
💻 使用示例
基礎用法
設置 MCP 服務器
若要創建一個 MCP 服務器,請按以下步驟操作:
- 在
app/Console/Commands
目錄下創建一個新的命令文件,例如 McpServerCommand.php
。
- 在該文件中,添加以下代碼:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use InnoGE\LaravelMCP\Tools\ServesMcpServer;
class McpServerCommand extends Command
{
protected function signature(): string
{
return 'mcp:serve';
}
protected function description(): string
{
return '啟動 MCP 服務器。';
}
public function handle()
{
$this->registerMcpServer();
return 0;
}
protected function registerMcpServer()
{
}
}
- 註冊命令到
app/Console/Kernel.php
:
protected function commands()
{
require app_path('Console/Commands/McpServerCommand.php');
}
- 啟動服務器:
php artisan mcp:serve
資源
概念
資源是 MCP 服務器的核心功能,它允許外部系統查詢和操作數據。例如,您可以創建一個資源來表示應用程序中的用戶。
創建資源
在 app/Models
目錄下創建一個新的模型文件,例如 UserResource.php
:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use InnoGE\LaravelMCP\Resources\Resource;
class UserResource extends Model implements Resource
{
protected $table = 'users';
}
註冊資源
在 app/Providers/AppServiceProvider.php
中註冊資源:
public function register()
{
$this->app->singleton(UserResource::class, function () {
return new UserResource();
});
}
工具
概念
工具是 MCP 服務器的核心功能,允許外部系統通過執行命令來操作應用程序。例如,您可以創建一個工具來發送郵件。
創建工具
在 app/Tools
目錄下創建一個新的工具文件,例如 SendEmailTool.php
:
<?php
namespace App\Tools;
use InnoGE\LaravelMCP\Tools\Tool;
class SendEmailTool implements Tool
{
public function getName(): string
{
return 'send-email';
}
public function getDescription(): string
{
return '發送郵件。';
}
public function getInputSchema(): array
{
return [
'type' => 'object',
'properties' => [
'to' => [
'type' => 'string',
'description' => '收件人郵箱地址。',
],
'subject' => [
'type' => 'string',
'description' => '郵件主題。',
],
'body' => [
'type' => 'string',
'description' => '郵件正文內容。',
],
],
'required' => ['to', 'subject', 'body'],
];
}
public function execute(array $parameters): string
{
return '郵件已成功發送。';
}
}
註冊工具
在 app/Providers/AppServiceProvider.php
中註冊工具:
public function register()
{
$this->app->singleton(SendEmailTool::class, function () {
return new SendEmailTool();
});
}
測試
使用 Modelcontext Protocol Inspector 測試
要測試 MCP 服務器,請運行以下命令:
php artisan mcp:serve
然後在瀏覽器中訪問 http://localhost:8000
。
配置 Claude Desktop
要在 Claude Desktop 中使用 MCP 服務器,請按照以下步驟操作:
- 打開 Claude Desktop。
- 點擊頂部菜單欄中的 File,然後選擇 New Connection。
- 在連接設置中輸入您的 MCP 服務器地址(例如
http://localhost:8000
)。
- 點擊 Connect。
🤝 貢獻
如果您有任何問題或建議,請在 GitHub 上提出 Issues 或 Pull Requests。
🔒 安全政策
請參考 安全政策文檔 以瞭解更多信息。
📄 許可證
Laravel MCP 是在 MIT 許可證下發布的。請參考 LICENSE 以獲取詳細信息。