Skip to content

MCP server ​

fusion-stack/mcp lets AI clients such as Claude, Cursor and VS Code use your API through the Model Context Protocol. You choose which endpoints to expose. Each becomes an MCP tool or resource whose description and input schema come from the same attributes that build your OpenAPI document, so there is nothing extra to write or keep in sync.

It is optional and built on laravel/mcp. The core package does not depend on it.

sh
composer require fusion-stack/mcp

The server is served at /mcp as soon as the package is installed. It has no tools until you mark endpoints.

Expose an endpoint as a tool ​

Add #[McpTool] next to the endpoint's #[Endpoint]:

php
use FusionStack\Laravel\OpenApi\Endpoint;
use FusionStack\Mcp\McpTool;

#[McpTool(name: 'list_orders')]
#[Endpoint('List orders', 'Orders, newest first. Filter by status, total or reference, and include each customer.')]
public function index(OrderQuery $query): AnonymousResourceCollection { ... }

#[McpTool(name: 'create_order', destructive: false)]
#[Endpoint('Create an order', 'Creates a pending order for a customer.')]
public function store(StoreOrderRequest $request): OrderResource { ... }

#[McpTool(name: 'cancel_order', destructive: true)]
#[Endpoint('Cancel an order', 'Only pending and paid orders can be cancelled; others get a 409 order_not_cancellable.')]
public function cancel(Order $order): OrderResource { ... }
ArgumentDefault
nameThe endpoint's summary in snake case: Get a customer becomes get_a_customer.
descriptionThe endpoint's summary and description, followed by the scopes it needs.
destructiveRequired for endpoints that are not GET. See safety.

The tool's input schema comes from the endpoint's OpenAPI operation:

  • Path parameters become top-level arguments, such as order.
  • The query becomes nested arguments: include, fields, filter, sort and page, limited to what the endpoint's ApiQuery allows. filter[status][in] is filter.status.in.
  • The request body, from the form request's rules and #[Describe] descriptions, is body.

So a client calling list_orders sends:

json
{ "include": ["customer"], "filter": { "status": { "in": ["paid"] } }, "sort": ["-total_cents"], "page": { "size": 20 } }

Reference data as resources ​

Data that clients load once rather than call for, such as order statuses or a product catalogue, fits better as an MCP resource. Mark a GET endpoint without path parameters with #[McpResource]:

php
use FusionStack\Mcp\McpResource;

Route::get('order-statuses', #[McpResource] #[Endpoint('Order statuses', 'Every status an order can have, in fulfilment order, and what it means.')] fn () => [
    'data' => [
        ['status' => 'pending', 'description' => 'Placed, awaiting payment', 'cancellable' => true],
        // ...
    ],
]);

Its URI defaults to api:// and the path, here api://v1/order-statuses. uri, name and description can each be set on the attribute. A resource read sends no query string, so a JSON:API list only has the relationships the endpoint loads itself.

An endpoint that is not GET, or has path parameters, cannot be a resource, and two resources cannot share a URI. Each mistake throws an exception naming the endpoint when the tools are listed, so api:mcp:list and your tests catch it.

Safety ​

Nothing is exposed without #[McpTool] or #[McpResource]. When you expose an endpoint that changes data, you must say how:

  • destructive: true for changes that lose or undo something, such as cancelling or deleting.
  • destructive: false for changes that only add, such as creating an order.

Leaving it out on a POST, PUT, PATCH or DELETE endpoint throws an exception that names the endpoint. Clients receive this as MCP's readOnlyHint and destructiveHint, and the description lists the scopes the tool needs, and many ask the user to confirm a destructive call before making it:

json
{
  "name": "cancel_order",
  "title": "Cancel an order",
  "annotations": { "readOnlyHint": false, "destructiveHint": true }
}

The full API pipeline ​

A tool call or resource read is not a shortcut into your controllers. It is an API request sent through the HTTP kernel, carrying the MCP client's Authorization header and the Api-Version header. Everything you configured for the API applies unchanged:

  • API keys and scopes. A call with a key that lacks orders:write fails with insufficient_scope, as the HTTP request would.
  • Rate limits count tool calls against the client's limit.
  • Idempotency. Each call to a tool that is not GET gets a new Idempotency-Key, so a retried request inside the pipeline cannot apply twice.
  • Versioning. Tools speak one API version, the version in config, or the latest version when it is not set. Version changes transform responses for that version as they would for any client.

What clients receive ​

Responses are shaped for a model's context window rather than for an HTTP client:

  • JSON:API documents are flattened. Each resource is a plain object of id, type and its attributes, and each included relationship is nested where it belongs.
  • Paginated lists end with next_page. A client passes it back as the page argument to fetch the next page.
  • The result is both text and structured content, so clients that understand structuredContent read it directly.
json
{
  "data": [
    {
      "id": "15", "type": "orders", "reference": "ORD-EJIWRGFH", "status": "pending", "total_cents": 19739, "currency": "GBP",
      "customer": { "id": "5", "type": "customers", "full_name": "Weston Konopelski", "email": "kobe95@example.net" }
    }
  ],
  "meta": { "page": { "size": 1 } },
  "next_page": { "size": "1", "after": "eyJvcmRlcnMuY3JlYXRlZF9hdCI6..." }
}

Errors come back as a failed tool result with each error's code, detail and pointer, followed by the request ID, so a model can correct its arguments and a person can find the request in your logs:

text
insufficient_scope: This request needs the [orders:write] scope.
Request ID: req_01m8q825f39nmeej1w3js16dah

Connect a client ​

Give the client the server's URL and an API key. Grant the key only the scopes the assistant needs. A key with no scopes can call endpoints that need none, which suits an assistant that only answers questions:

sh
php artisan api:key:create "Claude (read only)"
php artisan api:key:create "Support assistant" --scope=orders:write

Then add the server to the client. For Claude Code:

sh
claude mcp add --transport http acme https://api.example.com/mcp --header "Authorization: Bearer fs_live_…"

For clients configured with JSON, such as Cursor's mcp.json:

json
{
  "mcpServers": {
    "acme": {
      "url": "https://api.example.com/mcp",
      "headers": { "Authorization": "Bearer fs_live_…" }
    }
  }
}

Browser-based clients send an Origin header. laravel/mcp allows localhost and your app.url; list other origins in mcp.allowed_origins.

Configuration ​

Publish the config with:

sh
php artisan vendor:publish --tag=fusion-stack-mcp-config

It is merged into config('api.mcp'):

KeyDefault
enabledtrueSet false to remove the route.
pathmcpWhere the server is served.
middleware[]Middleware for the MCP connection itself, such as auth:sanctum or laravel/mcp's OAuth. Each call is still authenticated by the API with the caller's Authorization header.
namenullThe server name clients show. Defaults to the app name.
versionnullThe API version tools speak. Defaults to the latest.
log_channelnullWhere calls are logged: null for the default channel, false for none.

Pin version once your API has clients. Tool descriptions are generated from the version's OpenAPI operation, so a pinned server keeps describing and returning the shapes its users' prompts were written against until you choose to move it.

Auditing ​

Each tool call and resource read is logged at info with what was called, the request ID, the API client and the response status:

text
MCP tool call: cancel_order {"tool":"cancel_order","request_id":"req_01m8q825f39nmeej1w3js16dah","client":"api_key:1","status":403}

The request ID matches the one in the API's own logs and in the error the client saw.

Listing what is exposed ​

api:mcp:list shows every tool and resource with its endpoint, safety and scopes. Run it in review when an endpoint is added, as it is the full list of what an AI client can do:

text
$ php artisan api:mcp:list
+--------------+--------------------------------+-------------+--------------+
| Tool         | Endpoint                       | Safety      | Scopes       |
+--------------+--------------------------------+-------------+--------------+
| cancel_order | POST /v1/orders/{order}/cancel | destructive | orders:write |
| create_order | POST /v1/orders                | additive    | -            |
| get_order    | GET /v1/orders/{order}         | read-only   | -            |
| list_orders  | GET /v1/orders                 | read-only   | -            |
+--------------+--------------------------------+-------------+--------------+
+-------------------------+------------------------+--------+
| Resource                | Endpoint               | Scopes |
+-------------------------+------------------------+--------+
| api://v1/order-statuses | GET /v1/order-statuses | -      |
+-------------------------+------------------------+--------+

   INFO  4 tools and 1 resource, speaking API version 2026-11-30.atlas.

Testing ​

Use the InteractsWithMcp trait to call a tool or read a resource as a client would, through the full pipeline, and assert on what the client receives:

php
use FusionStack\Mcp\Testing\InteractsWithMcp;

uses(InteractsWithMcp::class);

it('lists orders with their customers', function () {
    [, $key] = ApiKey::issue('Test');

    $this->callMcpTool('list_orders', ['include' => ['customer']], token: $key)
        ->assertOk()
        ->assertStructuredContentPath('data.0.customer.full_name', 'Ada Lovelace');
});

it('needs the write scope to cancel', function () {
    [, $key] = ApiKey::issue('Test');

    $this->callMcpTool('cancel_order', ['order' => 1], token: $key)
        ->assertHasErrors(['insufficient_scope']);
});

it('serves order statuses', function () {
    $this->readMcpResource('api://v1/order-statuses')->assertOk()->assertSee('shipped');
});

Both helpers throw when no tool has that name or no resource has that URI, so renaming a tool breaks the tests that use it.

Released under the MIT License.