Skip to main content

What is an MCP server (advanced overview)

Model Context Protocol (MCP) is a specification that allows AI clients (Claude, Cursor, GitHub Copilot, etc.) to communicate with your application using a standardized protocol. MCP has three primary primitives:
PrimitiveRoleCommon use cases
ToolsFunctions the AI can invokeData manipulation, external API calls, computation
ResourcesContext the AI can readDocumentation, configuration, dynamic data
PromptsReusable templatesStandardized queries, workflow guidance
Building an MCP server with Laravel lets you use the entire Laravel ecosystem — Eloquent, caching, authentication, validation — as-is.
This advanced guide focuses on practical implementation. For a conceptual introduction to MCP, see Intermediate: Laravel MCP.

Installation and setup

1

Install the package

Install the package via Composer.
2

Publish the route file

Use vendor:publish to generate routes/ai.php, where you register your MCP servers.
3

Generate a server class

Create a server class with the Artisan command.
Register your tools, resources, and prompts in the generated app/Mcp/Servers/DatabaseServer.php.
4

Register the server

Register the server to a route in routes/ai.php.
The web server is accessed via HTTP POST. The local server runs as an Artisan command and is used with CLI-based AI clients.

Implementing tools

Tools are functions that AI clients can invoke. You can use Laravel’s service container, validation, and Eloquent directly.

Creating a tool

Implement the handle and schema methods in the generated class.

Defining parameters (schema)

Use the Illuminate\Contracts\JsonSchema\JsonSchema builder in the schema method to define accepted parameters.

Tool annotations

MCP protocol annotations let AI clients assess the safety of a tool.
AnnotationDescription
#[IsReadOnly]Does not modify data
#[IsDestructive]Performs a destructive operation such as deletion
#[IsIdempotent]Re-running with the same arguments is safe
#[IsOpenWorld]Communicates with external entities

Structured responses

Use Response::structured to return JSON responses that are easy for AI clients to parse.

Streaming responses

For long-running operations, return a Generator to stream progress updates.
On a web server, streaming responses are automatically sent as SSE (Server-Sent Events) streams.

Conditional registration

You can expose a tool only to users who meet certain conditions.

Implementing resources

Resources are data that AI clients load as context — documents, configuration, or dynamic data.

Static resources

Dynamic resources (URI templates)

URI templates let you serve dynamic resources based on URL parameters.
An AI client requests app://users/42/profile, and the {userId} value is available via $request->get('userId').

Resource annotations

You can explicitly set the priority and audience of a resource.

Implementing prompts

Prompts are reusable templates that AI clients can use to standardize common queries or complex workflows.

Creating a prompt

Using asAssistant() treats the message as a statement from the AI assistant. Combine system prompts and user messages to fine-tune AI behavior.

Authentication and authorization

Token authentication with Sanctum

The simplest approach. MCP clients attach an Authorization: Bearer <token> header.

OAuth 2.1 authentication

Use Laravel Passport for more robust authentication.
When using OAuth, publish the MCP authorization views and configure them in AppServiceProvider.

Custom middleware authentication

If you use your own API tokens, validate the Authorization header in custom middleware.

Authorization inside tools

Use $request->user() inside a tool or resource’s handle method for fine-grained authorization.
shouldRegister only hides the tool from the list. Always perform authorization checks inside the handle method when the tool is actually invoked.

Practical example: database operation tools

A complete implementation of tools that search and create data using Eloquent.

Server class

Search tool (read-only)

Create tool (write)

Practical example: file system tool

A tool that reads files using the Storage facade.
Always sanitize paths in file operation tools to prevent access outside allowed directories. Reject any path containing ...

Testing

MCP servers, tools, resources, and prompts can be unit tested with Laravel’s standard testing features.

Testing tools

Call a tool directly using Server::tool().

Testing resources and prompts

Key assertion methods

MethodDescription
assertOk()Confirms the response has no errors
assertSee($text)Confirms the response contains the given text
assertHasErrors()Confirms the response has errors
assertHasNoErrors()Confirms the response has no errors
assertName($name)Confirms the tool name
assertSentNotification($method, $data)Confirms a notification was sent
assertNotificationCount($count)Confirms the number of notifications sent

Debugging with MCP Inspector

Use MCP Inspector for interactive debugging.

Deployment considerations

HTTP streaming and SSE

If you use streaming responses (Generator) on a web server, verify your server configuration.

Using Laravel Octane

For high-traffic MCP servers, consider Laravel Octane (FrankenPHP or Swoole) to significantly reduce per-request overhead.
With Octane, state is shared between requests. Avoid using static properties or global state inside tools.

Rate limiting

Use the throttle middleware to limit requests to your MCP server.

Caching

Apply caching to frequently called read-only tools.

Logging and monitoring

Log MCP tool calls to track how AI clients are using your server.
In production, use Laravel Telescope or Sentry to monitor MCP server performance and exceptions.
Last modified on April 1, 2026