Metadata-Version: 2.5
Name: db-health-mcp
Version: 0.2.1
Summary: An MCP server that gives your AI agent a stethoscope for MySQL (and PostgreSQL): one-call health report with a score, plus slow queries, missing indexes, fragmentation/bloat, and unused indexes.
License: MIT
License-File: LICENSE
Requires-Python: >=3.10
Requires-Dist: mcp<2,>=1.2
Requires-Dist: psycopg[binary]>=3.1
Requires-Dist: pymysql>=1.1
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == 'dev'
Description-Content-Type: text/markdown

# db-health-mcp

<p align="center">
  <img src="https://img.shields.io/badge/python-3.11%2B-3776AB?logo=python&logoColor=white" alt="Python 3.11+">
  <img src="https://img.shields.io/badge/MySQL-8-4479A1?logo=mysql&logoColor=white" alt="MySQL 8">
  <img src="https://img.shields.io/badge/PostgreSQL-16-4169E1?logo=postgresql&logoColor=white" alt="PostgreSQL 16">
  <img src="https://img.shields.io/badge/tests-30%20passing-brightgreen" alt="30 tests passing">
  <img src="https://img.shields.io/badge/license-MIT-blue" alt="MIT license">
  <img src="https://img.shields.io/badge/MCP-server-purple" alt="MCP server">
</p>

<p align="center"><b>Your database looks fine. Probably.</b></p>

**One call. One health report for your database.** An MCP server that lets
Claude, Cursor, or any MCP client run a real checkup on your **MySQL**
database — slow queries, missing indexes, fragmentation, dead-weight
indexes — and returns a single scored report with a concrete fix for every
finding. PostgreSQL is supported too.

> Ask your agent: **"What's wrong with my database?"** — and watch it run
> `health_report` instead of guessing.

<p align="center">
  <img src="docs/health-card.svg" alt="Sample health report card: score 44/100, grade D, with per-category findings" width="640">
</p>

## How it works

```mermaid
flowchart LR
    A["💬 You ask:<br/>'What's wrong with my database?'"] --> B["🤖 MCP client<br/>(Claude, Cursor, ...)"]
    B -->|health_report| C["🩺 db-health-mcp"]
    C -->|read-only SELECTs| D[("MySQL 8 / PostgreSQL 16<br/>performance_schema · sys · pg_stat")]
    C --> E["📋 Scored report<br/>0–100 + grade · findings by severity<br/>fix SQL for every finding"]
```

## The headline: `health_report`

Most database MCP servers hand the agent a bag of small tools and let it
improvise. `health_report` runs every check at once and folds the results
into one report:

- **Score 0–100 with a letter grade** (transparent heuristic: severity
  deductions, capped per category — see `src/db_health_mcp/report.py`)
- **Findings sorted by severity**, each with the numbers behind it
- **A suggested fix per finding**, as SQL text — e.g. the exact
  `CREATE INDEX` / `OPTIMIZE TABLE` / `DROP INDEX` statement. The server is
  read-only: it proposes fixes, it never executes them.

Sample output (abridged, from a real run against MySQL 8.0.46):

```markdown
# Database health report (mysql)

**Score: 44/100 (grade D)**

- Server: 8.0.46-0ubuntu0.24.04.5
- Database size: 5.2 MB
- Active connections: 2
- Largest table: healthdemo.logs (2.5 MB)

Findings: 14 (1 high, 3 warning, 10 info)

## [HIGH] Table bloat / fragmentation: healthdemo.logs

80% of the table's allocated space is free (10.0 MB of 12.5 MB), left
behind by deletes/updates.

Suggested fix: `OPTIMIZE TABLE `healthdemo`.`logs`;`

## [WARNING] Missing indexes: healthdemo.orders

Full table scans have read 600,000 rows from this ~19,922-row table
(30 full passes).

Suggested fix: `CREATE INDEX idx_orders_<column> ON `healthdemo`.`orders` (<column>); ...`

## [INFO] Unused indexes: healthdemo.users

Index has never been used since the server started, but still costs write
overhead on every insert/update.

Suggested fix: `DROP INDEX `idx_nickname_unused` ON `healthdemo`.`users`;`
```

Verified end to end against live **MySQL 8.0.46** and **PostgreSQL 16.15**
(all six tools, both engines), plus 30 unit tests with mocked rows.

## Individual check tools

For follow-up questions, each check is also a tool of its own:

| Tool | MySQL source | PostgreSQL source |
| --- | --- | --- |
| `db_overview` | version, size, connections, largest tables | same |
| `slow_queries` | `performance_schema` statement digests | `pg_stat_statements` |
| `missing_indexes` | `sys.schema_tables_with_full_table_scans` | sequential-scan stats |
| `table_bloat` | InnoDB fragmentation (`information_schema.data_free`) | dead-tuple ratio |
| `index_usage` | `sys.schema_unused_indexes` | `pg_stat_user_indexes` |

The engine is picked automatically from the connection-string scheme
(`mysql://` vs `postgresql://`), and every tool accepts an optional
`database_url` argument, so one server instance can check several
databases.

**Read-only by design.** Sessions are opened read-only
(`SET SESSION TRANSACTION READ ONLY` / `default_transaction_read_only=on`)
with a statement timeout, and every query is a `SELECT` against
catalog/statistics views. The server cannot modify your database.

## Quick start

```bash
pip install db-health-mcp   # or: pip install -e . from a clone
```

### Claude Code

```bash
claude mcp add db-health \
  -e DATABASE_URL=mysql://user:pass@localhost:3306/mydb \
  -- db-health-mcp
```

### Cursor / other MCP clients

```json
{
  "mcpServers": {
    "db-health": {
      "command": "db-health-mcp",
      "env": {
        "DATABASE_URL": "mysql://user:pass@localhost:3306/mydb"
      }
    }
  }
}
```

PostgreSQL works the same way with a `postgresql://` URL.

Then just ask:

- "What's wrong with my database?"
- "Give my database a health check and list the fixes in priority order."
- "Which tables are missing indexes?"
- "Are there any indexes I can safely drop?"

## Notes

- MySQL checks need MySQL 8 with `performance_schema` and the `sys` schema
  enabled (both are defaults). If statement digests are unavailable,
  `slow_queries` tells you how to enable them instead of failing; the other
  checks still run.
- PostgreSQL `slow_queries` needs the `pg_stat_statements` extension; same
  deal — you get enable instructions, not an error.
- Statistics accumulate over time (MySQL: since server start; PostgreSQL:
  since the last stats reset) — on a freshly restarted database the
  scan/index findings need some real traffic before they mean much.
- Use a least-privilege, read-only database user for extra safety.

## Development

```bash
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
pytest                      # unit tests (mocked rows, no live DB needed)
python scripts/selftest.py  # MCP handshake + tool list + error paths
```

## Roadmap

- [ ] MariaDB compatibility pass (the `sys` schema and `max_execution_time` differ slightly)
- [ ] SQLite quick-check for local dev databases
- [ ] `explain_query` tool: run `EXPLAIN` on a query and interpret the plan
- [ ] Lock contention and long-running transaction checks
- [ ] Replication lag check
- [ ] A sibling project: cloud capacity/quota checks for AWS/GCP

## License

MIT
