Home / News / Building Powerful AI Tools with Laravel: A Complete Guide to MCP Integration

Building Powerful AI Tools with Laravel: A Complete Guide to MCP Integration

Here’s the sarcastic summary with hashtags related to the topic at the start:
#ModelContextProtocol #Laravel #PHP #LaravelMCP #API #APIintegration #AI-assistants #APItools #Tools #Resources #Validation #Sarcastic #Irony #MCP #PHP-Development #Laravel-Development #PHP-Server #API-Server #PHP-Tools #PHP-REST #PHP-Web #PHP-Web-Services #PHP-Service #PHP-Server-REST #PHP-RESTful #PHP-Web-REST #PHP-Web-RESTful #PHP-Web-REST-API #PHP-Web-REST-API-Integration #PHP-Web-REST-API-Tools #PHP-Web-REST-API-Resources #PHP-Web-REST-API-Validation #PHP-Web-REST-API-Sarcastic #PHP-Web-REST-API-Tools-Sarcastic #PHP-Web-REST-API-Resources-Sarcastic #PHP-Web-REST-API-Validation-Sarcastic #PHP-Web-REST-API-Sarcastic-Tools #PHP-Web-REST-API-Sarcastic-Resources #PHP-Web-REST-API-Sarcastic-Validation #

The Model Context Protocol (MCP) is revolutionizing how AI assistants interact with external systems. While most examples focus on JavaScript/TypeScript implementations, PHP developers have been left wondering how to leverage this powerful protocol in their Laravel applications. Today, I’ll show you how to build a comprehensive MCP server with Laravel that exposes tools, resources, and validation utilities to AI assistants.

What is MCP?

The Model Context Protocol (MCP) is an open protocol developed by Anthropic that enables AI assistants to securely connect to external data sources and tools. Instead of building custom integrations for each AI model, MCP provides a standardized way to expose your application’s functionality to any MCP-compatible AI assistant.

Think of MCP as an API specifically designed for AI agents – it allows them to:

  • Execute functions (tools) with proper input validation
  • Access dynamic resources and data
  • Interact with your application’s business logic safely

Setting Up MCP in Laravel

First, let’s set up the basic Laravel application with the MCP package:

composer create-project laravel/laravel mcp-laravel-demo
cd mcp-laravel-demo
composer require php-mcp/laravel

After installation, publish the MCP configuration:

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

Building Core Services

Let’s start by creating some essential services that will power our MCP tools:

Calculator Service

// app/Services/CalculatorService.php
<?php

namespace App\Services;

class CalculatorService
{
    public function add(float $a, float $b): float
    {
        return $a + $b;
    }

    public function multiply(float $x, float $y): float
    {
        return $x * $y;
    }
}

Email Service

// app/Services/EmailService.php
<?php

namespace App\Services;

use Illuminate\Mail\Mailable;
use Illuminate\Support\Facades\Mail;

class EmailService
{
    public function __invoke(
        string $to,
        string $subject,
        string $message,
        ?string $from = null
    ): array {
        try {
            // In a real application, you'd create a proper Mailable
            Mail::raw($message, function ($mail) use ($to, $subject, $from) {
                $mail->to($to)
                     ->subject($subject);
                if ($from) {
                    $mail->from($from);
                }
            });

            return [
                'success' => true,
                'message' => 'Email sent successfully',
                'to' => $to,
                'subject' => $subject
            ];
        } catch (\Exception $e) {
            return [
                'success' => false,
                'error' => $e->getMessage()
            ];
        }
    }
}

User service

// app/Services/UserService.php
<?php

namespace App\Services;

class UserService
{
    public function getSettings(): array
    {
        return [
            'app_name' => config('app.name'),
            'timezone' => config('app.timezone'),
            'locale' => config('app.locale'),
            'debug' => config('app.debug'),
        ];
    }

    public function getUserProfile(string $userId): array
    {
        // In a real application, you'd fetch from database
        return [
            'id' => $userId,
            'name' => "User {$userId}",
            'email' => "user{$userId}@example.com",
            'created_at' => now()->toISOString(),
        ];
    }
}

Prompt Service

// app/Services/PromptService.php
<?php

namespace App\Services;

class PromptService
{
    public function generate_prompt(string $context): string
    {
        $templates = [
            'business' => "Welcome to our professional platform! We're here to help you achieve your business goals with {$context}.",
            'casual' => "Hey there! Great to see you here. Let's explore {$context} together!",
            'technical' => "Welcome to the system. You now have access to {$context} functionality.",
        ];

        $style = array_rand($templates);
        return $templates[$style];
    }
}

Registering MCP Tools and Resources

Now comes the exciting part – registering our services as MCP tools and resources in routes/mcp.php:

// === VALIDATION TOOLS ===

// Email validation
Mcp::tool(function (string $email): array {
    $isValid = filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
    return [
        'email' => $email,
        'is_valid' => $isValid,
        'domain' => $isValid ? explode('@', $email)[1] : null,
    ];
})
    ->name('validate_email')
    ->description('Validate email address and extract domain');

// Phone validation with country support
Mcp::tool(function (string $phone, string $country = 'FR'): array {
    $cleaned = preg_replace('/[^0-9+]/', '', $phone);
    $patterns = [
        'FR' => '/^(\+33|0)[1-9](\d{8})$/',
        'US' => '/^(\+1)?[2-9]\d{2}[2-9]\d{6}$/',
        'UK' => '/^(\+44|0)[1-9]\d{8,9}$/',
    ];

    $pattern = $patterns[$country] ?? $patterns['FR'];
    $isValid = preg_match($pattern, $cleaned);

    return [
        'phone' => $phone,
        'cleaned' => $cleaned,
        'is_valid' => (bool) $isValid,
        'country' => $country,
    ];
})
    ->name('validate_phone')
    ->description('Validate phone number for different countries');

// JSON validation and parsing
Mcp::tool(function (string $jsonString): array {
    json_decode($jsonString);
    $error = json_last_error();

    return [
        'json' => $jsonString,
        'is_valid' => $error === JSON_ERROR_NONE,
        'error' => $error !== JSON_ERROR_NONE ? json_last_error_msg() : null,
        'parsed' => $error === JSON_ERROR_NONE ? json_decode($jsonString, true) : null,
    ];
})
    ->name('validate_json')
    ->description('Validate JSON string and parse it');

// URL validation with component extraction
Mcp::tool(function (string $url): array {
    $isValid = filter_var($url, FILTER_VALIDATE_URL) !== false;
    $parsed = $isValid ? parse_url($url) : null;

    return [
        'url' => $url,
        'is_valid' => $isValid,
        'scheme' => $parsed['scheme'] ?? null,
        'host' => $parsed['host'] ?? null,
        'path' => $parsed['path'] ?? null,
        'is_https' => ($parsed['scheme'] ?? '') === 'https',
    ];
})
    ->name('validate_url')
    ->description('Validate URL and extract components');

Running Your MCP Server

To start your MCP server, simply run:

php artisan serve --host=127.0.0.1 --port=8000

Connecting with Claude Desktop

To connect your Laravel MCP server with Claude Desktop, add this configuration to your .mcp.json:

{
  "mcpServers": {
    "my-laravel-app": {
      "command": "curl",
      "args": [
        "-X", "POST",
        "-H", "Content-Type: application/json",
        "http://127.0.0.1:8000/mcp"
      ]
    }
  }
}

Testing Your Tools

Once connected, you can test your tools directly with Claude. Here are some examples:

Calculator Tools:

  • “Add 15 and 27 using the add_numbers tool”
  • “Multiply 8.5 by 12.3”

Validation Tools:

  • “Validate this email: user@example.com
  • “Check if this is a valid French phone number: +33123456789”
  • “Validate this JSON: {\”name\”: \”John\”, \”age\”: 30}”

Resource Access:

  • “Show me the current application settings”
  • “Get the current server time”
  • “Fetch the profile for user ID 123”

Email Functionality:

  • “Send an email to test@example.com with subject ‘Hello’ and message ‘This is a test'”

Key Benefits

This Laravel MCP integration provides several advantages:

  1. Type Safety: Laravel’s strong typing ensures tools receive properly validated inputs
  2. Extensibility: Easy to add new tools by creating services and registering them
  3. Resource Management: Dynamic resources allow AI agents to access real-time data
  4. Validation Layer: Built-in validation tools help AI agents verify data integrity
  5. Laravel Ecosystem: Leverage all of Laravel’s features (Eloquent, Cache, Queue, etc.)

Real-World Applications

This setup opens up numerous possibilities:

  • Customer Support: AI agents can access user data, send emails, and validate information
  • Data Processing: Validate and transform data through AI-powered workflows
  • Content Management: AI can access and manipulate your application’s content
  • Business Logic: Expose complex business operations as simple tools for AI agents

Conclusion

MCP bridges the gap between AI assistants and your Laravel applications, creating powerful automation possibilities. By exposing your application’s functionality through standardized tools and resources, you enable AI agents to interact with your business logic safely and efficiently.

The complete code for this tutorial is available on GitHub, and I encourage you to experiment with additional tools and resources based on your specific needs.

What will you build with MCP and Laravel? The possibilities are endless !

Tagged:

Leave a Reply

Your email address will not be published. Required fields are marked *