Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Mcp Laravel Package

laravel/mcp

Build MCP (Model Context Protocol) servers in Laravel so AI clients can securely interact with your app. Expose tools, resources, and prompts using familiar Laravel patterns, with docs and integrations designed for rapid setup and deployment.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require laravel/mcp

Publish the MCP configuration:

php artisan vendor:publish --provider="Laravel\MCP\MCPServiceProvider" --tag="mcp-config"
  1. Register MCP Server: Define a server in config/mcp.php:

    'servers' => [
        'primary' => [
            'uri' => 'https://your-app.com/mcp',
            'port' => env('MCP_PORT', 8000),
            'protocol_version' => '2025-11-25',
        ],
    ],
    
  2. First Use Case: Create a tool using the McpTool trait or attribute:

    use Laravel\MCP\Attributes\Tool;
    
    #[Tool]
    class UserTool
    {
        public function getUser(string $id): array
        {
            return User::findOrFail($id)->toArray();
        }
    }
    

    Register the tool in App\Providers\MCPServiceProvider:

    public function registerTools(): array
    {
        return [
            UserTool::class,
        ];
    }
    
  3. Run the MCP Server:

    php artisan mcp:serve
    

Key Documentation


Implementation Patterns

Core Workflows

1. Tool Development

  • Annotations: Use attributes for declarative tool definitions:
    #[Tool(name: 'search_products', description: 'Search for products in the catalog')]
    class ProductTool
    {
        #[InputSchema(type: 'object', properties: [
            'query' => ['type' => 'string', 'description' => 'Search query']
        ])]
        public function search(string $query): array
        {
            return Product::where('name', 'like', "%{$query}%")->get()->toArray();
        }
    }
    
  • Dynamic Tools: Register tools programmatically:
    MCP::registerTool(new class {
        public function __invoke(array $input): array {
            return SomeService::handle($input);
        }
    });
    

2. Resource Integration

  • Define Resources:
    use Laravel\MCP\Attributes\Resource;
    
    #[Resource(
        uri: '/api/users/{id}',
        description: 'User resource endpoint'
    )]
    class UserResource
    {
        public function get(string $id): array
        {
            return User::findOrFail($id)->toArray();
        }
    }
    
  • Streaming Responses:
    public function streamLogs(string $userId): \Generator
    {
        foreach (Log::where('user_id', $userId)->cursor() as $log) {
            yield $log->toArray();
        }
    }
    

3. Authentication & Authorization

  • OAuth Registration:
    MCP::registerOAuthClient(
        name: 'github',
        redirectUri: 'https://your-app.com/mcp/oauth/callback',
        scopes: ['read:user']
    );
    
  • Role-Based Access:
    use Laravel\MCP\Attributes\Authorize;
    
    #[Authorize(roles: [Role::User])]
    public function sensitiveData(): array
    {
        return [...];
    }
    

4. Testing

  • Mock MCP Server:
    $response = MCP::fake()
        ->tool('get_user', fn($id) => ['id' => $id])
        ->assertToolCalled('get_user', ['1']);
    
  • Inspector Command:
    php artisan mcp:inspect --host=localhost --port=8000
    

Integration Tips

Laravel Ecosystem

  • Use Existing Models: Leverage Eloquent models directly in tools/resources:
    #[Tool]
    class PostTool
    {
        public function createPost(array $data): array
        {
            return Post::create($data)->toArray();
        }
    }
    
  • Validation: Use Laravel’s validation rules in InputSchema:
    #[InputSchema(properties: [
        'title' => ['type' => 'string', 'minLength' => 3],
        'content' => ['type' => 'string', 'maxLength' => 1000]
    ])]
    

Performance

  • Caching: Cache tool responses or resource data:
    public function getCachedData(string $key): array
    {
        return Cache::remember("mcp_{$key}", now()->addHours(1), fn() => $this->fetchData($key));
    }
    
  • Octane Support: MCP works seamlessly with Laravel Octane for high-performance environments.

Extending MCP

  • Custom Middleware:
    MCP::middleware(function ($request, $next) {
        if ($request->input('debug')) {
            \Log::debug('MCP Request', $request->all());
        }
        return $next($request);
    });
    
  • Event Listeners:
    MCP::listen('session.initialized', function ($session) {
        \Log::info("New MCP session started: {$session->id}");
    });
    

Gotchas and Tips

Common Pitfalls

1. Tool Registration

  • Issue: Tools not discovered automatically.
    • Fix: Ensure tools are registered in registerTools() or annotated with #[Tool].
    • Tip: Use php artisan mcp:tools to list registered tools.

2. OAuth Configuration

  • Issue: OAuth registration fails with invalid_redirect_uri.
    • Fix: Verify redirectUri matches the MCP server’s base URL (e.g., https://your-app.com/mcp/oauth/callback).
    • Tip: Use MCP::registerOAuthClient() with absolute URIs.

3. Resource URIs

  • Issue: Resources not found at /mcp/{resource}.
    • Fix: Ensure uri in #[Resource] is relative to the MCP server’s base path (e.g., /api/users/{id} becomes /mcp/api/users/{id}).
    • Tip: Use MCP::resourceUri('users', ['id' => 1]) to generate full URIs.

4. Session Management

  • Issue: Session IDs not persisted.
    • Fix: Use MCP::session() to access the current session or middleware to set custom session data.
    • Tip: Listen to session.initialized to initialize session-specific data.

5. JSON-RPC Errors

  • Issue: Tools return 500 Internal Server Error instead of structured JSON-RPC errors.
    • Fix: Use MCP::error() to throw structured errors:
      if (!$user) {
          MCP::error('user_not_found', 'User not found');
      }
      
    • Tip: Wrap business logic in try-catch blocks to convert exceptions to JSON-RPC errors.

Debugging Tips

1. Inspector Command

  • Use php artisan mcp:inspect to interactively test tools/resources:
    php artisan mcp:inspect --host=localhost --port=8000
    
  • Tip: Inspect tools/resources in real-time without writing tests.

2. Logging

  • Enable MCP logging in config/mcp.php:
    'logging' => [
        'enabled' => true,
        'channel' => 'single',
    ],
    
  • Tip: Check storage/logs/mcp.log for detailed request/response cycles.

3. Testing

  • Fake MCP Server:
    MCP::fake()
        ->tool('search', fn($query) => ['results' => [$query]])
        ->assertToolCalled('search', ['test']);
    
  • Tip: Use MCP::assertStructuredContent() to validate response schemas.

4. Configuration Quirks

  • Dynamic Ports: MCP supports dynamic ports (e.g., localhost:3000) for local development.
  • Protocol Version: Always specify the latest protocol_version in config/mcp.php to avoid compatibility issues.

Extension Points

1. Custom Content Types

  • Add support for custom content types (e.g., PDFs) by extending Laravel\MCP\Content\Content:
    class PdfContent extends Content
    {
        public static function type(): string
        {
            return 'application/pdf';
        }
    
        public function toResponse(): Response
        {
            return response()->file(storage_path("app/{$this->path}"));
        }
    }
    
  • Register the content type in MCPServiceProvider:
    MCP::contentType(PdfContent::class);
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4