Introduction
AI-powered applications are changing how people interact with software. Instead of navigating dashboards, filling out forms, and searching through databases, users can now ask AI assistants to perform tasks using natural language.
For developers, this creates an interesting opportunity: making existing applications accessible to AI agents without rebuilding the entire system.
Imagine you already have a production application with a REST API. It handles customer information, orders, payments, subscriptions, and other business operations. Your team has already invested significant time in authentication, validation, database management, and business logic.
Now, you want an AI assistant to access those same capabilities.
One approach is to build a completely separate AI integration. However, this can lead to duplicated business logic, additional maintenance, and security problems.
A better approach is to introduce the Model Context Protocol (MCP) as an additional interface for your existing application.
MCP provides a standard way for AI applications to discover and interact with external tools and services. Instead of exposing raw API endpoints directly to an AI model, you can create a dedicated MCP server that translates AI tool requests into existing REST API calls.
In this article, I'll explain how to approach this architecture using PHP and Laravel. We'll explore the design, create practical tools, connect them to an existing REST API, and discuss the security and reliability considerations involved in running an MCP server in production.
The main objective is simple: make an existing REST API accessible to AI applications without duplicating the application's core functionality.
Understanding MCP and Its Relationship With REST APIs
Before writing code, it's important to understand the difference between REST APIs and MCP.
A REST API provides an interface that allows applications to exchange data through HTTP requests. Developers interact with endpoints, provide parameters, and process responses.
For example, an e-commerce application might expose these endpoints:
GET /api/customers/{id} GET /api/orders/{id} POST /api/orders POST /api/orders/{id}/cancel GET /api/invoices/{id} A traditional application knows which endpoint to call and what parameters to provide.
AI applications work differently. An AI assistant needs to understand which capabilities are available, what each capability does, and what information it must provide before calling a tool.
This is where MCP becomes useful.
MCP allows a server to expose capabilities through discoverable tools with structured input and output definitions.
For example, instead of asking an AI assistant to understand an HTTP endpoint, you can expose a tool called get_order.
Its input might look like this:
{ "name": "get_order", "description": "Retrieve an order using its unique identifier.", "inputSchema": { "type": "object", "properties": { "order_id": { "type": "integer", "description": "The internal order ID." } }, "required": ["order_id"] } } The AI client can discover this tool and understand how to invoke it.
The MCP server then translates the request into an ordinary REST API call:
GET /api/orders/981 The REST API processes the request and returns the result. The MCP server converts that response into a format suitable for the AI client.
REST API vs MCP Server
| Feature | REST API | MCP Server |
|---|---|---|
| Main purpose | Application communication | AI application integration |
| Interface | HTTP endpoints | Tools, resources and prompts |
| Discovery | API documentation or OpenAPI | Protocol-based discovery |
| Input | Query, path and body parameters | Structured tool arguments |
| Output | HTTP response | MCP content and structured results |
| Primary consumers | Applications and developers | AI hosts and agents |
| Business logic | Application services | Should delegate to existing services |
These technologies are not competitors. They solve different problems and can work together.
The REST API remains responsible for application functionality, while MCP provides an additional interface through which AI applications can access selected capabilities.
Designing the Architecture
The most important architectural decision is determining where the MCP server should sit.
For an existing PHP application, there are two practical approaches.
1. Integrating MCP into the existing application
You can implement MCP tools inside your Laravel application and allow them to communicate directly with existing service classes.
This approach works well when you control the application and want to reuse its dependency injection container, authentication system, and business services.
2. Creating a separate MCP gateway
You can also create an independent PHP service that communicates with your existing REST API.
This approach is useful when the API belongs to an established application, a third-party platform, or a system that you do not want to modify.
For this implementation, we'll focus on the second approach because it demonstrates how to introduce MCP without changing the existing REST API.
Recommended Architecture
AI Application | | MCP Requests | v MCP Server (PHP) | --------------------- | | | v v v Authentication Validation Tool Registry | v REST API Client | | HTTP / JSON | v Existing REST API | v Application Logic | v Database The MCP server should have a limited number of responsibilities:
- Register available tools.
- Describe each tool and its purpose.
- Validate incoming arguments.
- Authenticate incoming requests.
- Check permissions before executing operations.
- Communicate with the existing REST API.
- Transform API responses into structured results.
- Handle errors and record useful logs.
It should not recreate existing business rules.
For example, if your REST API already checks whether an order can be cancelled, the MCP server should not implement another cancellation system. It should call the existing endpoint and return the result.
This keeps the original application as the single source of truth.
Preparing the PHP Environment
For a Laravel-based implementation, you can use Laravel's MCP integration.
Start by creating a Laravel project if you don't already have one:
composer create-project laravel/laravel mcp-gateway cd mcp-gateway Install the Laravel MCP package:
composer require laravel/mcp Publish the required AI routes:
php artisan vendor:publish --tag=ai-routes You can then generate an MCP server:
php artisan make:mcp-server CommerceServer And create individual tools:
php artisan make:mcp-tool GetOrderTool php artisan make:mcp-tool CancelOrderTool These commands provide the starting point for organizing your MCP implementation.
The exact available commands and method signatures should match the Laravel MCP package version installed in your project.
Configure the Existing REST API
The MCP server needs to know where the existing API is located and how to authenticate with it.
Add the following environment variables:
COMMERCE_API_URL=https://api.example.com COMMERCE_API_TOKEN=your-internal-service-token Register these values in your Laravel configuration:
// config/services.php 'commerce' => [ 'url' => env('COMMERCE_API_URL'), 'token' => env('COMMERCE_API_TOKEN'), ], Keeping credentials in environment-based configuration makes it easier to use different API credentials across development, staging, and production.
Never commit real API tokens to your repository.
Building a Central REST API Client
Before creating individual MCP tools, I recommend building a reusable HTTP client.
This is an important design decision because every tool may need to communicate with the same REST API.
Without a shared client, developers often end up repeating authentication headers, timeout settings, error handling, and request configuration throughout their codebase.
Create a file named:
app/Services/CommerceApiClient.php Add the following implementation:
<?php namespace App\Services; use Illuminate\Http\Client\PendingRequest; use Illuminate\Http\Client\Response; use Illuminate\Support\Facades\Http; final class CommerceApiClient { private function client(): PendingRequest { return Http::baseUrl( config('services.commerce.url') ) ->acceptJson() ->asJson() ->withToken( config('services.commerce.token') ) ->connectTimeout(3) ->timeout(10); } public function getOrder(int $orderId): Response { return $this->client()->get( "/api/orders/{$orderId}" ); } public function cancelOrder( int $orderId, string $reason, string $idempotencyKey ): Response { return $this->client() ->withHeaders([ 'Idempotency-Key' => $idempotencyKey, ]) ->post( "/api/orders/{$orderId}/cancel", [ 'reason' => $reason, ] ); } } This client provides two operations:
- Retrieve an existing order.
- Request cancellation of an order.
You can add more methods as the integration grows.
For example:
public function getCustomer(int $customerId): Response { return $this->client()->get( "/api/customers/{$customerId}" ); } The benefit is that all downstream communication follows the same configuration.
If the API URL, authentication mechanism, or timeout requirements change, you only need to update the shared client.
Creating Your First MCP Tool
Now that the REST API client is available, we can create an MCP tool.
Let's start with a simple example: retrieving an order.
The objective is to allow an AI assistant to request order information using a natural language instruction.
For example:
Find order number 981 and tell me its current status.
The AI client can identify the get_order tool and provide the required order ID.
Create the following tool:
<?php namespace App\Mcp\Tools; use App\Services\CommerceApiClient; use Illuminate\Contracts\JsonSchema\JsonSchema; use Laravel\Mcp\Request; use Laravel\Mcp\Response; use Laravel\Mcp\Server\Attributes\Description; use Laravel\Mcp\Server\Tool; #[Description( 'Retrieve an order using its internal numeric ID.' )] final class GetOrderTool extends Tool { public function __construct( private readonly CommerceApiClient $api ) {} public function schema(JsonSchema $schema): array { return [ 'order_id' => $schema ->integer() ->description( 'The unique internal order identifier.' ) ->required(), ]; } public function handle(Request $request): Response { $validated = $request->validate([ 'order_id' => [ 'required', 'integer', 'min:1', ], ]); $response = $this->api->getOrder( $validated['order_id'] ); if ($response->status() === 404) { return Response::error( 'The requested order could not be found.' ); } if ($response->failed()) { return Response::error( 'The order service is temporarily unavailable.' ); } $order = $response->json(); return Response::structured([ 'id' => $order['id'], 'status' => $order['status'], 'currency' => $order['currency'], 'total' => (float) $order['total'], ]); } } This example demonstrates the main integration process.
First, the tool defines its input schema. The AI client can discover that the tool requires an integer called order_id.
Next, Laravel validates the incoming argument.
The tool then calls the existing REST API through the shared client.
Finally, it transforms the API response into structured output.
Why Structured Responses Matter
Suppose the existing API returns this JSON:
{ "id": 981, "status": "processing", "currency": "GBP", "total": "139.99", "internal_account_id": 4417, "payment_reference": "private-reference", "customer": { "id": 771, "name": "Jane Smith", "email": "jane@example.com" } } The AI assistant may only need:
{ "id": 981, "status": "processing", "currency": "GBP", "total": 139.99 } Returning only the necessary information has two benefits.
First, the AI receives a cleaner response that is easier to understand.
Second, sensitive internal information remains outside the AI-facing interface.
This is particularly important when connecting business applications containing customer records, payment information, or internal operational data.
Creating an MCP Tool for Write Operations
Reading information is relatively straightforward. However, write operations require additional attention.
Consider an application that allows users to cancel orders.
The existing REST API might expose:
POST /api/orders/981/cancel With the following request body:
{ "reason": "customer_request" } We can expose this operation as an MCP tool named cancel_order.
The tool should define its input requirements clearly:
public function schema(JsonSchema $schema): array { return [ 'order_id' => $schema ->integer() ->description('The order to cancel.') ->required(), 'reason' => $schema ->string() ->enum([ 'customer_request', 'duplicate', 'fraud', ]) ->required(), ]; } The handler can then validate the arguments and call the REST API.
public function handle(Request $request): Response { $validated = $request->validate([ 'order_id' => [ 'required', 'integer', 'min:1', ], 'reason' => [ 'required', 'in:customer_request,duplicate,fraud', ], ]); if (! $request->user()->can('cancel-orders')) { return Response::error( 'You do not have permission to cancel orders.' ); } $idempotencyKey = (string) Str::uuid(); $response = $this->api->cancelOrder( $validated['order_id'], $validated['reason'], $idempotencyKey ); if ($response->status() === 409) { return Response::error( 'This order cannot be cancelled in its current state.' ); } if ($response->failed()) { return Response::error( 'The cancellation request could not be completed.' ); } return Response::structured([ 'order_id' => $response->json('id'), 'status' => $response->json('status'), 'cancelled' => true, ]); } The example assumes the authenticated user and permission policy are available through your MCP request context.
For a production implementation, the idempotency key must remain the same when retrying the same logical cancellation request. Do not generate a new key for every retry. Store or derive a stable operation key and make sure the existing API enforces idempotency.
You should also consider whether the AI assistant needs explicit user confirmation before executing a cancellation.
A tool description can communicate that cancellation is a sensitive action, but descriptions alone do not enforce confirmation. The application must implement the actual approval process.
Registering Tools With the MCP Server
Once the tools are ready, register them with your server.
For example:
<?php namespace App\Mcp\Servers; use App\Mcp\Tools\CancelOrderTool; use App\Mcp\Tools\GetOrderTool; use Laravel\Mcp\Server; use Laravel\Mcp\Server\Attributes\Name; use Laravel\Mcp\Server\Attributes\Version; #[Name('Commerce API')] #[Version('1.0.0')] class CommerceServer extends Server { protected array $tools = [ GetOrderTool::class, CancelOrderTool::class, ]; } You can expose the server through a remote HTTP route:
use App\Mcp\Servers\CommerceServer; use Laravel\Mcp\Facades\Mcp; Mcp::web( '/mcp/commerce', CommerceServer::class )->middleware([ 'auth:sanctum', 'throttle:mcp', ]); This gives your AI client a dedicated MCP endpoint.
The endpoint acts as the entry point for discovering available tools and invoking them.
Keep the registration focused. You don't need to expose every REST endpoint immediately.
Start with a small number of useful operations and expand the tool catalogue as the requirements become clearer.
Connecting MCP to an Existing REST API Securely
Security deserves special attention when an AI application can interact with business systems.
A REST API may have originally been designed for trusted internal applications. Introducing an AI-facing interface creates another access boundary.
There are several important considerations.
1. Authenticate MCP Clients
Don't leave a production MCP endpoint publicly accessible without an appropriate access-control mechanism.
Depending on the environment, you may use:
- OAuth-based authentication.
- Laravel Sanctum.
- A suitable API gateway.
- Service-to-service authentication.
For remote MCP deployments, implement the authentication requirements of the selected transport and protocol version.
2. Avoid Blind Token Forwarding
One common mistake is forwarding the AI client's bearer token directly to the existing REST API.
The token presented to your MCP server should be intended for that server.
Instead, validate the incoming identity and permissions, then use an appropriate downstream credential to access the REST API.
For user-specific operations, the downstream API should receive a properly scoped user identity or delegated credential where appropriate.
3. Apply Least-Privilege Permissions
Different tools should have different permission requirements.
For example:
| MCP Tool | Required Permission |
|---|---|
| get_order | orders:read |
| search_orders | orders:read |
| cancel_order | orders:cancel |
| get_customer | customers:read |
| create_refund | refunds:create |
This prevents a user with read-only access from executing sensitive operations.
4. Validate Every Argument
Never assume that the AI model will always provide valid input.
Even if the MCP schema defines the correct data types, the server must perform its own validation.
For example:
$request->validate([ 'customer_id' => [ 'required', 'integer', 'min:1', ], ]); Also validate resource ownership and tenant boundaries.
A valid customer ID doesn't automatically mean the authenticated user can access that customer.
5. Protect Sensitive Operations
Operations such as deleting records, issuing refunds, cancelling subscriptions, and modifying customer information should receive additional protection.
Consider:
- Explicit approval requirements.
- Permission checks.
- Audit records.
- Idempotency protection.
- Operation limits.
- Clear execution results.
The goal is to make AI-assisted operations predictable and controlled.
Handling Errors and API Failures
Your MCP server depends on another application. Therefore, it must handle situations where the REST API is unavailable or returns unexpected responses.
Consider these common scenarios:
| API Response | Expected MCP Behaviour |
|---|---|
| 200 | Return the requested result |
| 400 | Report an invalid request |
| 401 | Handle authentication failure |
| 403 | Report insufficient permissions |
| 404 | Explain that the resource was not found |
| 409 | Explain a business-state conflict |
| 429 | Apply appropriate rate-limit handling |
| 500 | Return a generic service error |
| 503 | Report temporary unavailability |
Avoid returning raw server exceptions to the AI client.
For example, this is not useful:
SQLSTATE[HY000]: General error... A better response is:
The order service is temporarily unavailable. Please try again later. However, you should preserve detailed error information in internal logs.
Implementing Retry Logic
Temporary network failures can interrupt communication between the MCP server and REST API.
Laravel provides retry functionality through its HTTP client.
For safe read operations, you can use:
$response = Http::retry( [100, 250, 500], throw: false )->get($url); However, retries must be designed carefully.
A GET request can generally be retried when the operation is safe.
A payment or refund request is different. If the first request reaches the server but its response gets lost, retrying without idempotency protection could create a duplicate transaction.
For write operations, use stable idempotency keys and ensure that the existing REST API supports them.
Also avoid retrying every failure. A validation error or permission denial will not become successful simply because the request is repeated.
Improving Performance With Caching
An MCP server may receive repeated requests for the same information.
For example, an AI assistant might request the same product details several times while answering a user's questions.
Making a new REST API request every time can increase response times and downstream server load.
Caching can help.
Laravel provides a convenient cache interface:
public function getProduct(int $productId): array { return Cache::remember( "mcp:product:{$productId}", now()->addMinutes(5), function () use ($productId) { return $this->api ->getProduct($productId) ->throw() ->json(); } ); } This example stores product information for five minutes.
However, caching should depend on the type of information.
Good candidates include:
- Product categories.
- Country lists.
- Currency information.
- Public configuration.
- Stable metadata.
Avoid caching sensitive or rapidly changing information without a clear invalidation strategy.
Payment status, inventory availability, and account permissions often require fresh data.
You should also consider whether a particular response is user-specific. Never share cached private information between users or organisations.
Testing the MCP Server
Before connecting the server to a production AI client, test its functionality independently.
I recommend testing several different layers.
1. Unit Testing
Test individual tools and response transformations.
For example, verify that an order returned by the REST API is correctly converted into structured MCP output.
public function test_order_response_is_mapped_correctly()...

