Laravel MCP
A powerful Laravel package for implementing the Model Context Protocol
Key Features
Laravel MCP provides a robust set of tools and capabilities for seamless integration between Laravel applications and AI models.
Documentation
Get started quickly with our comprehensive documentation and examples.
# Install via Composer
composer require laravelmcp/mcp
# Publish configuration
php artisan vendor:publish --provider="LaravelMCP\MCP\MCPServiceProvider" --tag="config"
# Configure environment
MCP_SERVER_HOST=127.0.0.1
MCP_SERVER_PORT=8080
MCP_SERVER_TRANSPORT=http
Code Examples
Explore practical examples of Laravel MCP in action.
AI-Powered Code Review
use LaravelMCP\MCP\Server\FastMCP;
$mcp = new FastMCP();
// Register code review tool
$mcp->tool('review-code', [
'code' => ['type' => 'string', 'required' => true],
'language' => ['type' => 'string', 'required' => true],
'style' => ['type' => 'string', 'enum' => ['serious', 'fun']]
])(function ($args) use ($mcp) {
// Analyze code and provide AI-powered suggestions
$suggestions = $mcp->prompt('suggest-improvements', [
'code' => $args['code'],
'language' => $args['language']
]);
return [
'suggestions' => $suggestions,
'complexity' => analyzeComplexity($args['code'])
];
});
Resource Management
// Register a file resource
$mcp->resource('file://{path}')(function ($matches) {
return [
'content' => file_get_contents($matches['path']),
'metadata' => [
'size' => filesize($matches['path']),
'modified' => filemtime($matches['path'])
]
];
});
LLM Agent Example
Create a powerful AI agent that can analyze code, suggest improvements, and interact with your Laravel application using the Model Context Protocol.
Complete Agent Implementation
mcp = new FastMCP();
$this->setupAgent();
}
protected function setupAgent(): void
{
// Register code analysis tools
$this->registerCodeAnalysisTools();
// Register file system resources
$this->registerFileResources();
// Register AI prompts
$this->registerPrompts();
// Setup event handlers
$this->setupEventHandlers();
}
protected function registerCodeAnalysisTools(): void
{
// Tool for analyzing code complexity
$this->mcp->tool('analyze-complexity', [
'code' => ['type' => 'string', 'required' => true],
'metrics' => ['type' => 'array', 'items' => ['type' => 'string'], 'default' => ['cyclomatic', 'cognitive']]
])(function ($args) {
return [
'complexity_score' => $this->calculateComplexity($args['code'], $args['metrics']),
'suggestions' => $this->generateSuggestions($args['code'])
];
});
// Tool for checking coding standards
$this->mcp->tool('check-standards', [
'path' => ['type' => 'string', 'required' => true],
'standard' => ['type' => 'string', 'default' => 'PSR12']
])(function ($args) {
return $this->runCodeSniffer($args['path'], $args['standard']);
});
}
protected function registerFileResources(): void
{
// Register project files resource
$this->mcp->resource('project://{path}', [
'path' => ['type' => 'string', 'pattern' => '^[a-zA-Z0-9/_-]+\.[a-zA-Z0-9]+$']
])(function ($matches) {
$fullPath = base_path($matches['path']);
return [
'content' => file_get_contents($fullPath),
'metadata' => [
'size' => filesize($fullPath),
'modified' => filemtime($fullPath),
'type' => pathinfo($fullPath, PATHINFO_EXTENSION)
]
];
});
}
protected function registerPrompts(): void
{
// Register AI code review prompt
$this->mcp->prompt('review-code', [
'code' => ['type' => 'string', 'required' => true],
'context' => ['type' => 'object', 'properties' => [
'language' => ['type' => 'string'],
'framework' => ['type' => 'string'],
'style' => ['type' => 'string', 'enum' => ['detailed', 'summary']]
]]
])(function ($args) {
// First analyze code complexity
$analysis = $this->mcp->tool('analyze-complexity')->call([
'code' => $args['code']
]);
// Check coding standards
$standards = $this->mcp->tool('check-standards')->call([
'path' => $this->saveTemporaryFile($args['code'])
]);
// Generate AI-powered review
return [
'review' => $this->generateAIReview($args['code'], $analysis, $standards),
'complexity' => $analysis['complexity_score'],
'standards_issues' => $standards['issues'],
'suggestions' => $this->prioritizeSuggestions($analysis['suggestions'])
];
});
}
protected function setupEventHandlers(): void
{
// Log all tool calls
$this->mcp->on('tool.called', function ($event) {
Log::info("Tool called: {$event->tool}", [
'args' => $event->args,
'timestamp' => now()
]);
});
// Handle progress updates
$this->mcp->on('progress', function ($progress) {
Log::debug("Analysis progress: {$progress->percentage}%", [
'message' => $progress->message
]);
});
// Handle errors
$this->mcp->on('error', function ($error) {
Log::error("MCP Error: {$error->message}", [
'code' => $error->code,
'context' => $error->context
]);
});
}
public function reviewFile(string $path, array $options = []): array
{
try {
// Read file content using resource
$file = $this->mcp->resource('project://' . $path)->get();
// Send progress update
$this->mcp->sendProgress(25, "Reading file contents");
// Perform code review using prompt
$review = $this->mcp->prompt('review-code')->call([
'code' => $file['content'],
'context' => [
'language' => pathinfo($path, PATHINFO_EXTENSION),
'framework' => 'laravel',
'style' => $options['style'] ?? 'detailed'
]
]);
$this->mcp->sendProgress(100, "Review completed");
return [
'success' => true,
'review' => $review,
'file_info' => $file['metadata']
];
} catch (\Exception $e) {
Log::error("Review failed: " . $e->getMessage());
return [
'success' => false,
'error' => $e->getMessage()
];
}
}
// Helper methods (implementation details omitted for brevity)
protected function calculateComplexity(string $code, array $metrics): array { /* ... */ }
protected function generateSuggestions(string $code): array { /* ... */ }
protected function runCodeSniffer(string $path, string $standard): array { /* ... */ }
protected function generateAIReview(string $code, array $analysis, array $standards): array { /* ... */ }
protected function prioritizeSuggestions(array $suggestions): array { /* ... */ }
protected function saveTemporaryFile(string $content): string { /* ... */ }
}
Usage Example
reviewFile('app/Http/Controllers/UserController.php', [
'style' => 'detailed'
]);
if ($review['success']) {
echo "Review completed successfully!\n";
echo "Complexity Score: " . $review['review']['complexity'] . "\n";
echo "Standards Issues: " . count($review['review']['standards_issues']) . "\n";
// Print suggestions
foreach ($review['review']['suggestions'] as $suggestion) {
echo "- {$suggestion['description']}\n";
}
} else {
echo "Review failed: " . $review['error'] . "\n";
}
Core Components
Explore the building blocks that make Laravel MCP powerful and flexible.
Server Capabilities
Manage server features, experimental flags, and logging configuration.
Client Capabilities
Handle feature flags, root directories, and state management.
Tools Capability
Track and manage tool registration and modifications.
Getting Started
Follow these simple steps to integrate Laravel MCP into your project.
-
Install the Package
composer require laravelmcp/mcp
-
Configure Environment
MCP_SERVER_HOST=127.0.0.1 MCP_SERVER_PORT=8080 MCP_SERVER_TRANSPORT=http
-
Start the Server
php artisan mcp:serve