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

api-platform/mcp

Experimental API Platform MCP component. Integrates the Model Context Protocol (MCP) PHP SDK with API Platform and Symfony’s MCP Bundle. Read-only split from api-platform/core; report issues and PRs in the core repository.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Prerequisites

    • Laravel project using API Platform (v3+) or Symfony.
    • PHP 8.1+ (recommended for MCP SDK compatibility).
    • Install the package (though note the experimental status):
      composer require api-platform/mcp
      
    • Ensure api-platform/core is installed (this package is a read-only split).
  2. First Configuration Register the MCP bundle in config/bundles.php (Symfony) or equivalent Laravel service provider:

    // For Symfony (if using API Platform)
    return [
        ApiPlatform\McpBundle\McpBundle::class => ['all' => true],
    ];
    

    For Laravel, create a service provider to bootstrap MCP:

    // app/Providers/McpServiceProvider.php
    namespace App\Providers;
    
    use Illuminate\Support\ServiceProvider;
    use ApiPlatform\McpBundle\McpBundle;
    
    class McpServiceProvider extends ServiceProvider
    {
        public function register()
        {
            $this->app->register(McpBundle::class);
        }
    }
    

    Register the provider in config/app.php:

    'providers' => [
        // ...
        App\Providers\McpServiceProvider::class,
    ],
    
  3. Enable MCP for a Resource Annotate an API resource class with MCP-specific metadata. Example:

    // src/Entity/Book.php
    use ApiPlatform\Metadata\ApiResource;
    use ApiPlatform\Metadata\Get;
    use ApiPlatform\Mcp\Annotation\McpContext;
    
    #[ApiResource]
    #[McpContext(
        context: "https://example.org/contexts/Book.jsonld",
        types: ["Book"]
    )]
    class Book
    {
        // ...
    }
    
  4. Test the Integration

    • Run the API and verify the response includes MCP headers:
      HTTP/1.1 200 OK
      Content-Type: application/ld+json
      Link: <https://example.org/contexts/Book.jsonld>; rel="http://www.w3.org/ns/hydra/context";
      
    • Use a tool like JSON-LD Playground to validate the response.

Implementation Patterns

Core Workflows

  1. Model Annotation Pattern

    • Use #[McpContext] to define the JSON-LD context and types for each resource.
    • Example for nested resources:
      #[McpContext(
          context: "https://example.org/contexts/Author.jsonld",
          types: ["Author"],
          embedded: ["Book" => "https://example.org/contexts/Book.jsonld"]
      )]
      class Author { ... }
      
  2. Context Resolution

    • MCP automatically resolves @context URIs during serialization. Override resolution logic in a custom context resolver:
      // src/Resolver/CustomContextResolver.php
      use ApiPlatform\Mcp\ContextResolverInterface;
      
      class CustomContextResolver implements ContextResolverInterface
      {
          public function resolve(string $contextUrl): string
          {
              // Custom logic (e.g., cache, remote fetch)
              return file_get_contents($contextUrl);
          }
      }
      
    • Bind the resolver in your service provider:
      $this->app->bind(ContextResolverInterface::class, CustomContextResolver::class);
      
  3. Hybrid API Design

    • Serve both OpenAPI and MCP responses by extending the ApiResource class:
      use ApiPlatform\Metadata\Operation;
      use ApiPlatform\Mcp\Annotation\McpOperation;
      
      #[ApiResource(
          operations: [
              new Get(
                  uriTemplate: '/books/{id}',
                  output: Book::class,
                  name: 'get_book'
              ),
              new McpOperation(
                  uriTemplate: '/books/{id}/mcp',
                  output: Book::class,
                  name: 'get_book_mcp',
                  formats: ['ld+json']
              )
          ]
      )]
      class Book { ... }
      
  4. Validation Layer

    • Add MCP-specific validation using Symfony’s validator:
      use Symfony\Component\Validator\Constraints as Assert;
      use ApiPlatform\Mcp\Validator\Constraints\McpContext;
      
      #[Assert\Valid]
      #[McpContext(
          context: "https://example.org/contexts/Book.jsonld",
          types: ["Book"]
      )]
      class Book { ... }
      

Integration Tips

  • Leverage API Platform’s Hydra Combine MCP with Hydra for richer API documentation:

    # config/packages/api_platform.yaml
    api_platform:
        formats:
            jsonld: ['application/ld+json']
        mcp:
            hydra_context: "https://api-platform.com/contexts/hydra.jsonld"
    
  • Caching Contexts Cache resolved contexts to improve performance:

    use Symfony\Contracts\Cache\CacheInterface;
    
    class CachedContextResolver implements ContextResolverInterface
    {
        public function __construct(private CacheInterface $cache) {}
    
        public function resolve(string $contextUrl): string
        {
            return $this->cache->get($contextUrl, fn() => file_get_contents($contextUrl));
        }
    }
    
  • Laravel-Specific Adaptations

    • Use Laravel’s service container to bind MCP components:
      $this->app->bind(
          \ApiPlatform\Mcp\ContextResolverInterface::class,
          \App\Services\CustomContextResolver::class
      );
      
    • Extend Laravel’s request handling to support MCP headers:
      // app/Http/Middleware/HandleMcpRequests.php
      use ApiPlatform\Mcp\McpRequest;
      
      class HandleMcpRequests
      {
          public function handle($request, \Closure $next)
          {
              if ($request->wantsJsonLd()) {
                  $request = new McpRequest($request->all());
              }
              return $next($request);
          }
      }
      

Gotchas and Tips

Pitfalls

  1. Experimental Status

    • The package is read-only and tied to api-platform/core. Issues/PRs must be submitted to the core repo.
    • No backward compatibility guarantees: MCP spec changes may break your API.
  2. Annotation Overhead

    • MCP annotations (#[McpContext]) are not backward compatible with standard API Platform resources. Refactoring existing models may be required.
    • Tip: Start with a new resource or isolate MCP-enabled endpoints.
  3. Context Resolution Failures

    • If @context URIs are unreachable, MCP will throw exceptions. Always:
      • Mock or stub context resolution in tests.
      • Implement fallback logic for missing contexts:
        public function resolve(string $contextUrl): string
        {
            try {
                return file_get_contents($contextUrl);
            } catch (\Exception $e) {
                // Fallback to a local context
                return file_get_contents(__DIR__.'/fallback-context.jsonld');
            }
        }
        
  4. Performance Bottlenecks

    • Context resolution can add latency. Profile with:
      php -d memory_limit=-1 vendor/bin/debug:profiler
      
    • Tip: Cache resolved contexts aggressively (e.g., Redis).
  5. Tooling Gaps

    • No IDE support: MCP annotations may not be recognized by PHPStorm/PhpCS.
      • Fix: Add custom inspection rules or use @property annotations for hints.
    • Limited validation tools: Manually validate JSON-LD responses with:
      composer require digitalbazaar/jsonld
      
  6. Symfony/Laravel Tensions

    • Laravel’s routing system may conflict with API Platform’s. Ensure:
      • MCP routes are properly namespaced.
      • Use api_platform.route middleware to avoid conflicts:
        Route::middleware(['api_platform.route'])->group(function () {
            // MCP-enabled routes
        });
        

Debugging Tips

  1. Enable MCP Debugging Add this to config/packages/dev/api_platform.yaml:

    api_platform:
        mcp:
            debug: true
    

    This logs context resolution and serialization steps.

  2. Inspect Headers Use telescope or laravel-debugbar to inspect MCP-specific headers:

    Link: <https://example.org/contexts/Book.jsonld>; rel="http://www.w3.org/ns/hydra/context"
    Content-Type: application/ld+json
    
  3. Validate JSON-LD Use the JSON-LD Validator to check responses:

    curl -H "Accept: application/ld+json" http://your-api/books/1 | \
    jq -r . > response.jsonld
    
  4. Common Errors

    • McpContextNotFoundException: The @context URL is invalid. Verify
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity