Schema Sentinel
This server provides read-only tools to analyze a Postgres database and its paired git repository, offering schema insights, migration risk detection, and health reporting.
Schema Overview: Retrieve tables, columns, primary keys, and foreign keys.
Missing Indexes: Identify FK columns lacking covering indexes.
Circular Foreign Keys: Detect FK cycles across tables, with one example cycle per group.
Table Complexity: See column counts, FK fan-in/fan-out, and cycle involvement per table.
ERD Generation: Produce a Mermaid
erDiagramrepresentation of the schema.Migration Risk Check: Statically parse a SQL migration file for dangerous patterns (e.g.,
DROP COLUMN,ALTER COLUMN TYPE,RENAME COLUMN/TABLE,ADD COLUMN NOT NULLwithoutDEFAULT,CREATE INDEXwithoutCONCURRENTLY) without executing it.Schema Churn: Analyze git history to see how often and how recently each table's migrations changed, optionally filtered by a time window.
Combined Report: Generate a full schema health report from all the above insights, optionally filtered by time window.
Analyzes the paired Git repository to track schema churn and migration history, identifying how often and how recently each table's migrations have changed.
Provides read-only tools for inspecting a PostgreSQL schema, including tables, columns, primary and foreign keys, missing indexes, circular foreign keys, table complexity, and ERD generation. Also parses migration files to flag risky database operations without executing them.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Schema Sentinel Generate a schema health report for the last 30 days"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Read-only MCP server that lets an AI agent look at a Postgres db + its paired git repo and just... know what's going on. Schema, ERD, missing indexes, circular FKs, migration risk, git-churn hotspots, all the stuff you'd normally dig up by hand with psql and git log.
Works against any Postgres + repo pair via .env config (connection string + repo path). Not hardcoded to one project.
Why I built this
Two reasons: it's a portfolio piece, and it was my hands-on way of actually learning MCP, schema introspection, static SQL parsing, git analysis, and wiring all of it up as agent-callable tools.
Related MCP server: MCP Server for Database
Tools
Tool | Args | What it does |
| — | Tables, columns, PKs, FKs for the connected db |
| — | Flags FK columns with no covering index |
| — | Catches FK cycles across tables, and shows one concrete cycle per group |
| — | Per table: column count, FK fan-in/fan-out, whether it's tangled in a cycle |
| — | Spits out a Mermaid |
|
| Statically parses one migration file and flags risky stuff. Never runs it |
|
| How often, and how recently, each table's migrations changed |
|
| Rolls all of the above into one health report |
What counts as migration risk
check_migration_risk parses the file and flags six patterns:
Pattern | Severity | Why |
| high | irreversible data loss |
| high | rewrites the table, holds a long lock, can silently truncate |
| high | breaks in-flight app code still using the old name mid-deploy |
| high | same, but takes out every FK pointing at the table too |
| medium | fails outright once the table has rows |
| medium | blocks writes for however long the build takes |
Setup
pip install -e .(orpip install -e ".[dev]"to also getpytest).Copy
.env.exampleto.envand fill inSCHEMA_SENTINEL_DB_URL,SCHEMA_SENTINEL_REPO_PATH,SCHEMA_SENTINEL_MIGRATIONS_PATH. The db role has to be read-only, runscripts/setup_readonly_role.sqlagainst your database first if you don't already have one.Run it:
schema-sentinel(installed as a console script), orpython -m schema_sentinel.server. Either way it speaks MCP over stdio.
To wire it into an MCP client, point the client at the console script and hand it the three env vars:
{
"mcpServers": {
"schema-sentinel": {
"command": "schema-sentinel",
"env": {
"SCHEMA_SENTINEL_DB_URL": "postgresql://schema_sentinel_ro@localhost:5432/your_database",
"SCHEMA_SENTINEL_REPO_PATH": "/path/to/your/repo",
"SCHEMA_SENTINEL_MIGRATIONS_PATH": "/path/to/your/repo/migrations"
}
}
}
}Decisions I've locked in
Python +
psycopgv3 (psycopg[binary]) for Postgres.The
mcpSDK's bundled FastMCP (mcp.server.fastmcp) for the server, not the standalonefastmcppackage. Pinned tomcp<2deliberately, see the rough edges below.Mermaid
erDiagramtext for the ERD, no Graphviz, no rendering lib. GitHub and Notion already render Mermaid natively, so why bother.pglast(wrapslibpg_query, Postgres's own C parser) to statically parse migrations.check_migration_riskonly ever parses, never runs, a migration. Non-negotiable.Worth saying why it's
pglastand not a generic multi-dialect parser: I started on one and found it silently gave up on multi-item DDL.ALTER TABLE x DROP COLUMN a, ALTER COLUMN b TYPE intcame back as an unparsed blob, which meant a genuinely dangerous migration would sail through reporting zero risks, andDROP TABLE a, b;raised outright. Both are ordinary SQL.pglastdoesn't approximate the grammar, it is the grammar, so neither is a problem.GitPython for the churn/file-history stuff.
Introspection goes through
pg_catalog, notinformation_schema. Not a style preference:information_schema.table_constraintsand friends gate visibility behind write-ish privileges, so a strictly read-only role sees zero rows there. Which is exactly the role this thing is designed to run as.psycopg3 param binding: list filters use
= ANY(%s), notIN %s. psycopg3 doesn't auto-expand a Python list into a SQLIN (...)the way psycopg2 did. Bit me once, not doing it again.Churn and complexity stay separate. Churn is a pure git signal, complexity is a pure schema signal, neither reaches into the other's half.
generate_reporthands you both.
Security posture (read-only, belt and suspenders)
Enforced in src/schema_sentinel/db/connection.py:
Session-level lock,
SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLYright after connecting, before anything else runs.Startup privilege check, checks
pg_rolesforrolsuper/rolcreatedb/rolcreaterole, andinformation_schema.role_table_grantsfor any non-SELECTgrant on the connecting role. Either one fails, the connection gets closed and it raisesWritableConnectionError, no usable connection handed back, period.scripts/setup_readonly_role.sqlsets up a correctly-scoped read-only role in one step, instead of doing it by hand.
The migration checker never touches the database at all, it only reads files off disk.
Project layout
src/schema_sentinel/
├── config.py env config -> Settings
├── schema.py get_schema_overview, find_missing_indexes,
│ find_circular_foreign_keys, find_table_complexity
├── erd.py generate_erd
├── migrations.py check_migration_risk
├── report.py generate_report
├── server.py MCP entrypoint, registers all 8 tools
├── db/connection.py the read-only gatekeeper
└── git_ops/churn.py find_schema_churn
tests/ mirrors src/, plus tests/test_db/ and tests/test_git_ops/
scripts/ setup_readonly_role.sql, setup_test_db.sqlRunning the tests
Most of the suite is DB-free, but the schema/connection/report tests run against a real local Postgres, since the whole point of the connection tests is proving actual grant enforcement and you can't meaningfully mock that.
createdb schema_sentinel_test
psql -d schema_sentinel_test -f scripts/setup_test_db.sql
pytestsetup_test_db.sql builds the fixture tables (simple and composite PKs, simple and composite FKs, one FK deliberately left unindexed) plus the three roles the connection tests need. Point the SCHEMA_SENTINEL_TEST_* URLs in .env at them. CI does exactly this against a throwaway Postgres container on every push.
Known rough edges
Schema-qualified names get flattened. Churn keys everything by bare table name, so
public.ordersandanalytics.orderswould land in the same bucket. Fine for the single-schema case, wrong for anything fancier.The risk checker knows six patterns. Plenty of other things worth flagging aren't in there yet:
ADD CONSTRAINTwithoutNOT VALID,SET NOT NULLon an existing column, volatileDEFAULTs,VACUUM FULL,CLUSTER.generate_reportre-queries more than it needs to. Several tools callget_schema_overviewor the constraint fetch independently, so a full report hitspg_constrainta handful of times over. Each tool being self-contained was the deliberate tradeoff, but on a big schema it's wasteful.Pinned to
mcp1.x. 2.0 removedmcp.server.fastmcp, which is whatserver.pyis written against, so upgrading means porting the tool registration to whatever replaced it. Pinned rather than rushed.Complexity is a raw count, not a score. Fan-in, fan-out and column count get sorted, not weighted, and nothing multiplies churn against complexity to give you a single "hotspot" number. You get both halves and draw your own conclusions.
License
AGPL-3.0-or-later, full text in LICENSE.
Short version: read it, run it, fork it, learn from it, all fine. But if you distribute a modified version, or run one as a service other people can reach, you have to publish your source too.
Copyright (C) 2026 Ramón Iglesias
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Available Tools
8 toolscheck_migration_riskA
Statically parses a single migration .sql file and flags risky patterns. Never executes it.
Inputs: sql_path (required). Returns: result
find_circular_foreign_keysA
Catches FK cycles across tables.
Inputs: no named parameters. Returns: result
find_missing_indexesA
Flags FK columns with no covering index.
Inputs: no named parameters. Returns: result
find_schema_churnB
Git-history churn per table: how often (and how recently) each table's migrations changed.
Inputs: since_days. Returns: result
find_table_complexityA
Structural complexity per table: column count, FK fan-in/out, circular-FK involvement.
Inputs: no named parameters. Returns: result
generate_erdB
Mermaid erDiagram text for the connected schema.
Inputs: no named parameters. Returns: result
generate_reportC
Rolls every tool above into one combined health report.
Inputs: since_days.
get_schema_overviewB
Tables, columns, PKs, FKs for the connected database.
Inputs: no named parameters.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 8 tools
Each tool targets a distinct analytical concern: index coverage, FK cycles, table complexity, ERD generation, migration risk, schema churn, combined reporting, and schema overview. There is no meaningful overlap between tool purposes.
All tool names follow a consistent verb-first snake_case pattern (e.g., find_missing_indexes, generate_erd). The verbs are imperative and the object is clear, making the set predictable.
Eight tools is well-scoped for a schema health analysis server. Each tool earns its place and covers a specific aspect of schema inspection without bloat.
The toolset covers a broad range of schema health checks: current schema, migrations, history, and ERD generation. Minor gaps exist such as index performance analysis or orphaned FK detection, but the core workflows are solid.
Maintenance
Related MCP Connectors
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
Hosted PostgreSQL MCP server for Claude, ChatGPT and Cursor, with each action switched per account.
PostgreSQL, MySQL, and SQL Server in one session. 26 read-only MCP tools for AI agents.
Text-to-SQL MCP server: read-only queries on PostgreSQL, MySQL and SQL Server with your real schema
Related MCP Servers
- AlicenseNot gradedqualityBmaintenanceA read-only PostgreSQL MCP server that enables AI agents to perform schema introspection and execute SELECT-only queries. It supports secure database connections through SSL and SSH tunnels while offering a structure-only mode to restrict query access.200 npmMIT
- FlicenseNot gradedqualityDmaintenanceA read-only MCP server that enables AI agents to explore database schemas and execute safe queries on PostgreSQL and MySQL.-
- AlicenseNot gradedqualityDmaintenanceA zero-config, read-only PostgreSQL MCP server that enforces read-only access at the database level using READ ONLY transactions, allowing AI agents to safely explore schemas and run SELECT queries without risk of mutation.19 npmMIT
- AlicenseNot gradedqualityDmaintenanceAn MCP server that provides safe, read-only SQL access for AI agents to query databases (PostgreSQL, MySQL, SQLite) with schema awareness and guardrails.15 npmMIT