The Model Context Protocol (MCP)—originally introduced to standardize how Large Language Models securely connect to external data sources and execution environments—has rapidly shifted from experimental prototype infrastructure to core production tooling. If you are building modern agentic workflows, you aren't just writing REST controllers or queuing background jobs anymore; you are exposing domain-specific capabilities to autonomous language models via standard JSON-RPC over stdio or HTTP SSE transports.
However, when you hand an AI agent the ability to execute database queries, dispatch Stripe payouts, or wipe caches directly from your Laravel application, the traditional guardrails of your web application crumble. A typical Laravel application relies on stateful HTTP sessions, CSRF tokens, and middleware tied to human users clicking around a UI. MCP servers, by contrast, operate on stateless, tool-driven execution loops where the caller is an LLM interpreting unstructured natural language prompts.
If you expose a query_database tool globally, an LLM prompt injection attack can trick the model into executing arbitrary SQL commands across your entire database schema.
This guide walks through building a production-grade Laravel MCP Server. We will cover implementing strict per-tool access policies, dynamic parameter validation, robust audit logging, and secure transport handling using modern PHP features.
📋 Table of Contents
- The Architectural Paradigm Shift: Laravel Meets MCP
- 1. Bootstrapping the MCP Transport Layer in Laravel
- 2. Defining Strongly Typed Tools with Attributes
- 3. Per-Tool Authorization and Context-Aware Guards
- 4. Comprehensive Audit Logging for Non-Human Actors
- 5. Handling Stateful Sessions and Multi-Tenant Contexts
- 6. Production Hardening, Timeouts, and Rate Limiting
- Production Architecture Decision Guide
The Architectural Paradigm Shift: Laravel Meets MCP
Before writing any code, it is vital to understand why standard Laravel middleware falls short in an MCP context. In a standard Laravel HTTP lifecycle, the request pipeline looks like this:
[Incoming HTTP Request]
→ EncryptCookies
→ StartSession
→ VerifyCsrfToken
→ Authenticate
→ Controller Action
In an MCP Server running over SSE (Server-Sent Events) or stdio, the communication model is bidirectional and message-oriented. The client (such as Claude Desktop or a custom agent orchestration runner) initializes a session, lists available tools, and then issues tool execution requests containing JSON payloads.
Because tools are invoked dynamically based on what the LLM decides to do during its reasoning loop, authorization cannot rely on a simple auth:sanctum check on a static URL route. Instead, authorization must happen per-tool, per-invocation, inspecting both the identity of the agent caller and the specific parameters passed to the tool.
1. Bootstrapping the MCP Transport Layer in Laravel
To host an MCP server inside a Laravel application, you need a package or custom implementation that translates JSON-RPC 2.0 messages into PHP method calls. While you can write a raw Symfony Process or Ratchet WebSocket wrapper, building it as an Artisan command (for stdio) and an HTTP controller (for SSE) gives you the cleanest integration with Laravel's service container.
Let's set up the core SSE endpoint in a dedicated controller that handles incoming JSON-RPC transport streams.
namespace App\Http\Controllers\Api;
use App\Services\Mcp\McpDispatcher;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpFoundation\StreamedResponse;
class McpServerController extends Controller
{
public function __construct(
protected McpDispatcher $dispatcher
) {}
public function handle(Request $request): JsonResponse|StreamedResponse
{
// Support Server-Sent Events (SSE) transport for remote MCP clients
if ($request->wantsJson() || $request->isMethod('POST')) {
$payload = $request->json()->all();
$response = $this->dispatcher->dispatch(
$payload,
$request->header('X-Agent-Token')
);
return response()->json($response);
}
return response()->stream(function () {
// Keep-alive SSE stream for bidirectional notifications
echo "event: endpoint\n";
echo "data: " . route('mcp.handle') . "\n\n";
while (true) {
if (connection_aborted()) {
break;
}
echo ": ping\n\n";
ob_flush();
flush();
sleep(15);
}
}, 200, [
'Content-Type' => 'text/event-stream',
'Cache-Control' => 'no-cache',
'Connection' => 'keep-alive',
]);
}
}
Why this structure works:
By decoupling the JSON-RPC parsing from the transport mechanism inside McpDispatcher, your core tool definitions remain completely agnostic to whether they are being invoked over a local CLI stdio pipe or a remote authenticated HTTP SSE connection.
💡 Practical note: If you are running your MCP server locally for development (e.g., integrating with Claude Desktop via stdio), wrap your dispatcher in a dedicated Artisan command that reads from
php://stdinand writes tophp://stdout.
2. Defining Strongly Typed Tools with Attributes
One of the most powerful features of modern PHP (8.2+) is native attribute support. Instead of registering tools in a sprawling configuration array, we can use PHP attributes to define tool schemas, descriptions, and parameter constraints directly on invokable classes.
Scenario: You want to expose a tool that allows an AI agent to search customer records, but you need the JSON schema passed to the LLM to strictly match the underlying validation rules without manual duplication.
Solution:
Create a AsMcpTool attribute and pair it with a FormRequest-like parameter object.
namespace App\Attributes;
use Attribute;
#[Attribute(Attribute::TARGET_CLASS)]
class AsMcpTool
{
public function __construct(
public string $name,
public string $description,
public array $tags = []
) {}
}
Now, implement a concrete tool class representing the customer search capability:
namespace App\Mcp\Tools;
use App\Attributes\AsMcpTool;
use App\Models\Customer;
use Illuminate\Support\Facades\Validator;
use InvalidArgumentException;
#[AsMcpTool(
name: 'search_customers',
description: 'Search customer records by email or company name. Restricted to authorized support agents.',
tags: ['crm', 'read-only']
)]
class SearchCustomersTool
{
public function handle(array $arguments, array $context): array
{
// 1. Validate incoming arguments from the LLM
$validator = Validator::make($arguments, [
'query' => ['required', 'string', 'min:2', 'max:100'],
'limit' => ['sometimes', 'integer', 'min:1', 'max:50'],
]);
if ($validator->fails()) {
throw new InvalidArgumentException(
'Invalid tool arguments: ' . json_encode($validator->errors()->all())
);
}
$limit = $arguments['limit'] ?? 15;
// 2. Execute query respecting tenant isolation
$customers = Customer::query()
->where('company_id', $context['tenant_id'])
->where(function ($q) use ($arguments) {
$q->where('email', 'like', "%{$arguments['query']}%")
->orWhere('name', 'like', "%{$arguments['query']}%");
})
->limit($limit)
->get(['id', 'name', 'email', 'status', 'created_at']);
return [
'count' => $customers->count(),
'results' => $customers->toArray(),
];
}
}
Why this works:
LLMs are notoriously creative with data types—they might pass an integer 10 as a string "10", or omit optional parameters entirely. Laravel's validator handles type coercion gracefully when configured correctly, and throwing an InvalidArgumentException allows our dispatcher to catch the error and return a clean, structured JSON-RPC error object back to the model, allowing it to self-correct its tool call arguments in the next turn.
3. Per-Tool Authorization and Context-Aware Guards
This is where standard API authentication breaks down. A typical API token grants access to an entire endpoint group (/api/v1/*). In an MCP server, a single authenticated agent connection might have permission to read CRM data, but zero permission to execute financial transactions or modify database schemas.
Scenario:
Your customer support AI agent needs access to customer search tools, but must be strictly blocked from calling a delete_customer or issue_refund tool, even though both tools live inside the same MCP server instance.
Solution:
Implement a middleware-like authorization pipeline that evaluates attribute-based policies before any tool's handle method is invoked.
namespace App\Services\Mcp;
use App\Attributes\AsMcpTool;
use App\Models\AgentToken;
use Illuminate\Support\Facades\Gate;
use ReflectionClass;
class McpAuthorizationPipeline
{
public function authorize(object $toolInstance, array $context): void
{
$reflection = new ReflectionClass($toolInstance);
$attributes = $reflection->getAttributes(AsMcpTool::class);
if (empty($attributes)) {
return;
}
/** @AsMcpTool $toolAttribute */
$toolAttribute = $attributes[0]->newInstance();
$agentToken = $context['agent_token'] ?? null;
if (!$agentToken instanceof AgentToken) {
throw new \RuntimeException('Unauthorized: No valid agent token provided.');
}
// Check if the token's allowed scopes include this specific tool name or tag
if (!$agentToken->canExecuteTool($toolAttribute->name, $toolAttribute->tags)) {
throw new \RuntimeException(
sprintf('Access Denied: Agent lacks permission to execute tool [%s].', $toolAttribute->name)
);
}
// Secondary check via Laravel Gates for granular resource-level rules
if (Gate::forUser($agentToken)->denies('mcp-execute', [$toolAttribute->name])) {
throw new \RuntimeException(
sprintf('Policy Violation: Execution of [%s] rejected by security policy.', $toolAttribute->name)
);
}
}
}
Why this works:
By extracting the AsMcpTool attribute via reflection right before execution, we enforce a double-lock security model: first checking static token scopes (stored in the database), and second evaluating Laravel's native Gate facade for dynamic, environment-aware rules (e.g., "AI agents cannot execute write operations outside of business hours").
4. Comprehensive Audit Logging for Non-Human Actors
When a human user clicks a button in your application, you have a user ID, an IP address, a session cookie, and standard audit trails. When an autonomous LLM invokes 40 sequential tools in a loop to debug an infrastructure incident, standard audit logs (Auth::id()) will show null, leaving you blind when compliance auditors ask who or what triggered a data export.
Scenario:
An LLM agent misinterprets a customer's prompt and triggers a batch export of sensitive PII records using your export_customer_data tool. You need an unalterable audit trail logging the exact prompt context, raw JSON arguments, model identifier, and execution status.
Solution:
Build a dedicated McpAuditLogger that intercepts every tool invocation asynchronously via Laravel's event dispatcher.
namespace App\Events;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class McpToolExecuted
{
use Dispatchable, SerializesModels;
public function __construct(
public string $toolName,
public array $arguments,
public mixed $result,
public ?array $error,
public array $context,
public float $executionTimeMs
) {}
}
Now, wire up a database event listener to store these events immutably:
namespace App\Listeners;
use App\Events\McpToolExecuted;
use App\Models\McpAuditLog;
class LogMcpToolExecution
{
public function handle(McpToolExecuted $event): void
{
McpAuditLog::create([
'agent_id' => $event->context['agent_token']->id ?? null,
'session_id' => $event->context['session_id'] ?? 'stateless',
'tool_name' => $event->toolName,
'arguments' => json_encode($event->arguments),
'response_summary' => $event->error ? json_encode($event->error) : 'success',
'status' => $event->error ? 'failed' : 'success',
'execution_time_ms' => $event->executionTimeMs,
'ip_address' => $event->context['ip'] ?? null,
'created_at' => now(),
]);
}
}
Inside your McpDispatcher, wrap the tool execution in a timing block and fire the event:
$startTime = microtime(true);
$error = null;
$result = null;
try {
$this->authorizationPipeline->authorize($toolInstance, $context);
$result = $toolInstance->handle($arguments, $context);
} catch (\Throwable $e) {
$error = ['message' => $e->getMessage(), 'code' => $e->getCode()];
throw $e;
} finally {
$duration = (microtime(true) - $startTime) * 1000;
event(new McpToolExecuted(
toolName: $toolName,
arguments: $arguments,
result: $result,
error: $error,
context: $context,
executionTimeMs: round($duration, 2)
));
}
⚠️ Production warning: Never log raw unmasked arguments if tools accept passwords, API keys, or credit card numbers. Implement a recursive sanitization macro on your dispatcher that scrubs keys matching
/password|secret|token|card/ibefore writing to the audit table.
5. Handling Stateful Sessions and Multi-Tenant Contexts
MCP protocol specifications allow for stateful interactions where a client maintains context across multiple tool calls. In a SaaS Laravel application, your MCP server must remain strictly multi-tenant. An agent servicing Tenant A must never bleed data into Tenant B's session.
Scenario: An external developer connects their Claude instance to your Laravel multi-tenant SaaS application via an SSE endpoint. You must inject the correct tenant database connection and user context into the container without relying on global HTTP request singletons.
Solution: Bind contextual scoping into Laravel's container during the JSON-RPC initialization handshake.
namespace App\Services\Mcp;
class McpDispatcher
{
public function dispatch(array $jsonRpcPayload, ?string $tokenString): array
{
// 1. Authenticate agent and resolve tenant
$agentToken = AgentToken::whereToken(hash('sha256', $tokenString))->firstOrFail();
// 2. Establish isolated execution context
$context = [
'agent_token' => $agentToken,
'tenant_id' => $agentToken->tenant_id,
'user_id' => $agentToken->user_id,
'session_id' => $jsonRpcPayload['params']['sessionId'] ?? uniqid('mcp_', true),
];
// 3. Set application-level multi-tenant scopes
app()->instance('mcp.context', $context);
// Set database search path or tenant scope if using multi-tenancy packages (e.g., Stancl Tenancy)
if (class_exists(\Stancl\Tenancy\Tenancy::class)) {
\Stancl\Tenancy\Facades\Tenancy::initialize($agentToken->tenant_id);
}
return $this->executeMethod($jsonRpcPayload, $context);
}
}
Why this works:
By explicitly capturing the tenant identifier from the validated agent token and bootstrapping tenancy packages before tool instantiation, you prevent cross-tenant data leaks that could occur if an LLM hallucinates an ID belonging to a different organization.
6. Production Hardening, Timeouts, and Rate Limiting
Allowing an LLM to trigger backend business logic introduces novel failure modes. An infinite tool-calling loop (where the model repeatedly calls search_customers because it keeps getting empty results) can exhaust your database connection pool in seconds.
To safeguard your production Laravel server, implement three mandatory layers of protection:
- Execution Timeouts: Wrap tool execution in a
pcntl_alarmor a ReactPHP promise timeout to prevent runaway queries from locking worker processes. - Token-Bucket Rate Limiting: Apply Laravel's native
RateLimiterkeyed specifically to the agent token ID rather than IP address. - Payload Size Restrictions: Reject incoming JSON-RPC payloads exceeding 64KB to prevent memory exhaustion attacks.
namespace App\Services\Mcp;
use Illuminate\Support\Facades\RateLimiter;
use Symfony\Component\HttpKernel\Exception\HttpException;
class McpRateLimiter
{
public function enforce(string $agentTokenId, string $toolName): void
{
$key = "mcp:rate-limit:{$agentTokenId}:{$toolName}";
// Allow max 30 calls per minute per tool per agent
if (RateLimiter::tooManyAttempts($key, 30)) {
$seconds = RateLimiter::availableIn($key);
throw new \RuntimeException(
"Rate limit exceeded for tool [{$toolName}]. Try again in {$seconds} seconds."
);
}
RateLimiter::hit($key, 60);
}
}
Production Architecture Decision Guide
When designing how your Laravel application exposes capabilities to AI models, evaluate your transport and security posture against these common trade-offs:
| Dimension | Local Stdio (Claude Desktop) | Remote SSE (Cloud Agent Runner) | WebSockets (Realtime Bi-directional) |
|---|---|---|---|
| Complexity | Low (Single process) | Medium (HTTP state management) | High (Persistent socket scaling) |
| Security Risk | Minimal (Local machine only) | High (Exposed to internet, requires tokens) | High (Requires connection heartbeat auth) |
| Multi-Tenancy | Single user/tenant per CLI | Dynamic tenant switching via headers | Complex session mapping |
| Audit Readiness | Local logs | Centralized database audit table | Distributed stream logging |
| Best Use Case | Local developer debugging & coding | Production SaaS agent integrations | Real-time collaborative agent swarms |
By treating MCP tools with the same rigorous security, validation, and auditing standards you apply to public-facing API endpoints, you can safely bridge the gap between autonomous AI agents and your core Laravel business logic.