Skip to main content
Glama
README.md
# laravel-mcp

[![CI](https://github.com/usamax0007/mcp-laravel/actions/workflows/ci.yml/badge.svg)](https://github.com/usamax0007/mcp-laravel/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/usamax0007/mcp-laravel/blob/main/LICENSE)

**Read-only [Model Context Protocol](https://modelcontextprotocol.io) server for Laravel.** Point it at any Laravel project and an AI assistant (Cursor, Claude Desktop, ChatGPT/Codex, …) can inspect the schema, Eloquent models, routes, logs, migrations, and run **SELECT-only** SQL — without ever seeing `.env` secrets or issuing writes.

Author: **Usama Tahir** ([Xcodrix](https://xcoderix.com)) — a senior Laravel / Twilio developer learning MCP by building the thing he wished existed.

This repository is both a useful tool and a teaching project. The code is commented on purpose. If you have never built an MCP server, start at [How it works](#how-it-works--learn-mcp-from-this-code).

## What is MCP, in plain words?

Your editor (Cursor, Claude Desktop, …) already talks to a language model. The model is smart, but it cannot see *your* Laravel app unless you paste files into the chat.

**MCP (Model Context Protocol)** is a small, open JSON-RPC protocol that lets the editor spawn extra processes called **servers**. A server advertises:

| Kind | What it is | Laravel example |
| --- | --- | --- |
| **Tools** | Functions the model can call with arguments | `run_query`, `list_models` |
| **Resources** | Read-only documents the host can attach as context | `laravel://schema` |
| **Prompts** | Reusable conversation starters | “Debug recent errors” |

The host (Cursor) is the **client**. `laravel-mcp` is the **server**. They speak JSON-RPC over **stdio** (a child process; this is what Cursor and Claude Desktop use) or **Streamable HTTP** (a POST endpoint for remote hosts).

```mermaid
flowchart LR
  subgraph Host["AI host (Cursor / Claude Desktop / Codex)"]
    LLM[Language model]
    Client[MCP client]
  end

  subgraph MCP["laravel-mcp"]
    Tools[Tools]
    Resources[Resources]
    Prompts[Prompts]
    Guard["SQL guard + secret mask + path jail"]
    Inspect["Models / routes / logs / composer.lock"]
    DB["SQLite / MySQL / PostgreSQL adapters"]
  end

  Laravel["Your Laravel app"]

  LLM --> Client
  Client -->|"JSON-RPC (stdio or HTTP)"| Tools
  Client --> Resources
  Client --> Prompts
  Tools --> Guard
  Guard --> DB
  Guard --> Inspect
  DB --> Laravel
  Inspect --> Laravel
```

Nothing in this server writes to your database or your files. SQLite is opened with `readonly: true`. MySQL and PostgreSQL still need a **read-only database user** in production — the SQL guard is a second line of defense, not a substitute for database privileges.

## Tools

| Tool | What it does |
| --- | --- |
| `list_tables` | List tables/views in the configured database |
| `describe_table` | Columns, types, nullability, indexes, foreign keys |
| `run_query` | **SELECT / WITH / EXPLAIN / SHOW / DESCRIBE only.** Writes, DDL, multiple statements, `SELECT INTO`, and `FOR UPDATE` are rejected. Row cap + timeout. |
| `list_models` | Scan `app/Models` and report Eloquent models, `$fillable` / `$casts` / relations (static PHP parse — PHP is not executed) |
| `list_routes` | `php artisan route:list --json` when PHP is available; otherwise parse `routes/*.php` |
| `read_logs` | Tail `storage/logs/laravel.log` with optional level filter and line limit |
| `app_info` | Laravel version, PHP version, `APP_ENV`, installed `composer.lock` packages. **Never returns secret values.** |
| `list_migrations` | Migration files + whether they have run (`migrations` table) |

**Resources:** `laravel://schema`, `laravel://models`, `laravel://app-info`, and `laravel://table/{name}`.

**Prompts:** `debug_recent_errors`, `explain_data_model`.

## Requirements

- Node.js **20+**
- A Laravel project (or the bundled `fixture/` for demos)
- For live MySQL / PostgreSQL: network access and credentials
- Optional: `php` on `PATH` so `list_routes` can use Artisan

## Install

```bash
# from source
git clone https://github.com/usamax0007/mcp-laravel.git
cd mcp-laravel
npm install
npm run fixture:db    # builds the sample SQLite database
npm run build

# or, once published
npx laravel-mcp --help
```

The CLI binary is `laravel-mcp` (`bin` in `package.json`), so `npx laravel-mcp` works after publish.

## Configure

### Option A — environment variables

```bash
export LARAVEL_MCP_PROJECT_ROOT=/path/to/your/laravel/app
# Optional overrides; if omitted, DB_* is read from the app's .env
export LARAVEL_MCP_DB_CONNECTION=mysql   # sqlite | mysql | pgsql
export LARAVEL_MCP_DB_HOST=127.0.0.1
export LARAVEL_MCP_DB_PORT=3306
export LARAVEL_MCP_DB_DATABASE=app
export LARAVEL_MCP_DB_USERNAME=readonly
export LARAVEL_MCP_DB_PASSWORD=...
export LARAVEL_MCP_QUERY_MAX_ROWS=100
export LARAVEL_MCP_QUERY_TIMEOUT_MS=5000
```

### Option B — `laravel-mcp.config.json`

See `laravel-mcp.config.example.json`.

```json
{
  "projectRoot": "/var/www/my-app",
  "database": {
    "connection": "pgsql",
    "host": "127.0.0.1",
    "port": 5432,
    "database": "myapp",
    "username": "readonly"
  }
}
```

Pass it with `--config ./laravel-mcp.config.json` or `LARAVEL_MCP_CONFIG`.

**Precedence:** CLI flags → `LARAVEL_MCP_*` env vars → config file → the Laravel app’s `.env` → defaults.

The server **does** read `DB_PASSWORD` from `.env` so it can connect. It **does not** put that value (or `APP_KEY`, tokens, `*_SECRET`) into any tool result.

### Cursor — `.cursor/mcp.json`

```json
{
  "mcpServers": {
    "laravel": {
      "command": "npx",
      "args": ["-y", "laravel-mcp"],
      "env": {
        "LARAVEL_MCP_PROJECT_ROOT": "/absolute/path/to/your/laravel/app"
      }
    }
  }
}
```

From this repo while developing:

```json
{
  "mcpServers": {
    "laravel": {
      "command": "node",
      "args": ["dist/index.js"],
      "cwd": "/absolute/path/to/laravel-mcp",
      "env": {
        "LARAVEL_MCP_PROJECT_ROOT": "/absolute/path/to/laravel-mcp/fixture"
      }
    }
  }
}
```

### Claude Desktop

Edit `claude_desktop_config.json` (macOS: `~/Library/Application Support/Claude/`; Windows: `%APPDATA%\Claude\`).

```json
{
  "mcpServers": {
    "laravel": {
      "command": "npx",
      "args": ["-y", "laravel-mcp"],
      "env": {
        "LARAVEL_MCP_PROJECT_ROOT": "/absolute/path/to/your/laravel/app"
      }
    }
  }
}
```

Restart Claude Desktop after saving.

### Streamable HTTP (optional)

```bash
npx laravel-mcp --http --port 3847 --project /path/to/laravel
# POST JSON-RPC to http://127.0.0.1:3847/mcp
```

Or `LARAVEL_MCP_TRANSPORT=http`. The process binds to `127.0.0.1` by default (DNS-rebinding protection via the SDK’s Express helper).

## Example prompts and outputs

**You:** “What tables does this app have?”

The model calls `list_tables` and sees something like:

```json
{
  "dialect": "sqlite",
  "tables": [
    { "name": "comments", "type": "table" },
    { "name": "migrations", "type": "table" },
    { "name": "posts", "type": "table" },
    { "name": "users", "type": "table" }
  ]
}
```

**You:** “How does Post relate to User?”

The model calls `list_models` + `describe_table` with `{ "table": "posts" }`:

```json
{
  "name": "posts",
  "columns": [
    { "name": "id", "type": "INTEGER", "nullable": true, "primaryKey": true },
    { "name": "user_id", "type": "INTEGER", "nullable": false, "primaryKey": false }
  ],
  "foreignKeys": [
    { "columns": ["user_id"], "referencedTable": "users", "referencedColumns": ["id"] }
  ]
}
```

…and from `list_models`:

```json
{
  "className": "Post",
  "table": "posts",
  "relationships": [
    { "method": "user", "type": "belongsTo", "related": "User" },
    { "method": "comments", "type": "hasMany", "related": "Comment" }
  ]
}
```

**You:** “Show unpublished posts.”

```json
{ "sql": "SELECT id, title FROM posts WHERE published = 0", "maxRows": 20 }
```

```json
{
  "rowCount": 1,
  "truncated": false,
  "rows": [{ "id": 3, "title": "Draft: Sketch of a calculator" }]
}
```

**You:** “Delete all users” → `run_query` returns an error (`isError: true`):

```
Only read-only queries are allowed (SELECT, WITH … SELECT, EXPLAIN, SHOW, DESCRIBE). Received 'DELETE'.
```

Use the built-in prompts from the host’s prompt picker: **Debug recent errors** and **Explain the data model**.

## Security notes

- **Read-only by default.** `run_query` is gated by `src/security/sql-guard.ts` (comments/strings stripped, single statement, allow-list of first keywords, deny-list of writes/DDL). SQLite is opened `{ readonly: true, fileMustExist: true }`.
- **Give MySQL/Postgres a SELECT-only user.** The guard can be wrong about an exotic dialect feature; the database cannot.
- **Secrets never leave the process.** `APP_KEY`, `*_PASSWORD`, `*_SECRET`, `*_TOKEN`, `*_KEY` are detected in `src/security/secrets.ts`. `app_info` lists *which* keys exist, not their values. Log tails run through the same masker for `KEY=value` fragments.
- **Path jail.** Every file read is resolved with `path.relative` against the project root (`src/security/paths.ts`). `read_logs` only accepts a **basename** inside `storage/logs/` — `../../.env` is rejected.
- **Do not bind HTTP to `0.0.0.0`** on a machine that can reach production data unless you add your own auth. Stdio is the intended local transport.
- Query results are **not** auto-redacted. `SELECT password FROM users` will return hashes if the column exists — that is the developer asking for their own data. Do not point this server at a database you would not query in `tinker` yourself.

## How it works / learn MCP from this code

If you are new to MCP, read the files in this order:

1. **`src/index.ts`** — CLI. Stdio vs HTTP. Notice `console.error` instead of `console.log`: **stdout is the protocol**.
2. **`src/server.ts`** — `new McpServer({ name, version })`, then register tools, resources, prompts. A factory so HTTP can mint a fresh instance per request.
3. **`src/tools/register.ts`** — this is a complete tool definition. Walkthrough below.
4. **`src/security/sql-guard.ts`** — why `run_query` is strict.
5. **`src/config.ts`** — env / config file / Laravel `.env` merge.

### Anatomy of one tool

An MCP tool is three pieces: a **name**, a **JSON Schema** (we write Zod; the SDK compiles it), and an **async handler**.

```ts
server.registerTool(
  'list_tables',                                         // 1. name the client calls
  {
    title: 'List tables',                                // 2a. short UI label
    description: 'List tables (and views) in the …',     // 2b. the model reads this
    inputSchema: {                                       // 2c. Zod raw shape → JSON Schema
      schema: z.string().optional().describe('PostgreSQL schema name. …'),
    },
  },
  async ({ schema }) => {                                 // 3. handler; args already validated
    try {
      const db = await ctx.getDatabase();
      const tables = await listTables(db, schema);
      return {
        content: [{ type: 'text', text: JSON.stringify({ tables }, null, 2) }],
      };
    } catch (err) {
      return {
        content: [{ type: 'text', text: err.message }],
        isError: true,                                   // model sees the error, turn continues
      };
    }
  },
);
```

That is the whole contract. Cursor’s model calls `tools/list`, picks `list_tables`, then `tools/call` with `{ "name": "list_tables", "arguments": {} }`.

Resources are even simpler: a URI plus a read callback (`src/resources/register.ts`). Prompts return `{ messages: [{ role, content }] }` that the host feeds to the model (`src/prompts/register.ts`).

### Transports

```ts
// Local editor integration (required): the host spawns this process.
await server.connect(new StdioServerTransport());

// Remote / HTTP (optional, stateless):
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
await server.connect(transport);
await transport.handleRequest(req, res, req.body);
```

### Layout

```
src/
  index.ts              CLI + transport choice
  server.ts             McpServer factory
  http.ts               Streamable HTTP (Express)
  config.ts             env / file / Laravel .env
  context.ts            lazy DB connection
  tools/register.ts     all eight tools
  resources/register.ts schema + models + app-info
  prompts/register.ts   debug + explain data model
  security/             sql-guard, secrets, path jail
  db/                   sqlite / mysql / postgres + schema inspect
  laravel/              models, routes, logs, migrations, app-info
fixture/                tiny Laravel-like app + SQLite DB for tests
tests/                  vitest — guard, masking, every tool, MCP protocol
```

## Sample fixture

`fixture/` is a Laravel-shaped tree (models, routes, migrations, `.env`, `composer.lock`, `storage/logs/laravel.log`) plus a SQLite database of users / posts / comments. It is **not** a bootable Laravel app. It exists so you can run the server without installing PHP or MySQL:

```bash
npm run fixture:db
LARAVEL_MCP_PROJECT_ROOT=./fixture node dist/index.js
```

## Development

```bash
npm install
npm run fixture:db
npm run lint
npm run typecheck
npm test
npm run build
```

- **Lint:** ESLint 9 + `typescript-eslint`
- **Typecheck:** `tsc --noEmit` (`strict`)
- **Tests:** Vitest, including an in-memory MCP client (`InMemoryTransport`) that speaks the real protocol

CI: [`.github/workflows/ci.yml`](https://github.com/usamax0007/mcp-laravel/blob/main/.github/workflows/ci.yml) runs the same commands on Node 20 and 22. Status: [![CI](https://github.com/usamax0007/mcp-laravel/actions/workflows/ci.yml/badge.svg)](https://github.com/usamax0007/mcp-laravel/actions/workflows/ci.yml)

## npm

The npm package name is **`laravel-mcp`**. The source lives at [github.com/usamax0007/mcp-laravel](https://github.com/usamax0007/mcp-laravel). The package is publish-ready (`bin`, `files`, `engines`, `prepublishOnly`) but **is not published from this repository automatically**. When you are ready:

```bash
npm publish --access public
```

## Limitations

- Eloquent parsing is **regex / static**. Traits, `__call`, and relations declared outside the model file are missed. Prefer `describe_table` for ground truth.
- Route-file fallback does not understand every `Route::group` prefix. Use PHP + Artisan for a complete list.
- SQLite via `better-sqlite3` is a native addon (prebuilds exist for common platforms).
- Large MySQL/Postgres result sets are truncated in memory after fetch; set `maxRows` low.
- `EXPLAIN ANALYZE` is rejected (`ANALYZE` is a forbidden keyword) because it *executes* the plan.
- No auth on the HTTP transport. Stdio is the supported way to expose this to an editor.

## License

MIT © 2026 Usama Tahir (Xcodrix) — see [LICENSE](LICENSE).