laravel-mcp
Enables AI assistants to inspect a Laravel project read-only, including database schema, Eloquent models, routes, logs, migrations, and app/composer metadata, plus run SELECT-only SQL against the app's configured database.
Provides read-only MySQL database inspection and SELECT-only query execution through the server's MySQL adapter, with row caps and timeouts.
Provides read-only PostgreSQL database inspection and SELECT-only query execution through the server's PostgreSQL adapter, with row caps and timeouts.
Provides read-only SQLite database inspection and SELECT-only query execution, opening SQLite in readonly mode.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
laravel-mcp
Read-only Model Context Protocol 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) — 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.
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 |
|
Resources | Read-only documents the host can attach as context |
|
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).
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 --> LaravelNothing 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.
Related MCP server: MCP Guide Schema Query
Tools
Tool | What it does |
| List tables/views in the configured database |
| Columns, types, nullability, indexes, foreign keys |
| SELECT / WITH / EXPLAIN / SHOW / DESCRIBE only. Writes, DDL, multiple statements, |
| Scan |
|
|
| Tail |
| Laravel version, PHP version, |
| Migration files + whether they have run ( |
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:
phponPATHsolist_routescan use Artisan
Install
# 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 --helpThe CLI binary is laravel-mcp (bin in package.json), so npx laravel-mcp works after publish.
Configure
Option A — environment variables
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=5000Option B — laravel-mcp.config.json
See laravel-mcp.config.example.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
{
"mcpServers": {
"laravel": {
"command": "npx",
"args": ["-y", "laravel-mcp"],
"env": {
"LARAVEL_MCP_PROJECT_ROOT": "/absolute/path/to/your/laravel/app"
}
}
}
}From this repo while developing:
{
"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\).
{
"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)
npx laravel-mcp --http --port 3847 --project /path/to/laravel
# POST JSON-RPC to http://127.0.0.1:3847/mcpOr 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:
{
"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" }:
{
"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:
{
"className": "Post",
"table": "posts",
"relationships": [
{ "method": "user", "type": "belongsTo", "related": "User" },
{ "method": "comments", "type": "hasMany", "related": "Comment" }
]
}You: “Show unpublished posts.”
{ "sql": "SELECT id, title FROM posts WHERE published = 0", "maxRows": 20 }{
"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_queryis gated bysrc/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,*_KEYare detected insrc/security/secrets.ts.app_infolists which keys exist, not their values. Log tails run through the same masker forKEY=valuefragments.Path jail. Every file read is resolved with
path.relativeagainst the project root (src/security/paths.ts).read_logsonly accepts a basename insidestorage/logs/—../../.envis rejected.Do not bind HTTP to
0.0.0.0on 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 userswill 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 intinkeryourself.
How it works / learn MCP from this code
If you are new to MCP, read the files in this order:
src/index.ts— CLI. Stdio vs HTTP. Noticeconsole.errorinstead ofconsole.log: stdout is the protocol.src/server.ts—new McpServer({ name, version }), then register tools, resources, prompts. A factory so HTTP can mint a fresh instance per request.src/tools/register.ts— this is a complete tool definition. Walkthrough below.src/security/sql-guard.ts— whyrun_queryis strict.src/config.ts— env / config file / Laravel.envmerge.
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.
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
// 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 protocolSample 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:
npm run fixture:db
LARAVEL_MCP_PROJECT_ROOT=./fixture node dist/index.jsDevelopment
npm install
npm run fixture:db
npm run lint
npm run typecheck
npm test
npm run buildLint: ESLint 9 +
typescript-eslintTypecheck:
tsc --noEmit(strict)Tests: Vitest, including an in-memory MCP client (
InMemoryTransport) that speaks the real protocol
CI: .github/workflows/ci.yml runs the same commands on Node 20 and 22. Status:
npm
The npm package name is laravel-mcp. The source lives at 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:
npm publish --access publicLimitations
Eloquent parsing is regex / static. Traits,
__call, and relations declared outside the model file are missed. Preferdescribe_tablefor ground truth.Route-file fallback does not understand every
Route::groupprefix. Use PHP + Artisan for a complete list.SQLite via
better-sqlite3is a native addon (prebuilds exist for common platforms).Large MySQL/Postgres result sets are truncated in memory after fetch; set
maxRowslow.EXPLAIN ANALYZEis rejected (ANALYZEis 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.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
Query 40 databases from Claude, ChatGPT, or Cursor — on any device. Read-only, encrypted, audited.
Work with your database from AI tools: ask, export, approved changes, and scheduled jobs.
Gives AI agents direct access to your Sanity projects and guidance for working with them
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceProvides AI assistants with read-only access to inspect database schemas, preview data, and run safe queries across PostgreSQL, MySQL, MongoDB, and SQL Server. It enables AI tools to understand database structures and relationships automatically to generate more accurate code.9 npm7MIT
- AlicenseNot gradedqualityDmaintenanceEnables AI tools to understand a database, inspect schema, and run safe SELECT queries with SQL guardrails, plus optional codebase reading.MIT
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to query PostgreSQL, inspect schemas, and explain queries, designed for local and development databases with read-only safety by default.38 npmMIT
- AlicenseAqualityDmaintenanceEnables AI assistants to interact with a Magento 2 or Adobe Commerce MySQL database through 50+ read-only tools for orders, catalog, customers, CMS, configuration, indexers, and diagnostics, with support for local DDEV, Commerce Cloud, and remote/SSH connections.4411 npmMIT