DEV Community

Cover image for Building an MCP Server for an Existing REST API: A Practical PHP Approach
Aasim Ghaffar
Aasim Ghaffar

Posted on

Building an MCP Server for an Existing REST API: A Practical PHP Approach

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}
Enter fullscreen mode Exit fullscreen mode

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"]
  }
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Install the Laravel MCP package:

composer require laravel/mcp
Enter fullscreen mode Exit fullscreen mode

Publish the required AI routes:

php artisan vendor:publish --tag=ai-routes
Enter fullscreen mode Exit fullscreen mode

You can then generate an MCP server:

php artisan make:mcp-server CommerceServer
Enter fullscreen mode Exit fullscreen mode

And create individual tools:

php artisan make:mcp-tool GetOrderTool

php artisan make:mcp-tool CancelOrderTool
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Register these values in your Laravel configuration:

// config/services.php

'commerce' => [
    'url' => env('COMMERCE_API_URL'),
    'token' => env('COMMERCE_API_TOKEN'),
],
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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,
                ]
            );
    }
}
Enter fullscreen mode Exit fullscreen mode

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}"
    );
}
Enter fullscreen mode Exit fullscreen mode

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'],
        ]);
    }
}
Enter fullscreen mode Exit fullscreen mode

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"
  }
}
Enter fullscreen mode Exit fullscreen mode

The AI assistant may only need:

{
  "id": 981,
  "status": "processing",
  "currency": "GBP",
  "total": 139.99
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

With the following request body:

{
  "reason": "customer_request"
}
Enter fullscreen mode Exit fullscreen mode

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(),
    ];
}
Enter fullscreen mode Exit fullscreen mode

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,
    ]);
}
Enter fullscreen mode Exit fullscreen mode

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,
    ];
}
Enter fullscreen mode Exit fullscreen mode

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',
]);
Enter fullscreen mode Exit fullscreen mode

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',
    ],
]);
Enter fullscreen mode Exit fullscreen mode

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...
Enter fullscreen mode Exit fullscreen mode

A better response is:

The order service is temporarily unavailable.
Please try again later.
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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();
        }
    );
}
Enter fullscreen mode Exit fullscreen mode

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(): void
{
    $order = [
        'id' => 981,
        'status' => 'processing',
        'currency' => 'GBP',
        'total' => '139.99',
    ];

    $result = OrderMapper::toMcp($order);

    $this->assertSame(981, $result['id']);

    $this->assertSame(
        'processing',
        $result['status']
    );

    $this->assertSame(
        139.99,
        $result['total']
    );
}
Enter fullscreen mode Exit fullscreen mode

This helps identify problems before they affect the actual integration.

2. REST API Integration Testing

Laravel allows you to fake HTTP responses during tests.

For example:

Http::fake([
    'api.example.com/api/orders/981' =>
        Http::response([
            'id' => 981,
            'status' => 'processing',
            'currency' => 'GBP',
            'total' => '139.99',
        ], 200),
]);
Enter fullscreen mode Exit fullscreen mode

You can then invoke the tool and verify that it returns the expected result.

3. Authentication Testing

Test the behaviour of the MCP server with different user permissions.

For example:

Unauthenticated user
    |
    v
get_order
    |
    v
Access denied
Enter fullscreen mode Exit fullscreen mode

And:

Authenticated user with orders:read
    |
    v
get_order
    |
    v
Access granted
Enter fullscreen mode Exit fullscreen mode

Also verify that read-only users cannot access write operations.

4. Failure Testing

Test what happens when the existing REST API returns:

  • 401 authentication errors.
  • 403 permission errors.
  • 404 missing resources.
  • 429 rate limits.
  • 500 server errors.
  • 503 service unavailability.
  • Connection timeouts.
  • Invalid JSON responses.

A production integration should not be considered reliable simply because it works when every request succeeds.

5. Test With an MCP Client

Finally, connect your server to a compatible MCP client.

Verify that the client can:

  1. Connect to the server.
  2. Discover the available tools.
  3. Read their descriptions and input schemas.
  4. Invoke a read operation.
  5. Receive structured output.
  6. Handle an unsuccessful operation correctly.

Also test sensitive operations with the expected approval and permission controls.

Deploying the MCP Server

Once the implementation and testing are complete, you can deploy the MCP server as a separate PHP application or as part of your existing Laravel infrastructure.

A typical deployment architecture might look like this:

              AI Clients
                  |
                  v
            HTTPS Gateway
                  |
                  v
             Load Balancer
                  |
          -------------------
          |        |        |
          v        v        v
        MCP 1    MCP 2    MCP 3
          |        |        |
          -------------------
                  |
                  v
            Existing REST API
                  |
                  v
             Application
Enter fullscreen mode Exit fullscreen mode

For production deployment, consider:

  • HTTPS for all external communication.
  • Secure secret management.
  • Request rate limiting.
  • PHP-FPM and appropriate web-server configuration.
  • Container resource limits.
  • Health and readiness checks.
  • Centralised logging.
  • Monitoring and alerting.
  • Regular dependency updates.
  • Automated deployment pipelines.

The MCP server should also be designed to scale horizontally where necessary.

Avoid relying on hidden in-memory state between requests. Store application state explicitly when it's needed, rather than assuming that consecutive requests will reach the same PHP process.

Monitoring Important Metrics

You should monitor more than whether the MCP endpoint is responding.

Useful metrics include:

Metric Why It Matters
Total MCP requests Measures overall usage
Tool invocation count Shows which tools are being used
Failed tool calls Identifies functional problems
Authentication failures Helps detect access issues
API response time Measures downstream performance
Cache hit rate Shows caching effectiveness
Rate-limit events Identifies excessive usage
Average execution time Helps identify slow tools

You should also use request IDs or distributed tracing to connect an MCP invocation with its corresponding REST API request.

Never log access tokens, API keys, or unnecessary customer information.

Common Mistakes When Building an MCP Server

There are several mistakes worth avoiding when introducing MCP into an existing application.

Exposing every REST endpoint

Just because an endpoint exists doesn't mean an AI assistant needs access to it.

Expose a small set of useful capabilities first.

Duplicating business logic

Don't create a second implementation of existing application rules.

Keep important business decisions inside the original application.

Ignoring permissions

A tool schema is not an authorisation system.

Every operation must enforce the permissions of the authenticated user or service.

Returning complete API responses

Large API responses can expose unnecessary information and make it harder for AI models to identify the important fields.

Return only what the tool needs to provide.

Using retries without idempotency

This is especially dangerous for payments, refunds, and other operations that change application state.

Skipping integration tests

An MCP server may work independently while still failing to communicate correctly with the existing REST API.

Test the complete request and response flow.

Conclusion

Building an MCP server for an existing REST API is a practical way to make established PHP applications accessible to modern AI assistants.

The most important architectural decision is to avoid rebuilding functionality that already exists.

Instead, introduce a thin integration layer that exposes selected REST API capabilities through discoverable MCP tools.

With PHP and Laravel, you can build reusable API clients, define structured tool schemas, validate incoming arguments, enforce permissions, and transform existing API responses into formats that AI applications can understand.

However, making an API accessible to AI is only one part of the implementation. Security, authorisation, idempotency, error handling, testing, and monitoring are equally important.

I would recommend starting with a small number of read-only tools, testing their behaviour, and then gradually introducing write operations with appropriate approval and permission controls.

This approach allows development teams to extend existing software without replacing its architecture or duplicating its business logic.

The real value of MCP is not rebuilding your application for AI. It is making the capabilities you have already built accessible through an interface that AI applications can understand and use.

Top comments (0)