Skip to main content
Glama
bomsan69

mysql-mcp-server

by bomsan69

mysql-mcp-server

Model Context Protocol (MCP) サーバーで、MCP クライアント(Claude Desktop、Claude Code など)が MySQL データベースに対して SQL を実行できるようにします。ツールは select、insert、update、delete の4つです。

このサーバーは uv 管理の Python パッケージとして動作し、クライアントが起動したサブプロセスとして stdio 経由でクライアントと通信します。

要件

  • Python 3.11+

  • uv

  • 到達可能な MySQL サーバー

Related MCP server: Universal Database MCP Server

インストール

uv sync

設定

サーバーには6つの値が必要です。各値は環境変数および/または CLI フラグで設定できます(CLI フラグは環境変数より優先されます):

パラメーター

環境変数

CLI フラグ

必須

デフォルト

モード

MYSQL_MODE

--mysql-mode

はい

—(readonly または readwrite)

ホスト

MYSQL_HOST

--mysql-host

はい

—

ポート

MYSQL_PORT

--mysql-port

いいえ

3306

ユーザー

MYSQL_USER

--mysql-user

はい

—

パスワード

MYSQL_PASSWORD

--mysql-password

はい

—

データベース

MYSQL_DATABASE

--mysql-database

はい

—

必要な値が欠けている場合、または MYSQL_MODE が readonly/readwrite でない場合、サーバーは stderr にエラーを出力し、起動せずに終了コード1で終了します。

  • readonly モード: select ツールのみが許可されます。insert/update/delete は PERMISSION_DENIED エラーで拒否されます。

  • readwrite モード: 4つすべてのツールが許可されます。

モードはプロセスの存続期間中固定され、実行時に変更することはできません。

セキュリティ上の推奨事項: readonly モードはアプリケーションレベルの保護であり、データベース権限の代わりにはなりません。可能な場合は、readonly モードの接続先として SELECT 権限のみを持つ MySQL アカウントを使用してください。

.env ファイルは必要ですか? いいえ。サーバー自体が .env ファイルを読み取ることはありません。読み取るのは CLI フラグと実際のプロセス環境変数(os.environ)だけです。その環境に値をどう渡すかは、実行方法によって異なります:

  • MCP サーバーとして使用する場合(下記の MCP クライアントから接続する を参照): クライアント(Claude Desktop/Code)がサーバープロセスを起動し、自身の JSON 設定の env ブロックを環境変数として直接注入します。.env ファイルは関与せず、必要もありません。

  • ローカル開発・テスト用に CLI を直接実行する場合: .env は、6つの変数を手動で export しなくて済むようにするための便宜上のものです。.env.example を .env にコピーし、実際の値を入力して、明示的に読み込んでください。自動的に読み込まれることはありません:

    uv run --env-file .env mysql-mcp-server

    .env は git で無視され、決してコミットしてはなりません。

実行

# Environment variables (or use `uv run --env-file .env mysql-mcp-server`, see above)
export MYSQL_MODE=readonly
export MYSQL_HOST=127.0.0.1
export MYSQL_PORT=3306
export MYSQL_USER=app_user
export MYSQL_PASSWORD=secret
export MYSQL_DATABASE=mydb
uv run mysql-mcp-server

# Or, equivalently, via CLI flags
uv run mysql-mcp-server \
  --mysql-mode readonly \
  --mysql-host 127.0.0.1 \
  --mysql-port 3306 \
  --mysql-user app_user \
  --mysql-password secret \
  --mysql-database mydb

MCP クライアントから接続する

Claude Desktop / Claude Code

MCP クライアントのサーバー設定にエントリを追加します(例: Claude Desktop の claude_desktop_config.json、Claude Code の場合は .mcp.json):

{
  "mcpServers": {
    "mysql": {
      "command": "uv",
      "args": [
        "--directory",
        "/absolute/path/to/mysql-mcp-server",
        "run",
        "mysql-mcp-server"
      ],
      "env": {
        "MYSQL_MODE": "readonly",
        "MYSQL_HOST": "127.0.0.1",
        "MYSQL_PORT": "3306",
        "MYSQL_USER": "app_user",
        "MYSQL_PASSWORD": "secret",
        "MYSQL_DATABASE": "mydb"
      }
    }
  }
}

設定を編集したらクライアントを再起動してください。select、insert、update、delete ツールが(MYSQL_MODE に応じて)モデルで利用できるようになります。

ツール

4つのツールはすべて {"query": string, "params"?: array} を受け取り、query 内では常に %s パラメーターバインディングのプレースホルダーを使用します。ユーザー入力を文字列としてクエリにフォーマットすることは決してありません。

ツール

許可されるモード

クエリの先頭キーワード

成功時の data の形式

select

すべてのモード

SELECT / WITH

{rows, row_count, truncated}(最大1000行)

insert

readwrite のみ

INSERT

{affected_rows, last_insert_id}

update

readwrite のみ

UPDATE

{affected_rows}(WHERE がない場合は warning を含む)

delete

readwrite のみ

DELETE

{affected_rows}(WHERE がない場合は warning を含む)

各ツール呼び出しは、次のいずれかを返します:

{ "success": true, "data": { ... } }
{ "success": false, "error": { "code": "...", "message": "..." } }

エラーコード: PERMISSION_DENIED、INVALID_QUERY_TYPE、MULTI_STATEMENT_NOT_ALLOWED、DB_CONNECTION_ERROR、DB_EXECUTION_ERROR、INTERNAL_ERROR。

マルチステートメントクエリ(; 区切り)および DDL・権限ステートメント(DROP、TRUNCATE、ALTER、GRANT、CREATE USER など)は常に拒否されます。受け付けられるのは、上記の許可された4種類のステートメントのみだからです。

開発

uv sync
uv run ruff format .
uv run ruff check .
uv run pytest -v
uv run uv build   # packaging check

トラブルシューティング

  • サーバーが終了コード1で即座に終了する: 必要な MYSQL_* の値が欠けているか、MYSQL_MODE が無効です。どれが原因かは stderr を確認してください。

  • DB_CONNECTION_ERROR: MySQL に到達できないか、認証情報が誤っています。サーバーは実行を継続し、次のツール呼び出し時に接続を再試行します。

  • insert/update/delete での PERMISSION_DENIED: サーバーが readonly モードで実行されています。書き込みを行う場合は MYSQL_MODE=readwrite で再起動してください。

バージョン履歴

  • 0.1.0 — 初期リリース: select/insert/update/delete ツール、readonly/readwrite モードポリシー、stdio MCP トランスポート、接続切断時の自動再接続・再試行。

Available Tools

4 tools
deleteA

Execute a DELETE statement and return the affected row count. Only available when the server is running in 'readwrite' mode; rejected with PERMISSION_DENIED in 'readonly' mode. A DELETE with no WHERE clause is executed but flagged with a warning, since it removes every row in the table. Always use %s placeholders in query with values passed via params; never concatenate user-supplied values into query.

ParametersJSON Schema
NameRequiredDescriptionDefault
queryYes
paramsNo

Output Schema

ParametersJSON Schema
NameRequiredDescription

No output parameters

TDQS

A4.8/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden. It discloses the readwrite/readonly mode behavior, the warning flag for DELETE without WHERE, and the security requirement to use placeholders. These are significant behavioral traits beyond what the schema shows.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is three sentences, each earning its place: core function, mode restriction, warning, and security guideline. No fluff or repetition.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a deletion tool with output schema present, the description covers the essential aspects: return value (row count), mode availability, dangerous no-WHERE behavior, and parameter usage. It is sufficiently complete for an agent to use correctly.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must explain both parameters. It does so by clarifying that `query` is a DELETE statement with %s placeholders and `params` provides values, plus warns against concatenation. This adds substantial meaning beyond the basic schema type definitions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Clearly states it executes a DELETE statement and returns the affected row count. This distinguishes it from sibling tools select, insert, and update by specifying the exact SQL operation.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Explains the tool is only available in 'readwrite' mode and rejected with PERMISSION_DENIED in 'readonly' mode, providing clear context for when it can be used. Does not explicitly compare to alternatives, but the purpose and mode restrictions give sufficient guidance.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

insertA

Execute an INSERT statement and return the affected row count and last insert id. Only available when the server is running in 'readwrite' mode; rejected with PERMISSION_DENIED in 'readonly' mode. Always use %s placeholders in query with values passed via params; never concatenate user-supplied values into query.

ParametersJSON Schema
NameRequiredDescriptionDefault
queryYes
paramsNo

Output Schema

ParametersJSON Schema
NameRequiredDescription

No output parameters

TDQS

A4.1/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

While no annotations are provided, the description discloses key behavioral traits: the mode-dependent availability (PERMISSION_DENIED in readonly mode) and the return values (affected row count and last insert id). It also provides security guidance on parameterization, which is essential for agent behavior.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is two sentences, front-loaded with the primary purpose, followed by mode restriction and security guidance. Every sentence earns its place; no filler or redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The tool has an output schema, which may explain return values, so the agent knows what to expect. The description covers the key semantics: the operation and parameterization. It gives clear guidance on mode requirements and security, which is sufficient for a tool with only two simple parameters and an output schema.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema has 0% description coverage, so the description must compensate. It does explain the purpose of `query` (the INSERT statement) and `params` (values for placeholders), but it doesn't detail the exact types or format expectations beyond mentioning placeholders. The baseline is 3 because the description adds some meaning but not fully.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: to execute an INSERT statement and return the affected row count and last insert id. It distinguishes itself from siblings (select, update, delete) by naming the specific SQL operation, though it could explicitly contrast with siblings.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit usage context: only available in 'readwrite' mode, and it warns against concatenating user-supplied values, instructing to use placeholders. It does not explicitly mention when not to use it (e.g., for other SQL operations), but the sibling names make that clear.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

selectA

Execute a read-only SELECT (or WITH ... SELECT) statement and return matching rows. Always available regardless of MYSQL_MODE. Always use %s placeholders in query with values passed via params; never concatenate user-supplied values into query.

ParametersJSON Schema
NameRequiredDescriptionDefault
queryYes
paramsNo

Output Schema

ParametersJSON Schema
NameRequiredDescription

No output parameters

TDQS

A4.5/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden. It discloses the read-only safety profile, availability, and the critical placeholder requirement. It does not mention error behavior, transaction details, or return format, but the output schema covers return values. It adds meaningful context beyond what annotations would provide.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is three concise sentences, each adding value: purpose, availability, and security guideline. It is front-loaded with the core purpose and contains no redundant or filler content.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the simple tool (2 parameters, no nested objects, output schema present), the description covers purpose, read-only nature, availability, and placeholder usage. It is complete for a SELECT tool and the output schema handles return value documentation. No significant gaps remain.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate. It explains that `query` is a SQL statement with %s placeholders and that `params` holds the substitution values, clarifying the relationship between the two parameters. It does not enumerate all parameter types, but the schema is simple and the guidance is sufficient.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description explicitly states 'Execute a read-only SELECT (or WITH ... SELECT) statement and return matching rows,' which is a specific verb+resource+scope. It clearly distinguishes from the sibling tools insert, update, and delete by emphasizing the read-only nature.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear usage context: always available regardless of MYSQL_MODE, and the requirement to use %s placeholders with params rather than concatenating values. It implies this is for read queries while siblings are for writes, but does not explicitly name alternatives or exclusion scenarios.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

updateA

Execute an UPDATE statement and return the affected row count. Only available when the server is running in 'readwrite' mode; rejected with PERMISSION_DENIED in 'readonly' mode. An UPDATE with no WHERE clause is executed but flagged with a warning, since it affects every row in the table. Always use %s placeholders in query with values passed via params; never concatenate user-supplied values into query.

ParametersJSON Schema
NameRequiredDescriptionDefault
queryYes
paramsNo

Output Schema

ParametersJSON Schema
NameRequiredDescription

No output parameters

TDQS

A4.8/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

The description reveals several behavioral traits: returns affected row count, is rejected in readonly mode, warns when no WHERE clause (affects all rows), and enforces parameterized queries. These go beyond the schema and give a clear picture of the tool's behavior and side effects.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is compact yet information-dense, with each sentence serving a specific purpose: purpose, mode condition, warning, and security guideline. It is well-structured and front-loaded, with no redundant or filler content.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the operation, mode constraints, warning behavior, and security practice, the description covers all essential aspects for using the tool correctly. It specifies the return value (affected row count) and does not leave critical gaps; it is complete for the context of an UPDATE tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description clarifies the meaning and relationship of the parameters: query is an UPDATE SQL statement, params are values for placeholders, and %s placeholders must be used. This adds significant semantic detail beyond the bare schema, which only lists query and params as types.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool executes an UPDATE statement and returns the affected row count, which is distinct from the sibling tools (select, insert, delete). The verb 'execute' and resource 'UPDATE statement' are specific and unambiguous.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit conditions for usage—only in readwrite mode, with a warning for missing WHERE clause—and gives security guidance (use %s placeholders, never concatenate user-supplied values). However, it does not explicitly contrast with when to use insert or delete, so it stops short of complete alternative differentiation.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

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

  1. 4 tool updatesv0.1.0
    • First observeddelete
    • First observedinsert
    • First observedselect
    • First observedupdate

TDQS

A4.6/5.0

Scored across 4 tools

Disambiguation5/5

Each tool maps to a distinct SQL operation (SELECT, INSERT, UPDATE, DELETE) with no functional overlap. Misselection is impossible because the actions are mutually exclusive.

Naming Consistency5/5

All tool names are single lowercase verbs that directly match their SQL counterparts, forming a perfectly consistent and predictable pattern.

Tool Count5/5

Four tools precisely cover the core CRUD operations for a database server without redundancy or excessive granularity, matching the expected scope.

Completeness5/5

The tool surface provides full coverage of data manipulation (create, read, update, delete) with no obvious gaps. Additional schema or transaction management is outside the stated read/write mode scope.

Maintenance

ActivitySlowing
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • F
    license
    Not graded
    quality
    D
    maintenance
    A versatile MCP server that connects to multiple relational databases (MySQL, PostgreSQL, Oracle, SQL Server, SQLite) and enables secure read-only SQL query execution and metadata access.
    4
    -
  • A
    license
    Not graded
    quality
    B
    maintenance
    A MySQL MCP server for local stdio clients, enabling database queries and management with read-only/write modes, audit logging, and configurable security.
    1,075 npm
    MIT
  • F
    license
    Not graded
    quality
    D
    maintenance
    A generic MCP server for MySQL operations, enabling listing databases/tables, describing schemas, running read-only SQL, and optionally executing write SQL with logging.
    1
    -