Skip to main content
Glama
mcp-mysql-client

mcp-mysql-client

MySQL MCP

npm CI License: MIT

MySQL MCP connects an AI application to a single MySQL or MariaDB database: view the schema, ask questions about the data in natural language, find out why a query is slow, and — if you have explicitly allowed it — change the data.

The server is bound to one database: the database is set through the configuration, and no tool can escape into any other. By default, only read access is available.

  • 6 tools. Connection and permissions, list tables, table structure, read query, query plan, modifying query.

  • The server determines the request type. SQL is parsed before connecting: DELETE in the read tool is rejected even if write permissions are enabled.

  • Reads cannot write. Read queries run inside START TRANSACTION READ ONLY — MySQL itself rejects the write even if the SQL parser is tricked.

  • The response will not overflow the context. Rows are read as a stream and are cut off at the limit instead of being loaded entirely; the response carries an honest truncated marker.

  • Permissions are only granted from outside. INSERT, UPDATE, and DELETE are switched on by environment variables and require a restart — they cannot be granted from a chat. DDL is always unavailable.

Start with a query that only reads data:

Show me the database schema and count how many records were added in the last week.


Quick start

Claude Code:

claude mcp add mysql-myapp \
  -e MYSQL_HOST=db.example.com \
  -e MYSQL_USER=myapp_ro \
  -e MYSQL_PASS='пароль' \
  -e MYSQL_DB=myapp \
  -e MYSQL_SSL=true \
  -- npx -y mcp-mysql-client

Or in .mcp.json / claude_desktop_config.json:

{
  "mcpServers": {
    "mysql-myapp": {
      "command": "npx",
      "args": ["-y", "mcp-mysql-client"],
      "env": {
        "MYSQL_HOST": "db.example.com",
        "MYSQL_PORT": "3306",
        "MYSQL_USER": "myapp_ro",
        "MYSQL_PASS": "пароль",
        "MYSQL_DB": "myapp",
        "MYSQL_SSL": "true"
      }
    }
  }
}

One server — one database. Need several databases? Add several entries with their own credentials: this keeps permissions isolated, and a server connected to the test database physically cannot see the production one.

Related MCP server: mysql-mcp

What can you assign

Request

What the server does

"What is there at all in this database?"

list_tables — tables, sizes, estimated row counts

"How is the orders table structured?"

describe_table — columns, indexes, foreign keys both ways

"How many orders were placed in July, and for how much?"

query — SELECT with aggregation

"Why is this query slow?"

explain — plan, indexes, row estimate

"Who am I connected as and what am I allowed to do?"

server_info — database, user, GRANT, server limits

"Set the status of the canceled orders."

execute — only when ALLOW_UPDATE_OPERATION=true

What can change

By default, nothing: the server starts in read-only mode. Writing is enabled per operation:

"ALLOW_INSERT_OPERATION": "true",
"ALLOW_UPDATE_OPERATION": "true",
"ALLOW_DELETE_OPERATION": "false"

What remains impossible:

What

Why

DDL

CREATE, ALTER, DROP, TRUNCATE, RENAME — under no settings.

Switching databases, SET, CALL, PREPARE, LOAD DATA, locks, and GRANT

Changes the meaning of the next query or executes untrusted text.

SELECT ... INTO OUTFILE

Writing a file on the database server.

UPDATE and DELETE without WHERE

Requires explicit allow_full_table=true in the call.

Multiple statements in one call

Executes exactly one.

MySQL privileges are a separate restriction on top of the above. The ALLOW_UPDATE_OPERATION permission does not give anything to a user without a GRANT UPDATE. Best practice: a dedicated user with minimal privileges, not root.

Environment variables

Variable

Default

Purpose

MYSQL_HOST

127.0.0.1

Database server host

MYSQL_PORT

3306

Port

MYSQL_SOCKET_PATH

—

Unix socket instead of host/port

MYSQL_USER

—

User (required)

MYSQL_PASS

—

Password (alias of MYSQL_PASSWORD)

MYSQL_PASS_FILE

—

Read the password from a file instead of a variable

MYSQL_DB

—

Database (required, alias of MYSQL_DATABASE)

MYSQL_SSL

false

Require TLS

MYSQL_SSL_CA

—

Path to the root certificate; it alone enables TLS

MYSQL_SSL_REJECT_UNAUTHORIZED

true

Verify the server certificate

ALLOW_INSERT_OPERATION

false

Allow INSERT

ALLOW_UPDATE_OPERATION

false

Allow UPDATE

ALLOW_DELETE_OPERATION

false

Allow DELETE

MYSQL_MAX_ROWS

1000

Maximum rows in one response

MYSQL_TIMEOUT_MS

30000

Query timeout

MYSQL_CONNECT_TIMEOUT_MS

10000

Connection timeout

MYSQL_POOL_SIZE

3

Connections in the pool

MYSQL_MAX_RETRIES

2

Retries on connection loss or deadlocks

MYSQL_READ_ONLY_TX

true

Run reads in a read-only transaction

ASKADS_TELEMETRY

—

0 turns off anonymous launch statistics

The password is present in the MCP client config in plain text. MYSQL_PASS_FILE lets you keep it in a file with the required permissions.

Migration from @benborla29/mcp-server-mysql

The variable names are the same, so just replace the package in the launch command:

-  "args": ["-y", "@benborla29/mcp-server-mysql"]
+  "args": ["-y", "mcp-mysql-client"]

What will change in behavior:

Behavior

Change

MYSQL_DB is mandatory

The server is always bound to one database.

Responses are limited by MYSQL_MAX_ROWS

Answers are marked as truncated.

DDL is unavailable

Even if write permissions are enabled.

UPDATE/DELETE without WHERE

They require explicit confirmation in the call.

The toolset is different

query, execute, explain, list_tables, describe_table, server_info.

Diagnostics

First, call server_info: it shows where the server has connected, what permissions the MySQL user has, and which limits are enabled.

Symptom

Cause

errno 1045

Invalid MYSQL_USER / MYSQL_PASS

errno 1044

The user exists, but has no access to the database.

errno 1142

Missing GRANT for the operation or table. ALLOW_* does not help here.

errno 3159

The server requires TLS: set MYSQL_SSL=true.

ECONNREFUSED / ETIMEDOUT

Host, port, firewall, or a VPN that isn’t up.

ER_NOT_SUPPORTED_AUTH_MODE

TLS is required for caching_sha2_password.

Server doesn’t connect

The configuration error is visible directly in the dialog: the server starts without credentials and explains what is missing.

Technical documentation

  • Tools — parameters and responses

  • Development — building, tests, live verification

  • Publishing — releases in npm and the MCP registry

  • CLAUDE.md — repository layout for AI agents

License

MIT

Available Tools

6 tools
describe_tableСтруктура таблицыA
Read-onlyIdempotent

Показывает структуру таблицы: столбцы с типами, обнуляемостью, значениями по умолчанию и комментариями, индексы с их составом, внешние ключи наружу и, главное, ссылки на эту таблицу из других (referenced_by) — именно они определяют, безопасно ли удалять строки. Разделы, кроме столбцов, можно отключить, если нужен только их список.

Inputs: table (required), include_indexes, include_foreign_keys.

executeВыполнить изменяющий SQL-запросA
Destructive

Выполняет один изменяющий запрос — 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.

Inputs: sql (required), params, allow_full_table.

explainПоказать план выполнения запросаA
Read-onlyIdempotent

Возвращает план выполнения читающего запроса: какие индексы будут использованы и сколько строк сервер рассчитывает просмотреть. Обычный режим ничего не выполняет; analyze=true запускает запрос по-настоящему и показывает фактическое время — на больших таблицах это дорого. Полезно перед тяжёлой выборкой и при диагностике медленных запросов.

Inputs: sql (required), format, params, analyze.

list_tablesСписок таблиц базыA
Read-onlyIdempotent

Перечисляет таблицы и представления подключённой базы: движок, кодировку, комментарий, размер данных и индексов в байтах и оценку числа строк. Оценка берётся из статистики InnoDB и может заметно расходиться с реальностью — точное число даёт COUNT(*) через query. С этого инструмента стоит начинать знакомство с незнакомой базой.

Inputs: no named parameters.

queryВыполнить читающий SQL-запросA
Read-onlyIdempotent

Выполняет один читающий запрос (SELECT, SHOW, DESCRIBE, WITH ... SELECT) и возвращает строки. Изменяющие запросы отклоняются даже при включённых правах на запись — для них есть execute. Запрос идёт внутри read-only транзакции, число строк ограничено MYSQL_MAX_ROWS: если ответ обрезан, поле truncated равно true и это префикс, а не весь результат. Значения подставляйте через ? и params — драйвер экранирует их сам.

Inputs: sql (required), limit, params.

server_infoСведения о подключении и правахA
Read-onlyIdempotent

Показывает, к какой базе и под каким пользователем подключён сервер, версию MySQL, размер базы, выданные пользователю права (GRANT) и действующие ограничения самого MCP-сервера: разрешённые операции записи, потолок строк в ответе и таймаут запроса. Стоит вызвать первым, если непонятно, почему запрос отклонён: права MySQL и разрешения сервера — это два независимых ограничения.

Inputs: no named parameters.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.4/5.0

    Scored across 6 tools

    Disambiguation5/5

    Each tool has a clearly distinct purpose: server_info covers connection state, list_tables and describe_table cover schema discovery, query executes read-only SQL, explain returns execution plans, and execute handles mutations. The only mild overlap is between query and explain, but their outputs and use cases are sufficiently different that an agent should not select the wrong one.

    Naming Consistency3/5

    The tool names are all lowercase and readable, but they do not follow one consistent pattern: list_tables and describe_table use verb_noun, explain and execute are bare verbs, while server_info and query are noun-style names. This is a mixed convention rather than a chaotic one, but it still falls short of a uniform naming scheme.

    Tool Count5/5

    Six tools is a well-scoped set for a MySQL client server. Each tool covers a distinct part of the interaction surface: server diagnostics, table enumeration, schema inspection, read queries, query planning, and write execution, so none feel redundant or missing.

    Completeness5/5

    The tool set covers the full expected workflow for a MySQL client: understand the environment, discover tables, inspect schema, run read queries, analyze plans, and perform DML writes. DDL and transactions are explicitly excluded by design, so their absence is not an unexpected gap within the server's declared scope.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      D
      maintenance
      Enables AI agents to safely interact with MySQL/MariaDB databases, supporting read-only queries by default with optional write operations and access control.
      8
      MIT
    • A
      license
      A
      quality
      D
      maintenance
      Enables AI agents to query and manage MySQL databases through a structured MCP interface, supporting SQL execution, table inspection, and database operations.
      9
      11 npm
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables AI agents to query and modify MySQL and MariaDB databases over MCP, with each connection independently permitting selects, inserts, updates, deletes, and DDL while defaulting to read-only and rejecting anything outside the allowed operations. Connections are configured in JSON, result sets are capped and truncated, and passwords stay server-side.
      MIT