mysql-mcp-server
mysql-mcp-server
MCP 클라이언트(Claude Desktop, Claude Code 등)가 select, insert, update, delete 네 가지 도구를 통해 MySQL 데이터베이스에 SQL을 실행할 수 있게 해주는 Model Context Protocol (MCP) 서버입니다.
이 서버는 uv로 관리되는 Python 패키지로 실행되며, 클라이언트가 시작한 하위 프로세스로서 stdio를 통해 클라이언트와 통신합니다.
요구 사항
Python 3.11+
연결 가능한 MySQL 서버
Related MCP server: Universal Database MCP Server
설치
uv sync구성
서버는 여섯 가지 값을 필요로 하며, 각 값은 환경 변수 및/또는 CLI 플래그로 설정할 수 있습니다(CLI 플래그가 환경 변수보다 우선합니다):
매개변수 | 환경 변수 | CLI 플래그 | 필수 | 기본값 |
Mode |
|
| 예 | — ( |
Host |
|
| 예 | — |
Port |
|
| 아니요 |
|
User |
|
| 예 | — |
Password |
|
| 예 | — |
Database |
|
| 예 | — |
필수 값이 누락되었거나 MYSQL_MODE가 readonly/readwrite가 아니면 서버는 stderr에 오류를 출력하고 시작하지 않은 채 종료 코드 1로 종료됩니다.
readonly모드:select도구만 허용됩니다.insert/update/delete는PERMISSION_DENIED오류와 함께 거부됩니다.readwrite모드: 네 가지 도구가 모두 허용됩니다.
모드는 프로세스 수명 동안 고정되며 런타임에 변경할 수 없습니다.
보안 권장사항:
readonly모드는 애플리케이션 수준의 보호 장치일 뿐 데이터베이스 권한을 대체하지 않습니다. 가능하면readonly모드가SELECT권한만 있는 MySQL 계정을 가리키도록 하세요.
.env파일이 필요한가요? 아닙니다. 서버 자체는.env파일을 읽지 않습니다. CLI 플래그와 실제 프로세스 환경 변수(os.environ)만 읽습니다. 해당 환경에 값을 넣는 방법은 실행 방식에 따라 다릅니다:
MCP 서버로 실행하는 경우 (아래 MCP 클라이언트에서 연결하기 참조): 클라이언트(Claude Desktop/Code)가 서버 프로세스를 생성하고 자체 JSON 구성의
env블록을 환경 변수로 직접 주입합니다..env파일은 관여하지 않으며 필요하지 않습니다.로컬 개발/테스트를 위해 CLI를 직접 실행하는 경우:
.env는 여섯 개의 변수를 일일이export하지 않아도 되도록 해주는 편의 기능일 뿐입니다..env.example을.env로 복사하고 실제 값을 입력한 뒤 명시적으로 로드하세요. 자동으로 읽히지 않습니다:uv run --env-file .env mysql-mcp-server
.env는 git-ignored 처리되어 있으며 절대 커밋하면 안 됩니다.
실행
# 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 mydbMCP 클라이언트에서 연결하기
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에 따라 다름)를 모델이 사용할 수 있습니다.
도구
네 가지 도구 모두 {"query": string, "params"?: array} 형식을 받으며 query에서 항상 %s 매개변수 바인딩 플레이스홀더를 사용합니다. 사용자 입력을 쿼리에 문자열 포맷으로 넣지 마세요.
도구 | 허용 모드 | 쿼리 시작 키워드 | 성공 시 |
| 모든 모드 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
모든 도구 호출은 다음 중 하나를 반환합니다:
{ "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, ...)은 항상 거부됩니다. 위의 네 가지 허용된 문 유형만 수락되기 때문입니다.
개발
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 toolsdeleteA
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.
| Name | Required | Description | Default |
|---|---|---|---|
| query | Yes | ||
| params | No |
Output Schema
| Name | Required | Description |
|---|---|---|
No output parameters | ||
TDQS
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.
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.
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.
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.
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.
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.
| Name | Required | Description | Default |
|---|---|---|---|
| query | Yes | ||
| params | No |
Output Schema
| Name | Required | Description |
|---|---|---|
No output parameters | ||
TDQS
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.
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.
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.
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.
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.
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.
| Name | Required | Description | Default |
|---|---|---|---|
| query | Yes | ||
| params | No |
Output Schema
| Name | Required | Description |
|---|---|---|
No output parameters | ||
TDQS
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.
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.
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.
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.
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.
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.
| Name | Required | Description | Default |
|---|---|---|---|
| query | Yes | ||
| params | No |
Output Schema
| Name | Required | Description |
|---|---|---|
No output parameters | ||
TDQS
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.
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.
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.
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.
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.
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.
4 tool updates
v0.1.0- First observed
delete - First observed
insert - First observed
select - First observed
update
TDQS
Scored across 4 tools
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.
All tool names are single lowercase verbs that directly match their SQL counterparts, forming a perfectly consistent and predictable pattern.
Four tools precisely cover the core CRUD operations for a database server without redundancy or excessive granularity, matching the expected scope.
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
Related MCP Connectors
Read-only MCP server for ClassQuill, a tutoring-business-management platform.
Text-to-SQL MCP server: read-only queries on PostgreSQL, MySQL and SQL Server with your real schema
An MCP server that provides read access to your cloud storage providers, bank accounts and more.
Related MCP Servers
- AlicenseAqualityAmaintenanceAn MCP server that provides read-only access to MySQL databases.4684 npm72MIT
- FlicenseNot gradedqualityDmaintenanceA 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-
- AlicenseNot gradedqualityBmaintenanceA MySQL MCP server for local stdio clients, enabling database queries and management with read-only/write modes, audit logging, and configurable security.1,075 npmMIT
- FlicenseNot gradedqualityDmaintenanceA generic MCP server for MySQL operations, enabling listing databases/tables, describing schemas, running read-only SQL, and optionally executing write SQL with logging.1-