Prisma PHP MCP Server

Prisma PHP’s Model Context Protocol (MCP) integration turns your app into a toolbox for AI agents and internal automations. Define tools with #[McpTool], start the server, and your capabilities become discoverable and callable.

Getting Started

Key files you already have:

  • /src/Lib/MCP/mcp-server.php – HTTP transport + tool discovery
  • /src/Lib/MCP/WeatherTools.php – Example tool with #[McpTool]
$ php src/Lib/MCP/mcp-server.php
# ➜ prints server info, host/port, and "Listening on http://127.0.0.1:4000/mcp"

On boot, the server auto-discovers all classes annotated with #[McpTool] under /src.

Environment Variables

Variable Default Description
MCP_NAME prisma-php-mcp Server name shown in logs and client handshakes.
MCP_VERSION 0.0.1 Semantic version of your MCP service.
MCP_HOST 127.0.0.1 Bind address for the HTTP transport.
MCP_PORT 4000 Port to listen on.
MCP_PATH_PREFIX mcp URL prefix for requests (e.g., /mcp).
MCP_JSON_RESPONSE false Enable plain JSON responses for debugging.
APP_TIMEZONE UTC Timezone for consistent timestamps.
# .env (example)
MCP_NAME="prisma-php-mcp"
MCP_VERSION="0.1.0"
MCP_HOST="127.0.0.1"
MCP_PORT="4000"
MCP_PATH_PREFIX="mcp"
MCP_JSON_RESPONSE="true"
APP_TIMEZONE="America/Managua"

Authoring Tools with #[McpTool]

Decorate public methods with #[McpTool]. Use #[Schema] to type/validate parameters. Tools are self-documented and safely callable by AI agents.

In src/Lib/MCP/WeatherTools.php you'll find an example implementation of #[McpTool] and #[Schema]. This file is provided for demonstration purposes—you can delete it or create your own MCP tools as needed.

<?php

use PhpMcp\Server\Attributes\McpTool;
use PhpMcp\Server\Attributes\Schema;

final class WeatherTools
{
    #[McpTool(name: 'get-weathers', description: 'Returns current temperature for a city')]
    public function getWeather(
        #[Schema(type: 'string', minLength: 1, description: 'City name')]
        string $city
    ): string {
        // ... your implementation (Open-Meteo example) ...
    }
}

Tip: Split tools by domain (e.g., DbTools, OrdersTools, InventoryTools). Keep methods single-purpose and clearly described — it improves agent reliability.

Run & Integrate

  1. Set your .env (host, port, path prefix).
  2. Start the server: By default, npm run dev will run mcp-server automatically (managed by the Prisma PHP environment). If you want, you can also run it directly: php src/Lib/MCP/mcp-server.php.
  3. Point your AI agent / client to http://<host>:<port>/<prefix>.
  4. Tools are discovered automatically on boot; restart after adding new tools.

Security: put your MCP behind auth (e.g., reverse proxy with JWT/API keys or IP allow-list). Never expose dangerous tool methods without strict validation/authorization.

Benefits

Benefit What it Means Example
Typed, discoverable tools Agents know exactly which functions exist and how to call them. #[McpTool(name: 'create-order')] with typed payload.
Fast integration Expose existing PHP code in minutes via attributes. Wrap your service layer methods; zero framework migration.
Safe execution Input schemas + server-side validation prevent bad calls. Rejects malformed IDs, enforces role checks.
AI-native workflows Natural-language to action via your own business logic. “Restock items below threshold” → calls InventoryTools.
Infra-friendly Plain PHP + HTTP. Works with Docker, Nginx/Apache, CI/CD. Deploy alongside your app or as a sidecar service.

Common Usage Patterns

Domain Typical Tools What the Agent Can Do
POS find-product, apply-discount, create-sale, close-shift Build a sale from a description, split payments, close register with audit trail.
E-commerce search-catalog, create-order, get-shipping-rates, refund-order Conversational checkout, returns/exchanges, promo recommendations.
Finance post-journal, reconcile-statement, generate-invoice Automate reconciliations and invoice creation from plain language.
Ops / Admin user-lookup, grant-role, run-report Role changes, data pulls, and canned reports via prompts.
Support ticket-create, ticket-escalate, order-status Resolve customer requests end-to-end without dashboards.

Example: Database Tool (Skeleton)

Here’s a safe pattern for DB access via Prisma PHP. Validate inputs, select only what you need, and enforce auth.

<?php

use PhpMcp\Server\Attributes\McpTool;
use PhpMcp\Server\Attributes\Schema;
use Lib\Prisma\Classes\Prisma;
use Lib\Auth\Auth;

final class OrdersTools
{
    #[McpTool(name: 'order-by-id', description: 'Fetch an order by public ID')]
    public function getOrder(
        #[Schema(type: 'string', minLength: 10, description: 'Public order ID')] string $orderId
    ): array {
        $auth = Auth::getInstance();
        $user = $auth->getPayload(); // enforce roles/ownership as needed

        $prisma = Prisma::getInstance();
        $order = $prisma->order->findFirst([
            'where' => ['publicId' => $orderId],
            'select' => [
                'publicId' => true,
                'status'   => true,
                'total'    => true,
                'items'    => [
                    'select' => ['sku' => true, 'qty' => true, 'price' => true]
                ],
            ],
        ]);

        if (!$order) {
            throw new \RuntimeException('Order not found.');
        }
        // Optional: authorization checks here
        return $order;
    }
}

Testing & Debugging

  • Start with MCP_JSON_RESPONSE=true to inspect payloads in a browser or via curl.
  • Throw \RuntimeException with clear messages for agent-readability.
  • Keep tools idempotent where possible; log side-effects with correlation IDs.
  • Use the MCP Inspector for live inspection of MCP server requests/responses:
# Install inspector globally (or via npx)
npx @modelcontextprotocol/inspector

# By default, MCP server runs automatically with:
npm run dev

# Or, to run MCP server directly (in a separate terminal):
php src/Lib/MCP/mcp-server.php

# In another terminal, run:
npx @modelcontextprotocol/inspector http://127.0.0.1:4000/mcp

# Inspector will list available tools and let you test calls interactively

Tip: The Inspector shows full request/response payloads, input validation errors, and lets you quickly iterate on #[McpTool] logic without writing a client.

Safety Checklist

Inputs

  • Validate with #[Schema] and server-side checks.
  • Whitelist fields; reject unexpected keys.

AuthZ

  • Require roles/ownership for mutating tools.
  • Rate-limit sensitive operations.