# Build an MCP Server in Laravel with the Official PHP SDK

> A tested walkthrough of the official MCP PHP SDK inside Laravel: attribute-based tools, stdio and Streamable HTTP, and connecting Claude Code.

*2026-10-15T14:50:47Z*

# Build an MCP Server in Laravel with the Official PHP SDK

The Model Context Protocol (MCP) lets AI agents such as Claude Code, Cursor or ChatGPT discover and call tools in your app. If your app is Laravel, you can expose real Eloquent queries as MCP tools in about 30 lines.

**The short answer:** install `mcp/sdk`, put PHP attributes (`#[McpTool]`, `#[McpResource]`) on plain class methods, build a server with `Server::builder()` using Laravel's container, then run it from an Artisan command (stdio) or a route (Streamable HTTP). Everything below was tested on Laravel 13.36 and PHP 8.4 with `mcp/sdk` v0.8.1.

## Which package: `mcp/sdk` or `laravel/mcp`?

There are two good options, and it's worth picking on purpose:

- **`mcp/sdk`** is the official PHP SDK, maintained by the PHP Foundation and Symfony under the `modelcontextprotocol` GitHub org. It's framework-agnostic and is still marked **experimental**, so pin the version.
- **`laravel/mcp`** is Laravel's first-party package. It has Artisan generators (`make:mcp-server`, `make:mcp-tool`), a `routes/ai.php` file with `Mcp::web()` and `Mcp::local()`, and an `mcp:inspector` command. If you only ever target Laravel, it's the more "Laravel-shaped" choice.

This guide uses the official SDK. It's the reference implementation of the spec, the same code works in Symfony or plain PHP, and you see exactly what's happening.

## Step 1: Install

```bash
composer require mcp/sdk symfony/finder
# only needed for the HTTP transport
composer require symfony/psr-http-message-bridge nyholm/psr7
```

`symfony/finder` is used by attribute discovery. The PSR-7 bridge lets a Laravel route receive a `ServerRequestInterface`.

## Step 2: Write tools as plain methods

Create `app/Mcp/UserTools.php`:

```php
<?php

namespace App\Mcp;

use App\Models\User;
use Mcp\Capability\Attribute\McpResource;
use Mcp\Capability\Attribute\McpTool;

class UserTools
{
    /** Count the registered users. */
    #[McpTool(name: 'count_users')]
    public function countUsers(): int
    {
        return User::count();
    }

    /**
     * Find a user by email and return their public profile.
     *
     * @param string $email The user's email address
     */
    #[McpTool(name: 'find_user')]
    public function findUser(string $email): array
    {
        $user = User::where('email', $email)->first();

        return $user
            ? $user->only(['id', 'name', 'email', 'created_at'])
            : ['error' => "No user with email {$email}"];
    }

    #[McpResource(uri: 'app://config/name', name: 'app_name', mimeType: 'text/plain')]
    public function appName(): string
    {
        return config('app.name');
    }
}
```

The docblock does real work here. The SDK builds the tool description and the JSON input schema from it, so `find_user` is advertised with a required string `email` and its description. Write docblocks for the model, not just for humans.

## Step 3: Build the server once

Both transports need the same server, so put it in a factory. `app/Mcp/ServerFactory.php`:

```php
<?php

namespace App\Mcp;

use Mcp\Server;
use Mcp\Server\Session\FileSessionStore;

class ServerFactory
{
    public static function make(): Server
    {
        return Server::builder()
            ->setServerInfo(config('app.name').' MCP', '1.0.0')
            ->setContainer(app())
            ->setDiscovery(base_path(), ['app/Mcp'])
            ->setSession(new FileSessionStore(storage_path('framework/mcp-sessions')))
            ->build();
    }
}
```

What each line does:

- `setContainer(app())`: Laravel's container is PSR-11, so tool classes are resolved through it, and constructor injection works.
- `setDiscovery()`: scans `app/Mcp` for attributes. You can also register tools by hand with `addTool()`.
- `setSession()`: HTTP is stateless between requests, so MCP sessions need a store. A file store under `storage/` is fine to start with.

## Step 4a: Run over stdio (local agents)

`app/Console/Commands/McpServe.php`:

```php
<?php

namespace App\Console\Commands;

use App\Mcp\ServerFactory;
use Illuminate\Console\Command;
use Mcp\Server\Transport\StdioTransport;

class McpServe extends Command
{
    protected $signature = 'mcp:serve';

    protected $description = 'Run the MCP server over stdio';

    public function handle(): int
    {
        return ServerFactory::make()->run(new StdioTransport());
    }
}
```

Connect it to Claude Code from the project root:

```bash
claude mcp add --transport stdio laravel-app -- php artisan mcp:serve
```

Everything after `--` is the command Claude Code starts. Add `--scope project` to share it with your team through `.mcp.json`. The default scope is `local`.

## Step 4b: Run over HTTP (remote agents)

Append this to `routes/web.php`:

```php
Route::match(['GET', 'POST', 'DELETE'], '/mcp', function (Psr\Http\Message\ServerRequestInterface $request) {
    return App\Mcp\ServerFactory::make()->run(
        new Mcp\Server\Transport\StreamableHttpTransport($request)
    );
})->withoutMiddleware(Illuminate\Foundation\Http\Middleware\PreventRequestForgery::class);
```

Two gotchas I hit while testing:

1. **CSRF.** Agents don't send a CSRF token, so the first POST returns `419`. In Laravel 13 the middleware is `PreventRequestForgery`. In Laravel 12 it's `ValidateCsrfToken`. Better still, put the route in `routes/api.php`, which has no CSRF middleware.
2. **PSR-7.** Without `symfony/psr-http-message-bridge` and `nyholm/psr7`, Laravel can't inject `ServerRequestInterface`.

Then connect:

```bash
claude mcp add --transport http laravel-app https://your-app.test/mcp
```

## Step 5: Test it without an agent

You can smoke-test the HTTP endpoint with curl. The `initialize` response returns an `Mcp-Session-Id` header that you send back on later calls:

```bash
curl -i -X POST http://127.0.0.1:8000/mcp \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"curl","version":"1"}}}'
```

In my run, `initialize` returned `200` with the session header, `notifications/initialized` returned `202`, `tools/list` listed `count_users` and `find_user` with the generated schema, and `tools/call` on `find_user` returned the user's profile as text plus `structuredContent`.

## Honest limits

- **The SDK is experimental.** The API may change before 1.0. Pin `mcp/sdk` and read the changelog when you upgrade.
- **No auth in this example.** A public `/mcp` route that can query users is a data leak. Put it behind Sanctum tokens or the SDK's OAuth support, and scope tools to the caller's tenant.
- **Tools should be small and boring.** One clear action per tool, validated input, no "run any query" tool.

## FAQ

**Does it work with Filament?** Yes. Tools are plain PHP methods, so they can call the same models, policies and actions your Filament resources use.

**stdio or HTTP?** Use stdio for local developer tools, and HTTP for anything another machine or a hosted agent needs to reach.

## Next steps

- How to scope, secure and launch an MCP server for a real product: [Ship an official MCP server for your SaaS in 2 weeks](https://fadymondy.com/en/blog/ship-official-mcp-server-for-saas-in-2-weeks).
- Want a team to build it into your Laravel or Filament product? [White-label Laravel & Filament development](https://fadymondy.com/en/services/white-label-laravel-filament?utm_source=tomatophp&utm_medium=referral&utm_campaign=seo-content-oct26).

---

Source: https://tomatophp.com/en/blog/laravel-mcp-server-official-php-sdk
