thakurcoder

July 30, 2025

· 8 min read

Building AI-Powered Applications with Laravel Using the MCP SDK

Learn how to use the Laravel MCP SDK to build MCP servers that allow AI assistants like Claude and ChatGPT to interact with your Laravel application through standardized tools, resources, and prompts.

Introduction

Artificial Intelligence (AI) is transforming the way we build and interact with web applications. From intelligent chatbots to personalized recommendations, AI is becoming an essential component of modern software development. Laravel, one of the most popular PHP frameworks, provides a robust and elegant foundation for building web applications. With the advent of the Model Context Protocol (MCP), developers can now seamlessly integrate AI assistants into their Laravel applications.

The Laravel MCP SDK is a powerful tool that enables developers to build MCP servers directly within their Laravel projects. This allows AI assistants like Anthropic's Claude, Cursor IDE, and OpenAI's ChatGPT to interact with the Laravel backend using standardized interfaces. By exposing tools, resources, and prompts through MCP, developers can create intelligent applications that leverage the capabilities of AI models.

In this blog post, we will explore what the Model Context Protocol is, why you should use the Laravel MCP SDK, and how to get started with it. We will also delve into advanced features and real-world use cases to help you understand how to build AI-powered applications with Laravel.

What is Model Context Protocol (MCP)?

The Model Context Protocol (MCP) is an open standard that defines a communication protocol between AI models and backend services. It allows AI assistants to access and utilize tools, resources, and prompts provided by the backend, enabling a more dynamic and interactive experience.

MCP standardizes the way AI models can request information or perform actions on behalf of users. For example, an AI assistant might need to fetch data from a database, perform a calculation, or retrieve a file. MCP provides a structured way for the AI model to make these requests and receive responses.

Key components of MCP include:

  • Tools: Functions or actions that the AI can call, such as performing a calculation or sending an email.
  • Resources: Data or files that the AI can access, like database records or images.
  • Prompts: Templates or formats for generating text or other outputs.
  • Resource Templates: Predefined structures for resources, helping in consistent data handling.

By using MCP, developers can create backend services that are easily accessible by AI models, fostering a more integrated and efficient development process.

Why Use Laravel MCP SDK?

The Laravel MCP SDK offers several advantages for developers looking to integrate AI into their Laravel applications:

  1. Seamless Integration: The SDK is built specifically for Laravel, providing deep integration with the framework's service container, configuration, caching, logging, and more.
  2. Fluent API: Defining MCP elements is straightforward with the Mcp facade, allowing for an elegant and Laravel-like syntax.
  3. Attribute-Based Discovery: With PHP 8 attributes, developers can define MCP elements directly in their code, which are automatically discovered and cached.
  4. Flexible Transports: Support for multiple transport methods (STDIO, Integrated HTTP, Dedicated HTTP) ensures that the MCP server can be run in various environments, from development to production.
  5. Enterprise-Grade Features: Advanced session management, robust logging, and comprehensive testing utilities make the SDK suitable for large-scale applications.
  6. Standardized Communication: By adhering to the MCP standard, the SDK ensures compatibility with a wide range of AI assistants and tools.

Using the Laravel MCP SDK, developers can focus on building their application's core functionality while leveraging the power of AI to enhance user experiences.

Getting Started with Laravel MCP SDK

To start using the Laravel MCP SDK, follow these steps:

  1. Install the Package:

    composer require php-mcp/laravel
  2. Publish the Configuration:

    php artisan vendor:publish --provider="PhpMcp\Laravel\McpServiceProvider" --tag="mcp-config"

    This will create a config/mcp.php file where you can configure various settings for the MCP server.

  3. Set Up Sessions (Optional):

    If you want to use database sessions, publish the migration:

    php artisan vendor:publish --provider="PhpMcp\Laravel\McpServiceProvider" --tag="mcp-migrations"

    Then run the migration:

    php artisan migrate
  4. Configure the MCP Server:

    Edit the config/mcp.php file to set up server information, capabilities, discovery settings, session management, transports, caching, and logging.

    For example:

    return [
        'server' => [
            'name' => 'My Laravel App',
            'version' => '1.0.0',
            'description' => 'MCP server for my Laravel application',
        ],
        'capabilities' => [
            'tools' => true,
            'resources' => true,
            'prompts' => true,
            'templates' => true,
        ],
        'discovery' => [
            'auto_discover' => true,
        ],
        'session' => [
            'handler' => 'file', // or 'database', 'cache', 'redis'
        ],
        'transports' => [
            'stdio' => [
                'enabled' => true,
            ],
            'http_integrated' => [
                'enabled' => true,
                'route_prefix' => 'mcp',
            ],
            'http_dedicated' => [
                'enabled' => false,
                'host' => '127.0.0.1',
                'port' => 8090,
                'path_prefix' => 'mcp',
            ],
        ],
        // Other configurations...
    ];
  5. Define MCP Elements:

    You can define MCP elements manually in routes/mcp.php or use attributes for automatic discovery.

    For manual definition:

    use PhpMcp\Laravel\Facades\Mcp;
     
    Mcp::tool([CalculatorService::class, 'add'])
        ->name('add')
        ->description('Adds two numbers')
        ->inputSchema(['num1' => ['type' => 'number'], 'num2' => ['type' => 'number']])
        ->outputSchema(['result' => ['type' => 'number']]);

    For attribute-based discovery, define your tools with attributes:

    use PhpMcp\Attributes\McpTool;
    use PhpMcp\Attributes\InputSchema;
    use PhpMcp\Attributes\OutputSchema;
     
    class CalculatorService
    {
        #[McpTool]
        #[InputSchema(['num1' => ['type' => 'number'], 'num2' => ['type' => 'number']])]
        #[OutputSchema(['result' => ['type' => 'number']])]
        public function add($args)
        {
            return ['result' => $args['num1'] + $args['num2']];
        }
    }

    Run php artisan mcp:discover to cache the discovered elements.

  6. Run the MCP Server:

    • For STDIO transport (e.g., for Cursor IDE):

      php artisan mcp:serve --transport=stdio
    • For Integrated HTTP transport:

      Ensure that the route prefix is excluded from CSRF protection if necessary. In Laravel 11+, add 'except' => ['mcp', 'mcp/*'] to your CSRF middleware.

    • For Dedicated HTTP transport:

      php artisan mcp:serve --transport=http --host=0.0.0.0 --port=8091 --path-prefix=mcp_api

      Manage this server with tools like Supervisor or systemd for production use.

With these steps, you can set up a basic MCP server in your Laravel application and start exposing functionality to AI assistants.

Advanced Features

The Laravel MCP SDK offers several advanced features to enhance your AI integration:

  1. Schema Validation:

    Use attributes to define input and output schemas for your tools, ensuring that the data exchanged with AI models is correctly formatted.

    Example:

    #[McpTool]
    #[InputSchema(['username' => ['type' => 'string', 'minLength' => 3]])]
    public function getUser($args)
    {
        // Implementation
    }
  2. Completion Providers:

    Implement completion providers to offer auto-completion suggestions for tool parameters, enhancing the user experience in AI assistants.

    Example:

    use PhpMcp\Server\Completion\CompletionProviderInterface;
     
    class UserIdCompletionProvider implements CompletionProviderInterface
    {
        public function getCompletions(string $prefix): array
        {
            // Return list of user IDs starting with $prefix
        }
    }
  3. Dependency Injection:

    Leverage Laravel's service container to inject dependencies into your MCP handlers, making it easy to use existing services and logic.

    Example:

    use App\Services\CalculatorService;
     
    class McpController extends Controller
    {
        public function __construct(private CalculatorService $calculator)
        {
        }
     
        #[McpTool]
        public function add($args)
        {
            return $this->calculator->add($args['num1'], $args['num2']);
        }
    }
  4. Exception Handling:

    Exceptions thrown in your handlers are automatically converted to JSON-RPC errors, providing a consistent error response format.

  5. Logging:

    Configure logging for MCP requests and responses to monitor and debug your server. Set up a dedicated logging channel in config/logging.php.

    Example configuration in config/mcp.php:

    'logging' => [
        'channel' => 'mcp',
        'level' => 'debug',
    ],

    And in config/logging.php:

    'channels' => [
        'mcp' => [
            'driver' => 'single',
            'path' => storage_path('logs/mcp.log'),
            'level' => 'debug',
        ],
    ],

These advanced features allow you to build robust and maintainable MCP servers that integrate seamlessly with your Laravel application.

Real-World Use Cases

The Laravel MCP SDK opens up a world of possibilities for integrating AI into your applications. Here are some real-world use cases:

  1. AI-Powered Chatbots:

    Build chatbots that can perform actions like fetching data from your database, sending emails, or generating reports, all through natural language interactions.

  2. Intelligent Search:

    Enhance your application's search functionality by allowing AI assistants to query your database or index through MCP tools.

  3. Automated Content Generation:

    Use AI models to generate content such as blog posts, product descriptions, or social media updates based on templates and prompts defined in your Laravel application.

  4. Personalized Recommendations:

    Expose recommendation logic through MCP, allowing AI assistants to provide personalized suggestions to users based on their preferences and behavior.

  5. Data Analysis and Insights:

    Let AI models analyze data stored in your application and provide insights or visualizations through MCP resources and tools.

By leveraging the Laravel MCP SDK, you can create innovative applications that combine the power of AI with the flexibility and robustness of Laravel.

Conclusion

The Laravel MCP SDK is a game-changer for developers looking to integrate AI into their Laravel applications. By providing a standardized and efficient way to expose backend functionality to AI assistants, it bridges the gap between traditional web development and cutting-edge AI technologies.

With its deep integration with Laravel, flexible transport options, and enterprise-grade features, the Laravel MCP SDK empowers developers to build intelligent, responsive, and scalable applications. Whether you're creating chatbots, enhancing search capabilities, or automating content generation, the SDK provides the tools you need to succeed.

Start exploring the Laravel MCP SDK today and unlock the full potential of AI in your Laravel projects. The future of web development is here, and it's powered by intelligent integration between humans and machines.

[[NEWSLETTER]]

References

This blog post provides a comprehensive guide to using the Laravel MCP SDK for integrating AI into Laravel applications, complete with code examples, explanations, and real-world use cases. It is structured to be informative and actionable for developers looking to leverage AI in their projects.