Skip to main content
Glama
CGAdmin544

多数据库 MCP Server

by CGAdmin544

多数据库 MCP Server

一个支持 Oracle / SQL Server / MySQL / PostgreSQL / SQLite 的 MCP(Model Context Protocol)服务器。底层用 SQLAlchemy 2.x 作为统一抽象层,把常用数据库操作封装为 MCP 工具,供 Claude Desktop、WorkBuddy 等 MCP 客户端调用。接口与原 Oracle 版完全兼容(execute_query / list_tables / describe_table / test_connection),原有仅配置 ORACLE_* 的旧环境无需改动即可继续工作。

功能

工具

说明

execute_query

执行 SELECT 查询(仅 SELECT/WITH),返回 JSON,最多 1000 行;支持 schemaName 指定默认命名空间

list_tables

列出指定 schema/数据库下的表名(不传则列出当前默认命名空间下的表)

describe_table

查看表结构(列名、类型、是否可空);支持 schemaName 限定所属 schema

test_connection

测试数据库连接是否正常

安全机制:

  • 只读模式(DB_MODE=readonly,默认)下禁止 INSERT/UPDATE/DELETE;

  • SQL 语法白名单校验(限定语句类型、禁止注释与多语句)+ 绑定变量传参,双重防注入;

  • 连接池复用(SQLAlchemy pool_pre_ping 探活)。

Related MCP server: mysql-mcp-zag

环境要求

  • Python 3.10+

  • 目标数据库可达,并安装对应驱动(见安装说明)

安装

# 1) 创建并激活虚拟环境(可选但推荐)
python -m venv .venv
.\.venv\Scripts\activate        # Windows
source .venv/bin/activate       # Linux / macOS

# 2) 以可编辑模式安装(会自动装好 mcp、sqlalchemy、各数据库驱动、python-dotenv)
pip install -e .

# 只装某个数据库驱动(可选):
pip install -e ".[mysql]"        # 仅 MySQL
pip install -e ".[mssql,postgres]"  # SQL Server + PostgreSQL

或手动安装依赖:

pip install "mcp<2" sqlalchemy oracledb pyodbc pymysql psycopg2-binary python-dotenv

注意:mcp 需锁定 <2(2.x 已将 FastMCP 重命名为 MCPServer,与本服务器代码不兼容)。

配置

连接信息从环境变量读取,支持两种方式(方式一优先级最高):

方式 A:完整 SQLAlchemy URL

DATABASE_URL=mysql+pymysql://user:pw@localhost:3306/mydb

方式 B:拆分字段

DB_TYPE=oracle            # oracle / sqlserver / mysql / postgres / sqlite
DB_USER=your_user
DB_PASSWORD=your_password
DB_HOST=localhost
DB_PORT=1521
DB_NAME=orcl_service_or_dbname
DB_MODE=readonly          # readonly(默认,禁 DML)/ readwrite

各 DB_TYPE 对应的 URL 模板(供参考):

DB_TYPE

URL 模板

oracle

oracle+oracledb://user:pw@host:port/?service_name=XXX

sqlserver

mssql+pyodbc://user:pw@host:1433/db?driver=ODBC+Driver+17+for+SQL+Server

mysql

mysql+pymysql://user:pw@host:3306/db

postgres

postgresql+psycopg2://user:pw@host:5432/db

sqlite

sqlite:///C:/path/to/app.db

Oracle 兼容(thick 模式,仅 11g 等老库需要):
thin 模式(默认)无需本地 Oracle 客户端,但仅支持 Oracle 12.1+。若目标库为 11g,必须启用 thick 模式:安装 Oracle Instant Client(如 11.2 / 19c,需 64 位),并设置 ORACLE_CLIENT_LIB_DIR。

ORACLE_CLIENT_LIB_DIR=E:\A_DevTool\instantclient_11_2

实测:Instant Client 11.2(64 位)+ python-oracledb 4.x 可正常连接 11g 库。旧环境只配 ORACLE_* 变量时,DB_TYPE 缺省会按 Oracle 处理,完全向后兼容。

使用

三种启动方式任选其一:

# 方式 1:pip install -e . 之后使用全局命令
oracle-mcp-server

# 方式 2:带预校验与启动横幅的启动脚本(推荐)
python run_server.py

# 方式 3:直接启动服务器主程序
python server.py

启动脚本 run_server.py 会在进入主循环前预校验必需环境变量(缺失时给出中文提示退出)并打印脱敏配置摘要;server.py 则直接进入 stdio 主循环。两者均可作为 MCP 客户端的启动命令。

接入 MCP 客户端

WorkBuddy

编辑 ~/.workbuddy/mcp.json(注意不是 .mcp.json),或参考本仓库的 mcp.json 示例:

{
  "mcpServers": {
    "oracle": {
      "command": "python",
      "args": ["F:/A_Study/oracle-mcp-server/run_server.py"],
      "env": {
        "DB_TYPE": "oracle",
        "ORACLE_HOST": "localhost",
        "ORACLE_PORT": "1521",
        "ORACLE_SERVICE_NAME": "XEPDB1",
        "ORACLE_USER": "your_user",
        "ORACLE_PASSWORD": "your_password",
        "ORACLE_MODE": "readonly"
      }
    }
  }
}

其它数据库示例(替换 env 即可):

{
  "mcpServers": {
    "mysql": {
      "command": "python",
      "args": ["F:/A_Study/oracle-mcp-server/run_server.py"],
      "env": {
        "DB_TYPE": "mysql",
        "DB_HOST": "localhost",
        "DB_PORT": "3306",
        "DB_NAME": "mydb",
        "DB_USER": "your_user",
        "DB_PASSWORD": "your_password",
        "DB_MODE": "readonly"
      }
    }
  }
}

要点:

  • command 建议写 Python 解释器的绝对路径(如虚拟环境 F:/A_Study/oracle-mcp-server/.venv/Scripts/python.exe),避免用到没有依赖的解释器;

  • env 中注入数据库连接信息后,可不依赖 .env 文件;

  • 配置完成后在 WorkBuddy 连接器管理页对该服务器点击"信任"以启用。

Claude Desktop

编辑 claude_desktop_config.json,写入同上结构即可。

安全提示

  • 只读场景保持 DB_MODE=readonly;确需写操作时再切 readwrite,并配合数据库侧最小权限账号。

  • .env 与 mcp.json 含数据库凭据,均已被 .gitignore 忽略,切勿提交到版本库。

  • 所有 SQL 均使用绑定变量传参 + 语法白名单校验,禁止在 SQL 中拼接用户输入。

项目结构

oracle-mcp-server/
├── .env.example       # 环境变量模板(多数据库)
├── .gitignore
├── mcp.json           # WorkBuddy MCP 配置示例(勿填真实密码提交)
├── pyproject.toml     # 项目配置、依赖与启动命令入口
├── run_server.py      # 启动脚本(预校验 + 横幅 + 进入主循环)
├── server.py          # MCP 服务器主程序(工具定义)
├── database.py        # 多数据库操作封装(SQLAlchemy + 查询/防护)
└── README.md          # 使用说明

Available Tools

4 tools
describe_tableA

查看表结构:列名、数据类型、是否可为空。

Args: table_name: 表名。 schemaName: 限定所属 schema(Oracle 为 owner,PostgreSQL 为 schema, MySQL/SQL Server 为数据库名);不传则匹配默认命名空间中的表。

ParametersJSON Schema
NameRequiredDescriptionDefault
schemaNameNo
table_nameYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4/5.0
Behavior2/5

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

With no annotations provided, the description carries the full burden for disclosing behavioral traits. It implies read-only behavior through the word 'view', but does not explicitly state that it is non-destructive, nor does it mention permissions, errors, or 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 concise and well-structured, starting with the main purpose followed by parameter explanations. No unnecessary fluff or redundancy is present.

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

Completeness4/5

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

The description covers the essential usage context, including the default namespace behavior. Since an output schema exists, it need not explain return values. It is sufficiently complete for a simple describe operation, though it omits potential error conditions or edge cases.

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?

The description adds meaningful details to the parameters, especially schemaName, explaining its interpretation across different database engines and the default behavior when omitted. table_name is only restated as 'table name', which adds minimal value, but overall the parameter documentation goes beyond the bare schema.

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's function: viewing table structure including column names, data types, and nullability. This distinctly differentiates it from siblings like list_tables, execute_query, and test_connection.

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 purpose makes the usage context clear (when you need to inspect a table's schema), and the schemaName parameter description provides additional context about default namespace behavior. However, it does not explicitly contrast with alternative tools or state when not to use it.

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

execute_queryA

执行只读 SQL 查询(仅允许 SELECT/WITH),结果以 JSON 数组返回。

Args: sql: SELECT 语句,绑定变量使用 :name 占位(不要字符串拼接值)。 schemaName: 指定默认 schema,未限定表名将解析到该 schema(如 "SCOTT")。

ParametersJSON Schema
NameRequiredDescriptionDefault
sqlYes
schemaNameNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.4/5.0
Behavior4/5

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

The description discloses key behaviors: it is read-only, only allows SELECT/WITH, returns a JSON array, and provides guidance on bind variables and schema resolution. This goes beyond minimal expectations, though it does not mention error handling or side effects, which are not critical for a read-only query tool.

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 concise and well-structured, using bullet-point style for arguments. It conveys all necessary information without unnecessary verbosity, making it easy to parse.

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 description covers the tool's purpose, input parameters, and output format (JSON array), which is sufficient for a read-only query tool. Since an output schema exists, the description does not need to detail the return structure further. It is complete for its scope.

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 explains both parameters in detail. For 'sql', it specifies that SELECT/WITH are allowed and that bind variables should use :name placeholders (avoiding string concatenation). For 'schemaName', it explains that it sets the default schema for unqualified table names, with an example. This fully compensates for the lack of schema-level descriptions.

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's purpose: executing read-only SQL queries (SELECT/WITH only) and returning results as a JSON array. This distinguishes it from sibling tools like list_tables and describe_table, which have different functions.

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

Usage Guidelines3/5

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

The description does not explicitly state when to use this tool versus its siblings. While the purpose is implicit, there is no direct guidance such as 'use this for querying data instead of describing schemas.' The description focuses on how to use it, not when to choose it among alternatives.

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

list_tablesA

列出数据库中的表;指定 schema 时仅列出该命名空间下的表。

Args: schema: 目标 schema/数据库名(不区分大小写);不传则列出当前默认命名空间下的表。

ParametersJSON Schema
NameRequiredDescriptionDefault
schemaNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.4/5.0
Behavior3/5

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

The description implies a read-only listing operation but does not explicitly state the absence of side effects, permissions needed, or error behavior. With no annotations provided, the description carries full burden, yet the operation is simple and self-evident.

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 concise and well-structured, with the purpose stated first followed by a brief parameter explanation. No unnecessary details are included.

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 tool's simplicity and the existence of an output schema, the description adequately covers the purpose and parameter behavior. It does not need to explain return values in detail.

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 Args section adds meaning beyond the raw schema: it explains that schema is a database/namespace name, is case-insensitive, and that omitting it uses the default namespace. This fully clarifies the parameter's semantics.

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 action ('List tables') and the resource ('tables in the database'), with a condition for filtering by namespace. It is distinct from sibling tools like execute_query, describe_table, and test_connection.

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?

It provides practical guidance by explaining the effect of specifying schema versus not specifying it, but it does not explicitly mention when to prefer this tool over alternatives or list exclusions.

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

test_connectionA

测试数据库连接是否正常,返回连接状态。

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.3/5.0
Behavior4/5

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

With no annotations, the description carries the full burden. It implies a read-only operation ('test') and explicitly mentions returning status, but does not explicitly state that it does not modify data or have other side effects. Nevertheless, the wording is sufficiently transparent for a simple connection test.

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 a single concise sentence that directly conveys the tool's purpose and output, with no unnecessary details.

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 simple test_connection tool with no parameters and a straightforward return of status, the description is complete. It fully explains what the tool does and what to expect.

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?

There are zero parameters, so schema coverage is trivially 100%. According to the rubric, a high coverage baseline of 3 applies, and no additional parameter description is needed.

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 verb 'test' and the resource 'database connection', along with the outcome of returning connection status. This distinguishes it from sibling tools like list_tables, execute_query, and describe_table.

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 context is clear: it is used to verify database connectivity, likely before other operations. However, it does not explicitly mention when to use it instead of alternatives, such as after a failure or before querying.

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.2.0
    • First observeddescribe_table
    • First observedexecute_query
    • First observedlist_tables
    • First observedtest_connection

TDQS

A4.4/5.0

Scored across 4 tools

Disambiguation5/5

Each tool has a clearly distinct purpose: listing tables, running read-only queries, describing table schemas, and testing connectivity. There is no meaningful overlap or ambiguity between them.

Naming Consistency5/5

All tool names follow the same verb_noun snake_case pattern: list_tables, execute_query, describe_table, test_connection. The naming is uniform and predictable.

Tool Count5/5

With 4 tools, the set is concise and well-scoped for a read-only database MCP server. Every tool serves a necessary core function without unnecessary bloat.

Completeness5/5

The tool set covers the essential read-only database workflow: discovery (list_tables), schema inspection (describe_table), querying (execute_query), and connection validation (test_connection). No obvious gaps exist for the stated purpose.

Maintenance

ActivityMaintained
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    C
    maintenance
    Enables read-only interaction with SQL databases through MCP, providing database metadata exploration, sample data retrieval, and secure query execution. Supports MySQL with multiple transport options and built-in security features including SQL injection protection and data sanitization.
    3 npm
    5
    MIT
  • A
    license
    Not graded
    quality
    D
    maintenance
    Read-only SQL Server MCP server enabling safe database queries, table listing, and schema inspection with built-in security protections.
    MIT
  • F
    license
    Not graded
    quality
    D
    maintenance
    Enables read-only SQL querying and schema inspection across MSSQL, PostgreSQL, and MySQL databases via MCP tools.
    -