# MySQL AIops [Health: Active]

**Category:** 🗄️ Databases  
**Repository:** https://github.com/AIops-tools/MySQL-AIops  
**GitHub Stars:** 0  
**Views:** 4  
**Installs:** 0  
**Upvotes:** 0  
**Directory Page:** https://allmcps.com/mcp/mysql-aiops

## Description
Governed MySQL/MariaDB DBA ops: slow-query, lock-wait, replication & fragmentation RCA; 33 tools.

## Tools
Capabilities this server exposes over MCP:

- **list_sessions** — [READ] Current sessions (processlist) with per-command counts.

    Flags sleeping sessions (connection-pool leak suspects).

    Args:
        include_sleeping: Include sessions in command=Sleep (default True).
        target: Target name from config; omit for the default.
    
- **long_running_queries** — [READ] Active statements running at least ``min_seconds``, oldest first.

    Args:
        min_seconds: Minimum age in seconds (default 60).
        target: Target name from config; omit for the default.
    
- **list_transactions** — [READ] Open InnoDB transactions, oldest first (stuck-transaction hunting).

    Args:
        target: Target name from config; omit for the default.
    
- **lock_waits** — [READ] InnoDB wait-for edges (blocked session -> blocking session).

    Reads performance_schema.data_lock_waits on MySQL 8.x, or
    information_schema.innodb_lock_waits on MariaDB (flavor-branched).

    Args:
        target: Target name from config; omit for the default.
    
- **slow_query_rca** — [READ] RCA for the worst statement digest, with cause + action.

    Picks the digest with the greatest total time and maps its numbers
    (no-index share, lock-time share, examined/sent ratio, tmp-disk spill,
    calls) — plus an optional EXPLAIN plan — to cited causes and concrete
    actions. Pass 'statements' for pure/offline analysis, or omit to pull the
    top digests live from performance_schema.

    Args:
        statements: Injected digest rows (as from top_queries); if omitted,
            the worst statements are pulled live.
        explain_sql: Optional SQL to EXPLAIN so plan access types feed the RCA.
        limit: How many statements to pull when not injected (default 20).
        target: Target name from config; omit for the default.
    
- **lock_wait_rca** — [READ] Build the InnoDB wait-for tree, name the root blocker, and parse
    the last deadlock out of SHOW ENGINE INNODB STATUS.

    Pass 'pairs' (as from lock_waits) for pure/offline analysis, or omit to
    pull the current lock-wait graph live.

    Args:
        pairs: Injected lock-wait pairs {blockedId, blockingId, ...}; if
            omitted, pulled live (flavor-branched).
        include_deadlock: Also parse the LATEST DETECTED DEADLOCK section from
            SHOW ENGINE INNODB STATUS (default True).
        target: Target name from config; omit for the default.
    
- **replication_lag_rca** — [READ] Map replica thread state / lag / error fields to cause + action.

    Pass 'status' (as from replica_status) for pure/offline analysis, or omit
    to pull the live replica status (flavor-branched).

    Args:
        status: Injected replica status record; if omitted, pulled live.
        target: Target name from config; omit for the default.
    
- **fragmentation_analysis** — [READ] Rank tables by reclaimable data_free into OPTIMIZE TABLE candidates.

    Pass 'tables' (as from table_fragmentation) for pure/offline analysis, or
    omit to pull the worst-fragmented tables live. Each recommendation cites
    its numbers.

    Args:
        tables: Injected fragmentation rows; if omitted, pulled live.
        limit: How many tables to pull when not injected (default 50).
        target: Target name from config; omit for the default.
    
- **unused_indexes** — [READ] Secondary indexes with zero I/O events since restart (drop candidates).

    From performance_schema.table_io_waits_summary_by_index_usage — counters
    reset on server restart, so confirm over a full business cycle.

    Args:
        target: Target name from config; omit for the default.
    
- **redundant_indexes** — [READ] Indexes whose columns are a leading prefix of another index (dupes).

    Args:
        target: Target name from config; omit for the default.
    
- **index_stats** — [READ] Per-index column lists and cardinality (selectivity screening).

    Args:
        target: Target name from config; omit for the default.
    
- **top_queries** — [READ] Top statement digests from performance_schema by a whitelisted metric.

    Args:
        order_by: One of total_time, mean_time, calls, rows_examined,
            lock_time, no_index.
        limit: Number of statements to return (1..200, default 20).
        target: Target name from config; omit for the default.

    Returns an envelope: {"statements": [...], "returned": N, "limit": L,
    "truncated": bool}. When "truncated" is true there is more beyond what
    was returned — re-run with a higher limit rather than treating this as
    the complete picture.
    
- **explain_query** — [READ] Return the JSON execution plan for ``sql`` (EXPLAIN FORMAT=JSON).

    The statement is planned, not executed.

    Args:
        sql: A single SQL statement to EXPLAIN.
        target: Target name from config; omit for the default.
    
- **reset_query_stats** — [WRITE][risk=medium] Reset statement-digest accumulators (irreversible).

    Truncates performance_schema.events_statements_summary_by_digest; the
    counters cannot be restored, so no undo is recorded. Pass dry_run=True
    to preview.

    Args:
        dry_run: If True, preview without resetting.
        target: Target name from config; omit for the default.
    
- **kill_session** — [WRITE][risk=high] Terminate a session (KILL CONNECTION). No safe inverse.

    Captures the session's user/host/query for the audit trail; a kill cannot
    be undone, so no undo is offered. Pass dry_run=True to preview.

    Refuses this tool's own session id — including under dry_run, which must
    report a refusal rather than preview a call that will be refused.

    Args:
        session_id: Session/connection id (from list_sessions).
        dry_run: If True, preview without killing.
        target: Target name from config; omit for the default.
    
- **kill_query** — [WRITE][risk=high] Cancel a session's running statement (KILL QUERY). No inverse.

    The session stays connected; only its current statement is aborted.
    Captures the session's user/host/query for audit. Pass dry_run=True to
    preview.

    Refuses this tool's own session id — the statement it would cancel is this
    very call. Enforced under dry_run too.

    Args:
        session_id: Session/connection id (from list_sessions).
        dry_run: If True, preview without cancelling.
        target: Target name from config; omit for the default.
    
- **optimize_table** — [WRITE][risk=medium] OPTIMIZE TABLE (rebuild, reclaim data_free). Records prior stats.

    No undo (a rebuild has no inverse); the prior size/fragmentation stats are
    captured for the audit trail. InnoDB maps this to ALTER TABLE ... FORCE
    (online DDL, brief locks) — schedule off-peak for hot tables. Pass
    dry_run=True to preview.

    Args:
        table: Table name (optionally schema-qualified, e.g. shop.orders).
        dry_run: If True, preview without running.
        target: Target name from config; omit for the default.
    
- **analyze_table** — [WRITE][risk=medium] ANALYZE TABLE to refresh index statistics.

    No undo; captures prior stats for audit. Takes a brief read lock while
    sampling. Pass dry_run=True to preview.

    Args:
        table: Table name (optionally schema-qualified).
        dry_run: If True, preview without running.
        target: Target name from config; omit for the default.
    
- **create_index** — [WRITE][risk=medium] Create an index. Reversible: undo drops the created index.

    The created (table, name) is returned so the harness records an undo that
    drops exactly this index. Pass dry_run=True to preview. Alternatively pass
    ``definition`` (a captured CREATE INDEX statement — this is how
    drop_index's undo descriptor replays) INSTEAD of table/columns.

    Args:
        table: Table to index (optionally schema-qualified). Required unless
            ``definition`` is given.
        columns: Column names to index. Required unless ``definition`` is given.
        name: Index name (auto-generated from table+columns when omitted).
        unique: Create a UNIQUE index.
        definition: A full CREATE [UNIQUE] INDEX statement to execute verbatim
            (shape-validated). Mutually exclusive with table/columns.
        dry_run: If True, preview without creating.
        target: Target name from config; omit for the default.
    
- **drop_index** — [WRITE][risk=high] Drop an index. Reversible: captures its definition first.

    Before dropping, the exact index definition is rebuilt from SHOW CREATE
    TABLE so the harness records an undo that recreates it. Pass dry_run=True
    to preview.

    Args:
        table: Table the index belongs to (optionally schema-qualified).
        name: Index name to drop.
        dry_run: If True, preview without dropping.
        target: Target name from config; omit for the default.
    
- **set_global_variable** — [WRITE][risk=medium] SET GLOBAL a server variable. Reversible: captures prior value.

    Runtime-only: the change does not survive a restart (persist it in my.cnf
    — or SET PERSIST on MySQL 8 — yourself); reported but NOT performed
    automatically. The prior value (from SHOW GLOBAL VARIABLES) is captured so
    the harness records an undo that sets it back. Pass dry_run=True to
    preview.

    Refuses the globals that would lock this tool out of the server
    (init_connect, max_connections, max_user_connections, read_only,
    super_read_only, skip_networking, require_secure_transport, and
    wait_timeout/interactive_timeout below 30s). SET GLOBAL is immediate, so
    those strand the undo. Enforced under dry_run too.

    Args:
        name: The global variable name (e.g. max_connections).
        value: The new value (as a string).
        dry_run: If True, preview without changing.
        target: Target name from config; omit for the default.
    
- **replica_status** — [READ] Replica thread state and lag (SHOW REPLICA/SLAVE STATUS, flavor-branched).

    Empty on a primary/standalone server. MySQL 8.x uses SHOW REPLICA STATUS;
    MariaDB uses SHOW SLAVE STATUS — the result is normalised either way.

    Args:
        target: Target name from config; omit for the default.
    
- **binlog_status** — [READ] Binary-log configuration, GTID mode, and connected downstream replicas.

    Args:
        target: Target name from config; omit for the default.
    
- **overview** — [READ] One-shot server health snapshot.

    Version + flavor (mysql/mariadb) + uptime, connection headroom vs
    max_connections, sessions by command, the longest-running query, the most
    fragmented table, and the replica role — each section captured defensively
    so one failing probe does not sink the rest.

    Args:
        target: Target name from config; omit for the default.
    
- **server_version** — [READ] Server version, flavor (mysql/mariadb), uptime and read-only state.

    Args:
        target: Target name from config; omit for the default.
    
- **show_variables** — [READ] Global variables (SHOW GLOBAL VARIABLES).

    Args:
        pattern: Optional substring to filter variable names
            (e.g. 'innodb_buffer', 'max_connections').
        target: Target name from config; omit for the default.
    
- **show_status** — [READ] Global status counters (SHOW GLOBAL STATUS).

    Args:
        pattern: Optional substring to filter counter names
            (e.g. 'Threads', 'Innodb_buffer_pool').
        target: Target name from config; omit for the default.
    
- **list_databases** — [READ] User schemas with table count and data/index size (largest first).

    Args:
        target: Target name from config; omit for the default.
    
- **list_engines** — [READ] Storage engines and which is the default (SHOW ENGINES).

    Args:
        target: Target name from config; omit for the default.
    
- **connection_stats** — [READ] Connection counters vs max_connections (exhaustion early warning).

    Args:
        target: Target name from config; omit for the default.
    
- **table_sizes** — [READ] Largest tables by data + index size.

    Args:
        limit: Number of tables to return, largest first (default 20).
        target: Target name from config; omit for the default.

    Returns an envelope: {"tables": [...], "returned": N, "limit": L,
    "truncated": bool}. When "truncated" is true there is more beyond what
    was returned — re-run with a higher limit rather than treating this as
    the complete picture.
    
- **table_fragmentation** — [READ] data_free per table (space OPTIMIZE TABLE could reclaim), worst first.

    Args:
        limit: Number of tables to inspect (default 50).
        target: Target name from config; omit for the default.

    Returns an envelope: {"tables": [...], "returned": N, "limit": L,
    "truncated": bool}. When "truncated" is true there is more beyond what
    was returned — re-run with a higher limit rather than treating this as
    the complete picture.
    
- **table_status** — [READ] Per-table engine, row format, row estimate and last update time.

    Flags non-InnoDB tables (no row-level locking / crash recovery).

    Args:
        limit: Number of tables to inspect (default 50).
        target: Target name from config; omit for the default.

    Returns an envelope: {"tables": [...], "returned": N, "limit": L,
    "truncated": bool}. When "truncated" is true there is more beyond what
    was returned — re-run with a higher limit rather than treating this as
    the complete picture.
    
- **undo_list** — [READ] List recorded, not-yet-applied undo tokens (most recent first).

    Each entry names the original tool, the inverse tool that ``undo_apply``
    would run, and a human note. Use the ``undoId`` with ``undo_apply``.

    Returns {"undos": [...], "returned": N, "limit": L, "truncated": bool}.
    ``truncated`` is *measured* (one extra row is fetched), not guessed from a
    length coincidence: when it is true there are MORE tokens than shown, so
    re-run with a higher ``limit`` rather than reporting the list as complete.

    Each entry carries ``effectVerified``. False means the original write lost
    its response, so the change it reverses is PROBABLE, not confirmed — check
    the live state before applying, and do not report the result as a restore
    of a state that may never have been reached.

    Args:
        limit: Max rows to return (default 50, capped at 500).
        target: Unused (undo state is host-local); accepted for CLI uniformity.
    
- **undo_apply** — [WRITE][risk=medium] Apply a recorded undo by dispatching its inverse tool.

    The inverse runs through its own governed tool, so its own risk tier and
    audit row are recorded there. Pass dry_run=True to preview
    the inverse call without executing it. A token can only be applied once.

    Args:
        undo_id: The undoId from undo_list (or an ``_undo_id`` in a write result).
        dry_run: If True, preview the inverse tool + params without running it.
        target: Passed through to the inverse tool when it accepts a target.
    

## Claude Desktop Quick Installation
Install path detected from listing signals. Uses `uvx` (confidence: high):

```json
"mcpServers": {
  "mysql-aiops": {
    "command": "uvx",
    "args": ["--from","mysql-aiops","mysql-aiops-mcp"],
    "env": {
      "MYSQL_AIOPS_MASTER_PASSWORD": ""
    }
  }
}
```

**Requires environment variables:** `MYSQL_AIOPS_MASTER_PASSWORD` — the values above are empty placeholders; fill in real credentials before running (see the repository for what each one is for).

## Documentation

## What MySQL AIops does

MySQL AIops exposes MySQL and MariaDB DBA operations through an MCP server and a companion CLI. Its main use is evidence-based investigation: slow-query, lock-wait and deadlock, replication-lag, and table-fragmentation analyses collect database measurements and turn them into cited causes and suggested actions.

The project targets MySQL 8.0 and 8.4, plus MariaDB 10.6 and later. It detects the database flavor from `version()` and selects flavor-specific statements, including the appropriate replication-status and lock-wait sources.

## How it works

The server connects with PyMySQL and reads database metadata and runtime instrumentation from `information_schema` and `performance_schema`. Flagship analyses can either process injected records for offline or pure analysis, or retrieve live data from a configured target. Slow-query analysis uses statement digest metrics and can include an `EXPLAIN FORMAT=JSON` plan. Lock analysis builds a wait-for tree and identifies the root blocker, while also parsing the last deadlock from InnoDB status. Replication analysis evaluates thread state, lag, and error fields. Fragmentation analysis ranks tables by reclaimable `data_free`.

All MCP and CLI calls pass through the bundled governance harness and create an audit row in `~/.mysql-aiops/audit.db`. Audit records include outcome summaries and descriptive risk tiers such as `none`, `confirm`, and `review`. The risk tier is informational; it does not approve or block an operation.

Writes require a committed pending audit row before the database platform is contacted. Read and preview operations can continue with a warning if audit storage is unavailable.

## Setup and configuration

Install the package with `uv tool install mysql-aiops` or `pipx install mysql-aiops`, then run `mysql-aiops init` to add a target and save its password. Credentials are stored in `~/.mysql-aiops/secrets.enc`, encrypted with Fernet and scrypt rather than written as plaintext. `mysql-aiops doctor` checks configuration, credentials, connectivity, detected flavor, and performance-schema readiness.

Run the standalone MCP process with `mysql-aiops-mcp`. For noninteractive use, set `MYSQL_AIOPS_MASTER_PASSWORD`; otherwise the CLI can request the master password interactively. The server uses stdio, so it can be added to an MCP client configuration such as Claude Desktop. Claude Code and OpenClaw integrations are also documented as bundled installation options.

## Tools and capabilities

The MCP surface contains 35 tools: 26 reads and 9 writes. Read coverage includes server metadata, variables, status, databases, engines, connections, sessions, long-running queries, transactions, lock waits, top queries, query plans, index usage, table sizes and status, replication, binlog state, the four RCA analyses, and undo inspection.

Write tools can kill sessions or queries, create or drop indexes, optimize or analyze tables, change global variables, reset query statistics, and apply recorded undo operations. Each write accepts a `dry_run` preview. CLI state-changing operations also support `--dry-run` and double confirmation.

Identifiers that cannot be bound as query parameters are checked against a strict character set and quoted with backticks; values use bound parameters. Mutations retrieve the real before-state and record an inverse when one exists. Dropped indexes can be recreated from their `SHOW CREATE TABLE` definition, and global-variable changes can restore the previous value.

## Limitations and notes

Slow-query tools and `slow_query_rca` require `performance_schema=ON`. A read account should have `SELECT` on `performance_schema`, plus `PROCESS` and `REPLICATION CLIENT`. Permission enforcement remains the responsibility of MySQL or MariaDB: use an account with only the privileges appropriate to the intended operation.

`kill_session`, `kill_query`, `optimize_table`, `analyze_table`, and `reset_query_stats` are treated as irreversible by the undo system, although their prior state is recorded for audit. MySQL 5.7 and older releases are outside the targeted support scope. Cloud-managed MySQL may support wire-compatible reads, but provider restrictions on operations such as `KILL` and `SET GLOBAL` apply and are untested.

_Full upstream README: https://allmcps.com/mcp/mysql-aiops/readme_

