Featured

Deploy OpenClaw in 60 seconds — 20% off logoDeploy OpenClaw in 60 seconds — 20% off

Launch OpenClaw on Hostinger in about 60 seconds and keep your agent live 24/7. Our referral link gives you 20% off, no coupon code needed.

Launch on Hostinger
Run your Hermes agent on Hostinger, fully managed logoRun your Hermes agent on Hostinger, fully managed

Launch Hermes on Hostinger in one click, fully managed, no VPS knowledge needed. Use code ZACAARON10 for 10% off.

Launch on Hostinger
Crawl and scrape any site into clean data, 10% off logoCrawl and scrape any site into clean data, 10% off

Firecrawl crawls and scrapes any site into clean markdown for your agent. Get 1,000 free credits, and new users get 10% off their first purchase.

Try Firecrawl free
Your own AI agent, running 24/7 with QwikClaw logoYour own AI agent, running 24/7 with QwikClaw

QwikClaw sets up and runs an always-on OpenClaw agent for you. One click, no config files, no server setup.

Deploy now
One API to scrape, enrich, and extract the internet. logoOne API to scrape, enrich, and extract the internet.

Context.dev gives your agents a single API to scrape, enrich, and extract live web data — no proxies, no parsers, no maintenance.

Start building free
SetupClaw: done-for-you OpenClaw for founders & exec teams logoSetupClaw: done-for-you OpenClaw for founders & exec teams

White-glove OpenClaw for founders and exec teams (4–50+ employees): we install, harden, integrate your tools, and maintain it — secured from day one.

Get it set up for you
SEO data APIs for your agent, $1 free credit logoSEO data APIs for your agent, $1 free credit

DataForSEO gives your agent live access to SERP results, keyword data, backlinks, and on-page SEO data through one API. New accounts get a $1 credit, good for up to 20,000 keyword or backlink lookups.

Try DataForSEO free
Reach 47,000+ AI builders

A flat monthly placement in front of developers actively installing AI tools. No lock-in, cancel anytime.

Advertise here

Works with

Claude CodeClaude DesktopCursorVS CodeClineCodex CLIOpenClaw+ any MCP client

Install to Claude Code

This server doesn't publish a one-line install command. Follow the setup in the source repository.

Summary

A Model Context Protocol server for unified database access and management, supporting multiple databases with CRUD operations, transactions, metadata queries, and built-in security features.

README.md

Database MCP Server

一个基于 Model Context Protocol (MCP) 的数据库连接服务器,支持多种数据库的统一访问和管理。

功能特性

支持的数据库

  • MySQL - 完整支持
  • PostgreSQL - 完整支持
  • Vastbase G100 - 完整支持(基于 PostgreSQL 适配)
  • ClickHouse - 完整支持(支持无密码连接)
  • Oracle - 基础支持(需要 OCI 库)
  • SQL Server - 基础支持(使用 tedious 驱动)

核心功能

  • 连接管理 - 连接池、心跳检测、自动回收
  • CRUD 操作 - select、insert、update、delete、count
  • 元数据查询 - list_tables、describe_table、get_table_indexes、list_databases
  • SQL 执行 - 参数化查询、执行计划分析
  • 事务管理 - begin_transaction、commit、rollback(支持隔离级别)
  • 高级查询 - GROUP BY、HAVING、ORDER BY

安全特性

  • SQL 注入防护 - SQL 解析校验、危险操作拦截
  • 数据脱敏 - 敏感字段自动脱敏(手机号、身份证、邮箱等)
  • 限流保护 - 令牌桶限流、并发查询限制
  • 熔断机制 - 自动熔断、故障恢复
  • 查询超时 - 超时控制、慢查询检测
  • 大表保护 - WHERE 条件强制、执行计划分析

日志审计

  • 审计日志 - 完整记录所有工具调用
  • 查询日志 - 记录 SQL 执行详情
  • 错误日志 - 详细的错误追踪
  • 日志轮转 - 自动轮转、保留期管理

---

快速开始

安装

# 克隆项目
git clone <repository-url>
cd database-mcp-server

# 安装依赖
npm install

# 构建
npm run build

配置

复制环境变量配置文件:

cp .env.example .env

编辑 .env 文件配置必要参数:

# 连接管理配置
CONNECTION_MAX_CONNECTIONS_PER_CLIENT=3
CONNECTION_IDLE_TIMEOUT=600000
CONNECTION_MAX_LIFETIME=1800000

# 查询配置
QUERY_TIMEOUT=30000

# 日志配置
LOG_LEVEL=info
LOG_DIR=./logs

启动

# 开发模式
npm run dev

# 生产模式
npm start

# 或直接运行构建后的文件
node dist/index.js

---

MCP 工具列表

连接管理

| 工具 | 描述 | |------|------| | connect | 连接到数据库 | | disconnect | 断开当前连接 | | get_connection | 获取连接状态 |

元数据查询

| 工具 | 描述 | |------|------| | list_databases | 列出所有数据库 | | list_tables | 列出所有表 | | describe_table | 查看表结构 | | get_table_indexes | 获取索引信息 |

CRUD 操作

| 工具 | 描述 | |------|------| | select | 查询数据(支持 GROUP BY/HAVING) | | insert | 插入数据 | | update | 更新数据 | | delete | 删除数据 | | count | 统计行数 |

SQL 执行

| 工具 | 描述 | |------|------| | execute_sql | 执行原始 SQL | | get_query_plan | 获取执行计划 |

事务管理

| 工具 | 描述 | |------|------| | begin_transaction | 开始事务 | | commit | 提交事务 | | rollback | 回滚事务 |

高级功能

| 工具 | 描述 | |------|------| | get_server_info | 获取服务器信息 | | truncate_table | 清空表(危险操作) | | get_security_status | 获取安全中间件状态 |

---

使用示例

1. 连接数据库

{
  "tool": "connect",
  "arguments": {
    "type": "mysql",
    "host": "localhost",
    "port": 3306,
    "database": "test_db",
    "username": "root",
    "password": "password"
  }
}

2. 查询数据

{
  "tool": "select",
  "arguments": {
    "table": "users",
    "columns": ["id", "name", "email"],
    "where": {
      "status": "active",
      "age": { "gte": 18 }
    },
    "orderBy": [{"column": "created_at", "direction": "desc"}],
    "limit": 10
  }
}

3. 分组聚合

{
  "tool": "select",
  "arguments": {
    "table": "orders",
    "columns": ["user_id", "count(*) as total", "sum(amount) as revenue"],
    "groupBy": ["user_id"],
    "having": { "count(*)": { "gt": 5 } }
  }
}

4. 执行事务

{
  "tool": "begin_transaction",
  "arguments": {
    "isolationLevel": "READ_COMMITTED"
  }
}

{
  "tool": "insert",
  "arguments": {
    "table": "accounts",
    "values": {"user_id": 1, "balance": 100}
  }
}

{
  "tool": "update",
  "arguments": {
    "table": "accounts",
    "values": {"balance": 50},
    "where": {"user_id": 2}
  }
}

{
  "tool": "commit"
}

5. 查看安全状态

{
  "tool": "get_security_status",
  "arguments": {}
}

---

配置说明

完整配置文件 (config/default.yaml)

connectionManager:
  maxConnectionsPerClient: 3
  idleTimeout: 600000      # 10 分钟
  maxLifetime: 1800000     # 30 分钟
  heartbeatInterval: 120000
  pool:
    min: 0
    max: 5
    acquireTimeout: 10000
    idleTimeout: 60000

query:
  maxRows: 1000
  maxResultSize: 10485760  # 10MB
  timeout: 30000
  requireWhereForLargeTables: true
  largeTableThreshold: 1000000
  maxJoins: 5
  maxSubqueryDepth: 3

rateLimit:
  requestsPerSecond: 10
  concurrentQueries: 5
  burstSize: 20

circuitBreaker:
  enabled: true
  errorThreshold: 50
  windowSize: 100
  timeout: 300000

security:
  sensitiveFields:
    hide: [password, passwd, secret, token, api_key, private_key]
    mask: [phone, id_card, credit_card, email]
  blockedSqlPatterns:
    - DROP\s+(TABLE|DATABASE)
    - TRUNCATE\s+
    - GRANT\s+
    - REVOKE\s+

audit:
  enabled: true
  filePath: ./logs/audit.log
  rotate: daily
  retention: 180
  logQueryParams: true
  logSql: true
  logResult: false
  logSlowQueries: true
  slowQueryThreshold: 1000

数据脱敏配置

敏感字段分为两类:

  1. hide - 完全隐藏,不出现在结果中
  • password, passwd, secret, token, api_key, private_key
  1. mask - 部分脱敏显示
  • phone: 138****1234
  • id_card: 110101********1234
  • credit_card: 6222 * * 1234
  • email: j***@example.com

限流熔断配置

| 参数 | 默认值 | 说明 | |------|--------|------| | requestsPerSecond | 10 | 每秒请求数限制 | | concurrentQueries | 5 | 并发查询数限制 | | burstSize | 20 | 突发流量大小 | | errorThreshold | 50 | 错误阈值(触发熔断) | | timeout | 300000 | 熔断超时(毫秒) |

---

开发

项目结构

database-mcp-server/
├── src/
│   ├── index.ts              # 入口文件
│   ├── server.ts             # MCP 服务器
│   ├── connection/           # 连接管理
│   │   ├── manager.ts
│   │   ├── pool.ts
│   │   └── string-builder.ts
│   ├── tools/                # MCP 工具实现
│   │   ├── connection.ts
│   │   ├── metadata.ts
│   │   ├── crud.ts
│   │   ├── sql.ts
│   │   └── transaction.ts
│   ├── middleware/           # 安全中间件
│   │   ├── data-masking.ts   # 数据脱敏
│   │   ├── rate-limiter.ts   # 限流熔断
│   │   └── security.ts       # 安全集成
│   ├── logger/               # 日志系统
│   │   ├── audit.ts
│   │   ├── query.ts
│   │   └── error.ts
│   └── types/                # 类型定义
│       ├── config.ts
│       └── database.ts
├── tests/
└── dist/

运行测试

# 运行所有测试
npm test

# 监听模式
npm run test:watch

# 生成覆盖率报告
npm run test:coverage

构建

# 编译 TypeScript
npm run build

# 清理并重新编译
npm run clean && npm run build

代码检查

# ESLint
npm run lint

# 格式化代码
npm run format

---

MCP 客户端配置

本服务器支持标准的 MCP 协议,可以在各种 AI 工具和客户端中使用。以下是详细的配置说明。

传输方式

Database MCP Server 使用 Stdio 传输方式(标准输入输出,用于本地进程通信)。

Claude Code 配置

Claude Code 是 Anthropic 官方的 CLI 工具,支持 MCP 协议。

配置位置

  • 全局配置: ~/.claude/settings.json
  • 项目配置: .claude/settings.local.json

配置示例

在项目目录中创建或编辑 .claude/settings.local.json

{
  "mcpServers": {
    "database-mcp": {
      "command": "node",
      "args": ["/absolute/path/to/database-mcp-server/dist/index.js"]
    }
  }
}

使用步骤

  1. 构建项目
   cd /path/to/database-mcp-server
   npm run build
  1. 配置 Claude Code
   # 在项目目录中
   mkdir -p .claude
   # 创建配置文件
  1. 启动 Claude Code
   claude
  1. 验证连接
   在对话中输入:/mcp
   查看已连接的 MCP 服务器

使用示例

用户:连接到 MySQL 数据库
Claude: 使用 database-mcp 的 connect 工具...

用户:查询 users 表中的所有数据
Claude: 使用 select 工具查询...

---

Cline (VS Code 扩展) 配置

Cline 是一个 VS Code 扩展,支持 MCP 协议。

配置位置

在 VS Code 中打开设置,搜索 "Cline",找到 MCP 配置项。

或者编辑 VS Code 设置文件:

  • Windows: %APPDATA%\Code\User\settings.json
  • macOS: ~/Library/Application Support/Code/User/settings.json
  • Linux: ~/.config/Code/User/settings.json

配置示例

{
  "cline.mcpServers": [
    {
      "name": "database-mcp",
      "type": "stdio",
      "command": "node",
      "args": ["C:/path/to/database-mcp-server/dist/index.js"]
    }
  ]
}

使用步骤

  1. 安装 Cline 扩展
  • 打开 VS Code
  • 搜索 "Cline" 并安装
  1. 配置 MCP 服务器
  • 打开 VS Code 设置
  • 搜索 "MCP"
  • 添加服务器配置
  1. 验证连接
  • 打开 Cline 面板
  • 查看 MCP 服务器状态

---

OpenCode 配置

OpenCode 是一个开源的 MCP 客户端。

配置位置

  • macOS/Linux: ~/.opencode/config.json
  • Windows: %USERPROFILE%\.opencode\config.json

配置示例

{
  "mcp": {
    "servers": {
      "database": {
        "command": "node",
        "args": ["/path/to/database-mcp-server/dist/index.js"]
      }
    }
  }
}

使用步骤

  1. 安装 OpenCode
   npm install -g @opencode/core
  1. 配置 MCP 服务器
   mkdir -p ~/.opencode
   # 创建 config.json 文件
  1. 启动 OpenCode
   opencode

---

Cursor 配置

Cursor 是支持 MCP 协议的 AI 代码编辑器。

配置位置

在 Cursor 中打开设置,搜索 "MCP"。

配置示例

在项目根目录创建 .cursor/mcp.json

{
  "servers": [
    {
      "name": "database-mcp",
      "type": "stdio",
      "command": "node",
      "args": ["${workspaceFolder}/../database-mcp-server/dist/index.js"]
    }
  ]
}

使用步骤

  1. 打开 Cursor 设置
  • File → Preferences → Settings
  1. 搜索 MCP
  • 找到 "MCP Servers" 配置项
  1. 添加服务器
  • 点击 "Add Server"
  • 填写配置信息
  1. 验证
  • 在 Cursor 中打开 AI 对话框
  • 输入 "@database 查询..." 测试

---

Windsurf 配置

Windsurf 是支持 MCP 的代码编辑器。

配置位置

  • 配置目录: ~/.windsurf/mcp-config.json

配置示例

{
  "mcpServers": {
    "database": {
      "command": "node",
      "args": ["/path/to/database-mcp-server/dist/index.js"]
    }
  }
}

---

常见问题排查

1. 服务器无法启动

检查路径: ```bash

确认构建文件存在

ls -la dist/index.js

重新构建

npm run build ```

检查权限: ```bash

Windows

以管理员身份运行 VS Code 或终端

macOS/Linux

chmod +x dist/index.js ```

2. 连接超时

  • 检查服务器日志
  • 确认端口未被占用
  • 检查防火墙设置

3. 工具不可见

  • 确认 MCP 服务器已正确连接
  • 在客户端中刷新 MCP 连接
  • 检查服务器日志输出

---

环境变量

| 变量名 | 默认值 | 说明 | |--------|--------|------| | CONNECTION_MAX_CONNECTIONS_PER_CLIENT | 3 | 每客户端最大连接数 | | CONNECTION_IDLE_TIMEOUT | 600000 | 空闲超时(毫秒) | | CONNECTION_MAX_LIFETIME | 1800000 | 最长存活时间(毫秒) | | QUERY_TIMEOUT | 30000 | 查询超时(毫秒) |

---

安全注意事项

  1. 数据库权限 - 使用最小权限原则创建专用数据库用户
  2. 敏感数据 - 根据实际需求配置敏感字段列表
  3. 日志安全 - 避免在生产环境日志中记录查询结果
  4. 网络隔离 - 建议将服务器部署在内网环境

---

故障排查

常见问题

1. 连接失败

  • 检查数据库服务是否运行
  • 验证连接参数(host、port、credentials)
  • 检查防火墙设置

2. 查询超时

  • 增加 QUERY_TIMEOUT 配置
  • 优化 SQL 查询性能
  • 检查数据库负载

3. 限流触发

  • 检查 get_security_status 查看限流状态
  • 调整 requestsPerSecond 配置

日志位置

  • 审计日志:./logs/audit.log
  • 错误日志:./logs/error.log
  • 查询日志:./logs/query.log

---

License

MIT

---

版本历史

| 版本 | 日期 | 变更 | |------|------|------| | 0.1.0 | 2026-03-05 | 初始版本,支持 MySQL/PostgreSQL/Vastbase/ClickHouse |

See related servers & alternatives →

Related MCP servers

Browse all →

Related guides

Hand-picked reading to help you choose and use Databases servers.