# MySQL MCP [Health: Active]

**Category:** 🗄️ Databases  
**Repository:** https://github.com/gistrec/mcp-mysql-client  
**GitHub Stars:** 0  
**npm Downloads (last month):** 764  
**Views:** 17  
**Installs:** 0  
**Upvotes:** 0  
**Directory Page:** https://allmcps.com/mcp/mysql-mcp

## Description
MCP server for one MySQL database: schema, read-only queries and guarded writes.

## Tools
Capabilities this server exposes over MCP:

- **server_info** — Показывает, к какой базе и под каким пользователем подключён сервер, версию MySQL, размер базы, выданные пользователю права (GRANT) и действующие ограничения самого MCP-сервера: разрешённые операции записи, потолок строк в ответе и таймаут запроса. Стоит вызвать первым, если непонятно, почему запрос отклонён: права MySQL и разрешения сервера — это два независимых ограничения.
- **list_tables** — Перечисляет таблицы и представления подключённой базы: движок, кодировку, комментарий, размер данных и индексов в байтах и оценку числа строк. Оценка берётся из статистики InnoDB и может заметно расходиться с реальностью — точное число даёт COUNT(*) через query. С этого инструмента стоит начинать знакомство с незнакомой базой.
- **describe_table** — Показывает структуру таблицы: столбцы с типами, обнуляемостью, значениями по умолчанию и комментариями, индексы с их составом, внешние ключи наружу и, главное, ссылки на эту таблицу из других (referenced_by) — именно они определяют, безопасно ли удалять строки. Разделы, кроме столбцов, можно отключить, если нужен только их список.
- **query** — Выполняет один читающий запрос (SELECT, SHOW, DESCRIBE, WITH ... SELECT) и возвращает строки. Изменяющие запросы отклоняются даже при включённых правах на запись — для них есть execute. Запрос идёт внутри read-only транзакции, число строк ограничено MYSQL_MAX_ROWS: если ответ обрезан, поле truncated равно true и это префикс, а не весь результат. Значения подставляйте через ? и params — драйвер экранирует их сам.
- **explain** — Возвращает план выполнения читающего запроса: какие индексы будут использованы и сколько строк сервер рассчитывает просмотреть. Обычный режим ничего не выполняет; analyze=true запускает запрос по-настоящему и показывает фактическое время — на больших таблицах это дорого. Полезно перед тяжёлой выборкой и при диагностике медленных запросов.
- **execute** — Выполняет один изменяющий запрос — INSERT, UPDATE, DELETE или REPLACE — и возвращает число затронутых строк. Сейчас сервер разрешает: только чтение. Права выдаются переменными ALLOW_INSERT_OPERATION, ALLOW_UPDATE_OPERATION и ALLOW_DELETE_OPERATION в конфигурации MCP-клиента и требуют перезапуска сервера — из диалога их получить нельзя. DDL (CREATE, ALTER, DROP, TRUNCATE) не поддерживается ни при каких настройках. Запрос выполняется сразу и без транзакции: откатить его отсюда нельзя. UPDATE и DELETE без WHERE и LIMIT требуют явного allow_full_table=true.

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

```json
"mcpServers": {
  "mysql-mcp": {
    "command": "npx",
    "args": ["-y","mcp-mysql-client"],
    "env": {
      "MYSQL_USER": "",
      "MYSQL_DB": ""
    }
  }
}
```

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

## Documentation

## What MySQL MCP does

MySQL MCP gives an MCP-compatible AI client access to one MySQL or MariaDB database. The database is selected in the server configuration, so a running instance cannot switch to another database through a tool call. To work with multiple databases, configure separate server entries and credentials for each one.

The default posture is read-only. Agents can inspect tables and relationships, run supported read queries, and examine execution plans without changing data. INSERT, UPDATE, and DELETE can be enabled independently through environment variables, but both the MCP setting and the connected MySQL account's GRANT permissions must allow the operation. DDL remains unavailable, including CREATE, ALTER, DROP, TRUNCATE, and RENAME.

## How it works

The server provides six tools:

- `server_info` reports the selected database, connected MySQL user, server version, database size, MySQL grants, and MCP-side limits.
- `list_tables` returns tables and views with engine, character set, comments, storage sizes, and an estimated row count. InnoDB estimates may differ from an exact `COUNT(*)`.
- `describe_table` shows columns, types, nullability, defaults, comments, indexes, outgoing foreign keys, and tables that reference the target.
- `query` accepts one read statement, including SELECT, SHOW, DESCRIBE, and suitable WITH queries. Parameters use `?` placeholders and a separate `params` value.
- `explain` returns an execution plan. With `analyze=true`, it runs the query to report actual timing, which can be expensive for large tables.
- `execute` runs one INSERT, UPDATE, DELETE, or REPLACE statement and returns affected-row counts.

Read queries run in read-only transactions when that setting is enabled, and their results are streamed up to `MYSQL_MAX_ROWS`. A response exceeding that limit is a prefix of the result and carries a `truncated` indicator. Each call contains one statement. UPDATE and DELETE statements without WHERE or LIMIT require `allow_full_table=true` in the call.

## Setup and configuration

Run the npm package with `npx -y mcp-mysql-client` from an MCP client configuration. Set `MYSQL_USER` and `MYSQL_DB`, along with the connection details required by the target environment. `MYSQL_HOST` defaults to `127.0.0.1`, `MYSQL_PORT` to `3306`, and `MYSQL_PASS` accepts a password; `MYSQL_PASSWORD` is an alias. `MYSQL_SOCKET_PATH` can select a Unix socket instead of host and port, while `MYSQL_PASS_FILE` reads the password from a file.

TLS can be required with `MYSQL_SSL=true`. Providing `MYSQL_SSL_CA` also enables TLS, and `MYSQL_SSL_REJECT_UNAUTHORIZED` controls certificate verification. `MYSQL_TIMEOUT_MS`, `MYSQL_CONNECT_TIMEOUT_MS`, `MYSQL_POOL_SIZE`, and `MYSQL_MAX_RETRIES` tune query timeout, connection timeout, pool size, and retry behavior.

Set `ALLOW_INSERT_OPERATION`, `ALLOW_UPDATE_OPERATION`, or `ALLOW_DELETE_OPERATION` to `true` to enable the corresponding write type. These changes require a server restart and do not grant permissions in MySQL. `MYSQL_READ_ONLY_TX` controls read-only transaction behavior, and `ASKADS_TELEMETRY=0` disables anonymous tool-call startup statistics.

## Tools and capabilities

A practical discovery sequence is `server_info`, `list_tables`, and `describe_table`, followed by `query` for exact counts or filtered data. `explain` is useful before running expensive reads or investigating slow SQL. Foreign-key references returned by `describe_table` help identify dependencies before deleting rows.

Use a least-privileged MySQL account rather than an administrative account. The server blocks session-changing or unsafe operations such as SET, CALL, PREPARE, LOAD DATA, locking statements, GRANT, and SELECT ... INTO OUTFILE. It also rejects multiple statements in one request.

## Limitations and notes

`execute` is immediate and does not provide a rollback facility through the server. Enabling an MCP write flag is not enough when the MySQL account lacks the matching grant. The server cannot perform DDL under any configuration, and read responses may be incomplete when the row ceiling is reached. Start with `server_info` when a request is rejected, because database grants and MCP restrictions are separate layers.

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

