定制 elliottlawson/mcp-laravel-sdk 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

elliottlawson/mcp-laravel-sdk

Composer 安装命令:

composer require elliottlawson/mcp-laravel-sdk

包简介

Laravel-native implementation of the Model Context Protocol (MCP)

README 文档

README

A Laravel-native implementation of the Model Context Protocol (MCP) Server, allowing seamless integration of MCP capabilities into Laravel applications. Compatible with Laravel 10.x, 11.x, and 12.x, with optimizations for the latest Laravel versions.

Installation

You can install the package via composer:

composer require elliottlawson/mcp-laravel-sdk

The service provider will be automatically registered through Laravel's package discovery.

Configuration

Laravel 10 and 11

For Laravel 10 and 11, publish the configuration file using:

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

This will create a config/mcp.php file that you can customize.

Laravel 12

For Laravel 12, the configuration should be placed in the bootstrap/mcp.php file, following Laravel 12's new configuration approach. Create this file manually or publish it using:

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

Features

  • Full Laravel-native implementation with no external JSON-RPC dependencies
  • Proper SSE implementation that works with Laravel's response lifecycle
  • Direct integration with Laravel's Eloquent models
  • Simple registration API for resources, tools, and prompts
  • JSON-RPC 2.0 compliant API
  • Support for batch requests
  • Comprehensive error handling

Basic Usage

Registering Resources, Tools, and Prompts

You can register resources, tools, and prompts in your service provider or directly in your application code:

use ElliottLawson\LaravelMcp\Facades\Mcp;
use App\Models\User;
use ElliottLawson\LaravelMcp\Tools\CommandTool;
use ElliottLawson\LaravelMcp\Prompts\FilePrompt;

// Register a resource from an Eloquent model
Mcp::resource('users', User::class);

// Register a tool with a schema and handler
Mcp::tool('echo', [
    'type' => 'object',
    'properties' => [
        'message' => [
            'type' => 'string',
            'description' => 'The message to echo'
        ]
    ]
], new CommandTool('echo', [
    'command' => 'echo',
    'args' => ['message']
]));

// Register a prompt
Mcp::prompt('system', 'You are a helpful assistant integrated with Laravel.');
// Or from a file
Mcp::prompt('system', new FilePrompt('system', storage_path('prompts/system.txt')));

Configuration File

Here's an example configuration file:

<?php

// For Laravel 10-11: config/mcp.php
// For Laravel 12: bootstrap/mcp.php

return [
    // Server information
    'name' => env('MCP_SERVER_NAME', 'Laravel MCP Server'),
    'version' => env('MCP_SERVER_VERSION', '1.0.0'),
    
    // HTTP configuration
    'http' => [
        'route_prefix' => 'mcp',
        'middleware' => ['web'],
        'cors' => [
            'allowed_origins' => ['*'],
            'allowed_methods' => ['GET', 'POST', 'OPTIONS'],
            'allowed_headers' => ['Content-Type', 'X-Requested-With'],
        ],
    ],
    
    // SSE configuration
    'sse' => [
        'heartbeat_interval' => 30, // seconds
        'max_execution_time' => 0, // 0 for no limit
        'retry_interval' => 3000, // milliseconds
    ],
    
    // Register resources
    'resources' => [
        'users' => App\Mcp\Resources\UserResource::class,
        // Or register a model directly
        'products' => App\Models\Product::class,
    ],
    
    // Register tools
    'tools' => [
        'calculator' => App\Mcp\Tools\CalculatorTool::class,
    ],
    
    // Register prompts
    'prompts' => [
        'system' => 'You are a helpful assistant integrated with Laravel.',
        // Or reference a file
        'chat' => resource_path('prompts/chat.txt'),
    ],
];

Creating Custom Components

Custom Resource

namespace App\Mcp\Resources;

use ElliottLawson\LaravelMcp\Resources\BaseResource;
use ElliottLawson\LaravelMcp\Contracts\ResourceContract;

class CustomResource implements ResourceContract
{
    public function getData(array $params)
    {
        // Implement your resource logic here
        return [
            'data' => [
                // Your resource data
            ],
            'meta' => [
                'total' => 1,
                'per_page' => 15,
                'current_page' => 1,
            ],
        ];
    }
}

Custom Tool

namespace App\Mcp\Tools;

use ElliottLawson\LaravelMcp\Tools\BaseTool;
use ElliottLawson\LaravelMcp\Contracts\ToolContract;

class CalculatorTool implements ToolContract
{
    public function execute(array $params)
    {
        $a = $params['a'] ?? 0;
        $b = $params['b'] ?? 0;
        $operation = $params['operation'] ?? 'add';
        
        switch ($operation) {
            case 'add':
                $result = $a + $b;
                break;
            case 'subtract':
                $result = $a - $b;
                break;
            case 'multiply':
                $result = $a * $b;
                break;
            case 'divide':
                $result = $b != 0 ? $a / $b : 'Error: Division by zero';
                break;
            default:
                $result = 'Error: Unknown operation';
        }
        
        return [
            'result' => $result,
            'operation' => $operation,
            'a' => $a,
            'b' => $b,
        ];
    }
}

Making MCP Requests

JSON-RPC Request Format

{
    "jsonrpc": "2.0",
    "method": "resource.get",
    "params": {
        "resource": "users",
        "query": {
            "id": 1
        }
    },
    "id": 1
}

Available Methods

  • server.info - Get server information
  • resource.get - Get a resource
  • tool.execute - Execute a tool
  • prompt.get - Get a prompt

Example Response

{
    "jsonrpc": "2.0",
    "result": {
        "data": {
            "id": 1,
            "name": "John Doe",
            "email": "john@example.com"
        },
        "meta": {
            "total": 1,
            "per_page": 15,
            "current_page": 1
        }
    },
    "id": 1
}

SSE Connection

The MCP server supports Server-Sent Events (SSE) for real-time communication. Connect to the SSE endpoint:

const clientId = 'your-client-id';
const eventSource = new EventSource(`/mcp/sse?client_id=${clientId}`);

eventSource.onmessage = (event) => {
    const data = JSON.parse(event.data);
    console.log('Received data:', data);
};

eventSource.addEventListener('error', (event) => {
    console.error('SSE connection error:', event);
    eventSource.close();
});

Testing

composer test

License

The MIT License (MIT). Please see License File for more information.

elliottlawson/mcp-laravel-sdk 适用场景与选型建议

elliottlawson/mcp-laravel-sdk 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 33 次下载、GitHub Stars 达 4, 最近一次更新时间为 2025 年 03 月 22 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 elliottlawson/mcp-laravel-sdk 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 elliottlawson/mcp-laravel-sdk 我们能提供哪些服务?
定制开发 / 二次开发

基于 elliottlawson/mcp-laravel-sdk 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 33
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 4
  • 点击次数: 15
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 4
  • Watchers: 2
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-03-22