Sponsored by Deepsite.site

MCP SDK for Laravel

Created By
ronydebnath6 months ago
WIP - Model Context Protocol (MCP) SDK for Laravel. A robust, extensible Laravel package that implements the Model Context Protocol (MCP) for building AI-driven conversational applications.
Content

Latest Version on Packagist

MCP SDK for Laravel

A Laravel package for interacting with Model Context Protocol (MCP) servers and implementing MCP servers.

Installation

You can install the package via composer:

composer require ronydebnath/mcp-sdk

The package will automatically register its service provider.

You can publish the config file with:

php artisan vendor:publish --provider="Ronydebnath\MCP\MCPServiceProvider" --tag="config"

This will create a config/mcp.php file in your config directory.

Configuration

The package configuration file includes settings for both client and server functionality:

return [
    'default' => env('MCP_CONNECTION', 'default'),
    
    'connections' => [
        'default' => [
            'host' => env('MCP_HOST', 'localhost'),
            'port' => env('MCP_PORT', 8000),
            'timeout' => env('MCP_TIMEOUT', 30),
            'verify' => env('MCP_VERIFY_SSL', true),
        ],
    ],

    'server' => [
        'session_expiry' => env('MCP_SESSION_EXPIRY', 60),
        'max_connections' => env('MCP_MAX_CONNECTIONS', 100),
        'allowed_origins' => explode(',', env('MCP_ALLOWED_ORIGINS', '*')),
    ],

    'auth' => [
        'token_expiry' => env('MCP_TOKEN_EXPIRY', 60),
        'token_length' => env('MCP_TOKEN_LENGTH', 32),
    ],

    'memory' => [
        'max_size' => env('MCP_MEMORY_MAX_SIZE', 100),
        'persist' => env('MCP_MEMORY_PERSIST', false),
        'storage_path' => env('MCP_MEMORY_STORAGE_PATH', storage_path('app/mcp/memory')),
    ],

    'message' => [
        'default_type' => 'text',
        'max_length' => env('MCP_MAX_MESSAGE_LENGTH', 4096),
    ],
];

Using the MCP Client

Using Dependency Injection

use Ronydebnath\MCP\Client\MCPClient;
use Ronydebnath\MCP\Types\Message;
use Ronydebnath\MCP\Types\Role;

class YourController
{
    public function __construct(private MCPClient $client)
    {}

    public function handle()
    {
        $message = new Message(
            role: Role::USER,
            content: 'Hello, how are you?',
            type: 'text'
        );

        $response = $this->client->send($message);
    }
}

Using the Facade

use Ronydebnath\MCP\Facades\MCP;
use Ronydebnath\MCP\Types\Message;
use Ronydebnath\MCP\Types\Role;

$message = new Message(
    role: Role::USER,
    content: 'Hello, how are you?',
    type: 'text'
);

$response = MCP::send($message);

Sending Multiple Messages

use Ronydebnath\MCP\Client\MCPClient;
use Ronydebnath\MCP\Types\Message;
use Ronydebnath\MCP\Types\Role;

$messages = [
    new Message(role: Role::USER, content: 'First message', type: 'text'),
    new Message(role: Role::USER, content: 'Second message', type: 'text'),
];

$responses = $client->sendMultiple($messages);

Using Streaming

use Ronydebnath\MCP\Client\StreamingMCPClient;
use Ronydebnath\MCP\Types\Message;
use Ronydebnath\MCP\Types\Role;

// Using Dependency Injection
class YourController
{
    public function __construct(private StreamingMCPClient $client)
    {}

    public function handle()
    {
        $message = new Message(
            role: Role::USER,
            content: 'Hello, how are you?',
            type: 'text'
        );

        $this->client->stream($message, function ($chunk) {
            // Handle each chunk of the response
            echo $chunk['content'];
        });
    }
}

// Using the Facade
MCP::stream($message, function ($chunk) {
    echo $chunk['content'];
});

// Streaming multiple messages
$messages = [
    new Message(role: Role::USER, content: 'First message', type: 'text'),
    new Message(role: Role::USER, content: 'Second message', type: 'text'),
];

$client->streamMultiple($messages, function ($chunk) {
    echo $chunk['content'];
});

Using the MCP Server

Setting Up Routes

Add the following route to your routes/api.php:

use Ronydebnath\MCP\Server\MCPServer;

Route::post('/mcp', function (Request $request, MCPServer $server) {
    return $server->handle($request);
});

Registering Message Handlers

use Ronydebnath\MCP\Server\MCPServer;
use Ronydebnath\MCP\Types\Message;
use Ronydebnath\MCP\Types\Role;

$server->registerHandler('text', function (Message $message) {
    return [
        'role' => Role::ASSISTANT->value,
        'content' => 'This is a response to: ' . $message->content,
        'type' => 'text',
    ];
});

Using Authentication

The package includes built-in authentication support:

use Ronydebnath\MCP\Server\Auth\AuthMiddleware;
use Ronydebnath\MCP\Server\Auth\AuthProvider;

// Generate a token
$token = $authProvider->generateToken();

// Register the authentication middleware
$server->registerMiddleware(function ($request) use ($authMiddleware) {
    return $authMiddleware->handle($request);
});

Clients can authenticate using either:

  1. Bearer token in the Authorization header:
Authorization: Bearer your-token-here
  1. Token as a query parameter:
/mcp?token=your-token-here

Handling Streaming Requests

The server automatically handles streaming requests when the client sets the Accept: text/event-stream header. The server will:

  1. Create a new session or use an existing one
  2. Send an initial connection message
  3. Stream response chunks as they become available
  4. Maintain the session for the duration of the connection

Memory and Context Management

The package includes memory and context management for maintaining conversation state:

Using Memory

use Ronydebnath\MCP\Shared\Memory;
use Ronydebnath\MCP\Types\Message;
use Ronydebnath\MCP\Types\Role;

$memory = app(Memory::class);

// Add messages to memory
$memory->add(new Message(
    role: Role::USER,
    content: 'Hello',
    type: 'text'
));

// Get messages by role
$userMessages = $memory->getByRole(Role::USER);

// Get messages by type
$textMessages = $memory->getByType('text');

// Clear memory
$memory->clear();

Using Context

use Ronydebnath\MCP\Shared\Context;
use Ronydebnath\MCP\Types\Message;
use Ronydebnath\MCP\Types\Role;

$context = app(Context::class);

// Set context data
$context->set('user_id', 123);
$context->set('preferences', ['theme' => 'dark']);

// Add messages to context
$context->addMessage(new Message(
    role: Role::USER,
    content: 'Hello',
    type: 'text'
));

// Get context data
$userId = $context->get('user_id');
$messages = $context->getMessages();

// Clear context
$context->clear();

Using Progress Tracking

use Ronydebnath\MCP\Shared\Progress;

$progress = app(Progress::class);

// Update progress
$progress->update(50, 'Processing...', ['step' => 'analysis']);

// Increment progress
$progress->increment(10, 'Moving to next step');

// Get progress information
$percentage = $progress->getPercentage();
$status = $progress->getStatus();
$metadata = $progress->getMetadata();

// Check if complete
if ($progress->isComplete()) {
    // Handle completion
}

// Reset progress
$progress->reset();

Testing

composer test

Security

If you discover any security related issues, please email hello[at]ronydebnath.com instead of using the issue tracker.

License

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

Recommend Servers
TraeBuild with Free GPT-4.1 & Claude 3.7. Fully MCP-Ready.
AiimagemultistyleA Model Context Protocol (MCP) server for image generation and manipulation using fal.ai's Stable Diffusion model.
WindsurfThe new purpose-built IDE to harness magic
ChatWiseThe second fastest AI chatbot™
Jina AI MCP ToolsA Model Context Protocol (MCP) server that integrates with Jina AI Search Foundation APIs.
Context7Context7 MCP Server -- Up-to-date code documentation for LLMs and AI code editors
Playwright McpPlaywright MCP server
DeepChatYour AI Partner on Desktop
MCP AdvisorMCP Advisor & Installation - Use the right MCP server for your needs
MiniMax MCPOfficial MiniMax Model Context Protocol (MCP) server that enables interaction with powerful Text to Speech, image generation and video generation APIs.
Zhipu Web SearchZhipu Web Search MCP Server is a search engine specifically designed for large models. It integrates four search engines, allowing users to flexibly compare and switch between them. Building upon the web crawling and ranking capabilities of traditional search engines, it enhances intent recognition capabilities, returning results more suitable for large model processing (such as webpage titles, URLs, summaries, site names, site icons, etc.). This helps AI applications achieve "dynamic knowledge acquisition" and "precise scenario adaptation" capabilities.
Visual Studio Code - Open Source ("Code - OSS")Visual Studio Code
EdgeOne Pages MCPAn MCP service designed for deploying HTML content to EdgeOne Pages and obtaining an accessible public URL.
Serper MCP ServerA Serper MCP Server
CursorThe AI Code Editor
Tavily Mcp
Baidu Map百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
TimeA Model Context Protocol server that provides time and timezone conversion capabilities. This server enables LLMs to get current time information and perform timezone conversions using IANA timezone names, with automatic system timezone detection.
BlenderBlenderMCP connects Blender to Claude AI through the Model Context Protocol (MCP), allowing Claude to directly interact with and control Blender. This integration enables prompt assisted 3D modeling, scene creation, and manipulation.
Howtocook Mcp基于Anduin2017 / HowToCook (程序员在家做饭指南)的mcp server,帮你推荐菜谱、规划膳食,解决“今天吃什么“的世纪难题; Based on Anduin2017/HowToCook (Programmer's Guide to Cooking at Home), MCP Server helps you recommend recipes, plan meals, and solve the century old problem of "what to eat today"
Amap Maps高德地图官方 MCP Server