Download the PHP package chaoticingenuity/laravel-mcp-server without Composer
On this page you can find all versions of the php package chaoticingenuity/laravel-mcp-server. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download chaoticingenuity/laravel-mcp-server
More information about chaoticingenuity/laravel-mcp-server
Files in chaoticingenuity/laravel-mcp-server
Package laravel-mcp-server
Short Description Model Context Protocol (MCP) server implementation for Laravel
License MIT
Informations about the package laravel-mcp-server
Laravel MCP Server
A Laravel package that implements the Model Context Protocol (MCP) server specification, enabling AI models to interact with your Laravel application through a standardized protocol.
Features
- ✅ Full MCP 2024-11-05 protocol implementation
- ✅ Tool and Resource support with JSON-RPC 2.0
- ✅ Fine-grained permission system with field-level access control
- ✅ Template resources with parameter extraction
- ✅ Multiple authentication methods (API keys, Basic Auth, Bearer tokens)
- ✅ Flexible custom authentication system with database integration
- ✅ Comprehensive security middleware stack
- ✅ Rate limiting with per-client controls and burst protection
- ✅ Performance monitoring and detailed logging
- ✅ Extensible architecture for custom tools/resources
- ✅ Laravel 10+, 11+ and 12+ support
- ✅ Comprehensive test suite
- ✅ Auto-discovery of tools and resources
- ✅ NEW: Advanced permission resolution system with custom resolvers
- ✅ NEW: Enhanced field-level security with data filtering
- ✅ NEW: API key audit logging and usage tracking
- ✅ NEW: Per-key rate limiting with burst protection
- ✅ NEW: Security enhancements (key rotation, scope-based permissions)
- ✅ NEW: Performance monitoring and metrics tracking
Installation
Install the package via Composer:
Quick Start
1. Publish Configuration
2. Publish Controllers (Optional)
Note: You only need to publish if you want to customize the MCPController. The middleware classes are used directly from the package namespace.
3. Laravel Version-Specific Setup
Laravel 11+ (including Laravel 12) Setup (Recommended Method)
For Laravel 11+, use the static helper method to register middleware in bootstrap/app.php:
Add the MCP route to your routes/api.php:
Laravel 10 Setup
For Laravel 10, middleware is automatically registered by the service provider. Just ensure your routes/api.php includes the MCP route (same as above).
4. Set Environment Variables
Add to your .env file:
5. Configure Authentication
Choose your authentication strategy:
Option A: Static Configuration (Simple)
Edit config/mcp.php:
Option B: Database Authentication (Recommended)
-
Add MCP support to your User model:
-
Run migrations:
- Enable custom database authenticator:
6. Test the Installation
7. Verification
Check that everything is working:
Advanced Features (v1.1.0+)
Permission Resolution System
The package now includes a flexible permission resolution system that allows custom permission logic:
Enhanced API Key Management
Advanced API key features with audit logging and per-key rate limiting:
Scope-Based Permissions
Implement fine-grained access control with scopes:
Data Filtering & Field Security
Automatically filter response data based on field access permissions:
Performance Monitoring & Analytics
Built-in performance tracking and usage analytics:
Authentication Methods
The package supports multiple authentication strategies that can be used simultaneously:
Static Configuration
Configure static API keys, basic auth, and bearer tokens:
Database Authentication
Store API keys in your database with user relationships:
Custom Authentication
Create your own authentication logic:
Flexible Key Storage Patterns
The package supports multiple API key storage strategies:
Separate Table (Default)
Uses the ApiKey model with foreign key relationships:
User Table Columns
Store hashed keys directly in user table columns:
JSON Column Storage
Store all keys in a single JSON column:
Client Permissions
Configure fine-grained permissions for each client:
Creating Custom Tools
1. Generate Tool Stub
2. Create Your Tool
3. Register Your Tool
Add to config/mcp.php:
Creating Custom Resources
1. Static Resources
2. Template Resources
Resources that accept parameters in the URI:
3. Register Your Resources
Security
Field-Level Access Control
Control which fields clients can access at a granular level:
Middleware Stack
The package includes comprehensive security middleware:
- MCPSecurityMiddleware: HTTPS enforcement, IP whitelisting, security headers
- MCPAuthMiddleware: Multi-method authentication with custom authenticators
- MCPThrottleMiddleware: Rate limiting with per-client and burst controls
- MCPLoggingMiddleware: Request/response logging with performance metrics
Environment-Based Security
IP Whitelisting
Support for both individual IPs and CIDR notation:
Rate Limiting
Configure rate limits globally and per-client:
What's New in v1.0.0 🎉
Enhanced Permission Management
- 🔗 Optional Bouncer Integration: Seamlessly integrate with Laravel Bouncer for advanced role-based permissions
- 🔄 Permission Manager Architecture: Pluggable permission system with automatic fallback
- ⚡ Performance Optimizations: Registry template matching with compiled pattern caching
- 🛡️ Enhanced Security: Improved authentication flow and circular dependency prevention
New Features
- 🚀 MCP Setup Command:
php artisan mcp:setup --bouncerfor easy configuration - 📊 Comprehensive Test Suite: 74 tests covering all major functionality
- 🎛️ Flexible Authentication: Multiple storage patterns for API keys (database, user columns, JSON)
- 📝 Better Documentation: Enhanced examples, troubleshooting guides, and migration instructions
Developer Experience
- ✨ PSR-12 Compliance: Full code formatting standards with .editorconfig
- 🔧 Auto-Detection: Automatic Bouncer package detection and configuration
- 📚 Rich Examples: Comprehensive examples for both basic and Bouncer usage
- 🐛 Improved Error Handling: Better validation and error messages
Quick Setup with Bouncer (Optional)
If you want enhanced permission management with Laravel Bouncer:
Testing
Comprehensive Test Suite (v1.0.0)
The package includes 74 comprehensive tests covering:
- ✅ Core MCP Protocol: Initialize, tools/list, tools/call, resources/*
- ✅ Authentication: API keys, Basic auth, Bearer tokens, custom authenticators
- ✅ Permission Management: Default and Bouncer permission managers
- ✅ Bouncer Integration: Package detection, fallback behavior, configuration
- ✅ Registry Performance: Template matching, caching, memory optimization
- ✅ Security: Access control, rate limiting, validation
- ✅ HTTP Integration: Middleware, routing, error handling
Running Tests
Performance Benchmarks
The v1.0.0 test suite includes performance validation:
- Template URI Matching: 1000 matches complete in <100ms
- Memory Usage: 1000 tool/resource registrations use <5MB
- Authentication: Cached permission lookups for optimal performance
- Registry: Compiled pattern caching for repeated template matches
Running Package Tests
Testing Your Implementation
MCP Protocol Methods
The package implements all standard MCP methods:
| Method | Description | Response |
|---|---|---|
initialize |
Initialize MCP session | Server capabilities and info |
tools/list |
List available tools | Array of tool definitions |
tools/call |
Execute a tool | Tool execution result |
resources/list |
List available static resources | Array of resource definitions |
resources/read |
Read resource content | Resource content |
resources/templates/list |
List template resources | Array of template definitions |
Error Handling
The package provides standardized JSON-RPC 2.0 error responses:
| Code | Meaning | When Used |
|---|---|---|
-32001 |
Authentication required | Invalid/missing credentials |
-32002 |
Access denied | Insufficient permissions |
-32003 |
Rate limit exceeded | Too many requests |
-32602 |
Invalid params | Missing/invalid parameters |
-32603 |
Internal error | Server-side errors |
Exception Types
The package uses specific exception types for better error handling:
MCPAuthenticationException: Thrown for authentication failures, invalid client IDs, or authorization issues- Client ID Validation: Client IDs must be alphanumeric with dots, hyphens, or underscores only (max 255 chars)
Input Validation
Client IDs are automatically validated and must meet these requirements:
- Non-empty
- Maximum 255 characters
- Only alphanumeric characters, dots (.), hyphens (-), and underscores (_)
- Invalid characters will throw
MCPAuthenticationException
Example error response:
Performance Considerations
Caching Strategies
Implement intelligent caching in your custom tools and resources:
Database Optimization
- Use appropriate indexes for your search fields
- Implement field selection based on access permissions
- Consider read replicas for heavy MCP usage
- Use
select()to limit returned columns
Authentication Performance
- Database authenticators use intelligent caching
- Cache duration is configurable per environment
- Failed authentication attempts are rate limited
- Async updates (last_used_at) don't block requests
Monitoring
Use the built-in logging to monitor performance:
User Management
Creating API Keys for Users
User Permission Management
Bulk Operations
Deployment
Production Checklist
- [ ] Set
MCP_DEBUG_*variables tofalse - [ ] Use strong API keys (32+ characters)
- [ ] Configure rate limits appropriate for your infrastructure
- [ ] Enable HTTPS (
MCP_REQUIRE_HTTPS=true) - [ ] Set up IP whitelisting if applicable
- [ ] Configure proper logging levels
- [ ] Set up log rotation for MCP logs
- [ ] Test all middleware is properly registered
- [ ] Verify error responses don't expose sensitive information
- [ ] Set up monitoring for MCP endpoints
- [ ] Configure database indexes for API key lookups
- [ ] Test authentication performance under load
Environment Variables
Docker
Database Indexes
Create proper indexes for optimal performance:
Load Balancing
MCP servers are stateless and can be load balanced normally. Consider:
- Session affinity not required
- Rate limiting may need shared storage (Redis)
- Resource caching benefits from shared cache
- Log aggregation for monitoring across instances
- Database connection pooling for authentication
Monitoring Setup
Troubleshooting
Common Issues
Middleware Not Found Error
Tool/Resource Not Found
Database Authentication Issues
Client ID Validation Errors
Field Access Issues
Access Denied Errors
Rate Limit Issues
Debug Mode
Enable debug mode for development:
Check logs for detailed information:
Performance Debugging
Monitor and optimize performance:
Testing Authentication
Laravel Version Compatibility
Laravel 11
- ✅ Fully supported
- ⚠️ Requires manual middleware registration in
bootstrap/app.php - ✅ Uses new application structure
- ✅ Follows Laravel 11 conventions
Laravel 10
- ✅ Fully supported
- ✅ Automatic middleware registration
- ✅ Traditional
app/Http/Kernel.phpstructure
Migration from Laravel 10 to 11
If upgrading your Laravel application:
- Update middleware registration in
bootstrap/app.php - Remove any manual middleware registration from
app/Http/Kernel.php - Test all MCP endpoints still work
- Update any custom middleware following Laravel 11 patterns
Advanced Configuration
Custom Context Factory
Create custom client context logic:
Multi-Tenant Support
Configure MCP for multi-tenant applications:
Custom Schema Validation
Add JSON Schema validation for tool inputs:
Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Add tests for new functionality
- Ensure all tests pass (
composer test) - Follow PSR-12 coding standards (
composer format) - Update documentation as needed
- Submit a pull request
Development Setup
Package Structure
License
MIT License - see LICENSE file for details.
Changelog
See CHANGELOG.md for version history.
Support
- Documentation: GitHub Wiki
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Security Issues: Email [email protected]
Credits
- Model Context Protocol Specification
- Laravel Framework
- JSON-RPC 2.0 Specification
- All contributors who have helped improve this package
Related Packages
- Laravel Sanctum: For API token authentication
- Laravel Passport: For OAuth2 authentication
- Laravel Telescope: For debugging and monitoring
- Laravel Horizon: For queue monitoring
- Spatie Laravel Permission: For role-based permissions
All versions of laravel-mcp-server with dependencies
illuminate/contracts Version ^10.0|^11.0|^12.0
illuminate/support Version ^10.0|^11.0|^12.0
illuminate/http Version ^10.0|^11.0|^12.0
illuminate/database Version ^10.0|^11.0|^12.0