数据库查询服务

MCP数据库服务器是一个允许AI代理(如Claude、Cursor等)安全查询和探索数据库的服务,支持PostgreSQL、MySQL和MongoDB,提供SQL注入检测、写入操作阻止和结果格式化等功能。

  • by rohitkapoorfriend
  • TypeScript
  • 本地部署
  • 更新于
在 GitHub 查看 rohitkapoorfriend/mcp-database-server

使用说明

mcp数据库服务器

一个MCP服务器,允许AI代理(Claude、Cursor等)安全地查询和探索数据库。使用TypeScript构建,支持PostgreSQL、MySQL和MongoDB。

为什么?

我想找到一种方法,让Claude和其他人工智能工具与我的数据库进行对话,而无需向它们提供原始访问权限。该服务器位于两者之间——它验证查询,默认情况下阻止写入,并格式化结果,以便人工智能能够真正理解它们。

建筑

AI Agent (Claude / Cursor / GPT)
          │
          │  JSON-RPC over stdio (MCP Protocol)
          ▼
┌─────────────────────────────────────┐
│         MCP DATABASE SERVER         │
│           TypeScript · Node.js      │
│                                     │
│  ┌──────────────┐  ┌─────────────┐  │
│  │ Safety Layer │  │  5 Tools    │  │
│  │              │  │             │  │
│  │ · SQL inject │  │ execute_    │  │
│  │   detection  │  │   query     │  │
│  │ · Write-op   │  │ get_schema  │  │
│  │   blocking   │  │ describe_   │  │
│  │ · Row limits │  │   table     │  │
│  │ · Timeouts   │  │ sample_data │  │
│  │ · Sanitizer  │  │ table_stats │  │
│  └──────────────┘  └─────────────┘  │
└──────────┬──────────────────────────┘
           │  DB Adapter (factory pattern)
    ┌──────┼──────┐
    ▼      ▼      ▼
  [PG]  [MySQL] [MongoDB]

每个查询在到达数据库适配器之前都会通过安全层。适配器模式意味着添加新数据库是一个具有标准接口的文件。

特性

  • PostgreSQL、MySQL、MongoDB支持
  • 默认情况下为只读(仅限SELECT,除非您翻转 ALLOW_WRITE)
  • SQL注入检测——阻止危险模式,验证输入
  • 5个MCP工具:查询、模式、描述、示例数据、表统计
  • 输出为markdown表、JSON或CSV
  • 架构作为MCP资源公开
  • 内置查询助手提示符
  • 行限制、查询超时、写保护
  • 使用示例电子商务数据进行Docker设置

快速开始

# Clone and install
git clone https://github.com/rohitkapoorfriend/mcp-database-server
cd mcp-database-server
npm install

# Configure your database
cp .env.example .env
# Edit .env with your database credentials

# Build and start
npm run build
node build/index.js

安装

npm install
npm run build

配置

所有配置都是通过环境变量进行的:

变量 默认值 描述
DB_TYPE postgresql 数据库类型: postgresql, mysql, mongodb
DB_HOST localhost 数据库主机
DB_PORT 5432 数据库端口
DB_NAME mydb 数据库名称
DB_USER postgres 数据库用户
DB_PASSWORD (空) 数据库密码
DB_SSL false 启用SSL连接
ALLOW_WRITE false 允许插入/更新/删除查询
MAX_ROWS 1000 每个查询结果的最大行数
QUERY_TIMEOUT 30000 查询超时(毫秒)
LOG_LEVEL info 日志级别: debug, info, warn, error

用法

克劳德桌面版

添加到您的 claude_desktop_config.json:

{
  "mcpServers": {
    "database": {
      "command": "node",
      "args": ["/absolute/path/to/mcp-database-server/build/index.js"],
      "env": {
        "DB_TYPE": "postgresql",
        "DB_HOST": "localhost",
        "DB_PORT": "5432",
        "DB_NAME": "mydb",
        "DB_USER": "postgres",
        "DB_PASSWORD": "your_password"
      }
    }
  }
}

Cursor IDE

添加到光标MCP设置中:

{
  "mcpServers": {
    "database": {
      "command": "node",
      "args": ["/absolute/path/to/mcp-database-server/build/index.js"],
      "env": {
        "DB_TYPE": "postgresql",
        "DB_HOST": "localhost",
        "DB_PORT": "5432",
        "DB_NAME": "mydb",
        "DB_USER": "postgres",
        "DB_PASSWORD": "your_password"
      }
    }
  }
}

克劳德代码CLI

DB_TYPE=postgresql DB_HOST=localhost DB_NAME=mydb DB_USER=postgres DB_PASSWORD=pass node build/index.js

工具

execute_query

对数据库执行SQL查询。

输入:

{ "query": "SELECT name, email FROM users LIMIT 5", "format": "table" }

输出:

name  | email
----- | -----------------
Alice | alice@example.com
Bob   | bob@example.com

_2 row(s) returned in 12ms._

get_schema

获取完整的数据库架构。

输入:

{ "schema": "public" }

输出: 带有所有表、列、类型、键、索引的Markdown。

describe_table

获取特定表格的详细信息。

输入:

{ "table_name": "users" }

输出: 列详细信息、约束、样本值、索引。

sample_data

从表中获取示例行。

输入:

{ "table_name": "orders", "limit": 5 }

输出: 带示例行的格式化markdown表。

table_stats

获取表的统计信息。

输入:

{ "table_name": "users" }

输出: 行数、表大小、列数、索引数。

Docker设置

# Start server with PostgreSQL and seed data
cd docker
docker-compose up -d

# The PostgreSQL database will be seeded with an ecommerce sample:
# - users (20 rows)
# - products (22 rows)
# - orders (20 rows)
# - order_items (30 rows)

测试

# Run all tests
npm test

# Run tests in watch mode
npm run test:watch

# Test with MCP Inspector
npx @modelcontextprotocol/inspector node build/index.js

发展

# Run in dev mode (auto-recompile)
npm run dev

# Build
npm run build

# Lint
npm run lint

项目结构

src/
├── index.ts              # Entry point — MCP server setup
├── config.ts             # Environment config with zod validation
├── databases/
│   ├── base.ts           # DatabaseAdapter interface
│   ├── index.ts          # Adapter factory
│   ├── postgresql.ts     # PostgreSQL adapter
│   ├── mysql.ts          # MySQL adapter
│   └── mongodb.ts        # MongoDB adapter
├── tools/
│   ├── query.ts          # execute_query tool
│   ├── schema.ts         # get_schema tool
│   ├── describe.ts       # describe_table tool
│   ├── sample.ts         # sample_data tool
│   └── stats.ts          # table_stats tool
├── resources/
│   └── schema-resource.ts # database://schema resource
├── prompts/
│   └── query-helper.ts   # query_helper prompt
├── safety/
│   ├── query-validator.ts # SQL safety validation
│   └── sanitizer.ts      # Input/output sanitization
└── utils/
    ├── formatter.ts      # Result formatting (table/json/csv)
    └── logger.ts         # Structured stderr logging

路线图

  • []SSE传输支持(HTTP模式)
  • []SQLite适配器
  • []Redis适配器
  • []连接池度量工具
  • []每位客户的费率限制

贡献

  1. 分叉存储库
  2. 创建要素分支: git checkout -b feature/my-feature
  3. 进行更改并添加测试
  4. 确保所有测试通过: npm test
  5. 确保构建成功: npm run build
  6. 提交拉取请求

许可证

麻省理工学院