MCP数据库查询服务

MCP数据库查询服务

一个基于Model Context Protocol的SQLite数据库查询服务,为AI应用提供标准化的数据库访问、安全的SQL查询执行以及表结构预览功能。

Category
Visit Server

README

MCP数据库查询服务

一个基于Model Context Protocol (MCP)的SQLite数据库查询服务,为AI应用提供标准化的数据库访问能力。

🚀 功能特性

核心功能

  • 数据库连接管理: 安全的SQLite数据库连接和查询
  • SQL查询执行: 支持SELECT查询,内置安全防护
  • 表结构查询: 获取数据库表的详细结构信息
  • 样本数据获取: 快速预览表中的示例数据
  • 架构导出: 完整的数据库架构信息

MCP协议支持

  • 工具(Tools): 提供5个核心数据库操作工具
  • 资源(Resources): 支持数据库元数据资源访问
  • 提示(Prompts): 内置SQL查询和分析提示模板
  • 安全机制: SQL注入防护、查询限制、访问控制

技术架构

  • 通信协议: JSON-RPC over stdio
  • 数据库: SQLite 3.x
  • 编程语言: Python 3.8+
  • 依赖管理: pip/requirements.txt

📦 安装指南

1. 环境要求

  • Python 3.8 或更高版本
  • pip 包管理器

2. 克隆项目

git clone <repository-url>
cd mcp_learn

3. 安装依赖

pip install -r requirements.txt

4. 创建示例数据库

python create_sample_database.py

🎯 快速开始

方式一:使用启动脚本

python start_server.py

方式二:直接启动服务器

python mcp_database_server.py

📋 项目结构

mcp_learn/
├── README.md                    # 项目说明文档
├── requirements.txt             # Python依赖列表
├── config.py                    # 服务器配置文件
├── database_manager.py          # 数据库管理模块
├── mcp_database_server.py       # MCP服务器主程序
├── create_sample_database.py    # 示例数据库创建脚本
├── start_server.py             # 服务器启动脚本
└── sample_data.db              # 示例SQLite数据库(运行后生成)

🛠️ 可用工具

1. query_database

执行SQL查询操作

{
  "name": "query_database",
  "arguments": {
    "query": "SELECT * FROM users WHERE age > 25 LIMIT 10"
  }
}

2. get_table_info

获取表结构信息

{
  "name": "get_table_info",
  "arguments": {
    "table_name": "users"
  }
}

3. list_tables

列出所有数据库表

{
  "name": "list_tables",
  "arguments": {}
}

4. get_table_sample

获取表样本数据

{
  "name": "get_table_sample",
  "arguments": {
    "table_name": "products",
    "limit": 5
  }
}

5. get_database_schema

获取完整数据库架构

{
  "name": "get_database_schema",
  "arguments": {}
}

📚 可用资源

1. 数据库表列表

  • URI: database://tables
  • 描述: 获取所有数据库表的列表

2. 数据库架构

  • URI: database://schema
  • 描述: 获取完整的数据库架构信息

3. 特定表信息

  • URI: database://table/{table_name}
  • 描述: 获取指定表的详细信息

💡 提示模板

1. SQL查询助手

  • 名称: sql_query_helper
  • 用途: 帮助构建和优化SQL查询

2. 数据分析助手

  • 名称: data_analysis_helper
  • 用途: 协助进行数据分析和洞察

3. 表结构分析

  • 名称: schema_analysis_helper
  • 用途: 分析数据库表结构和关系

🔧 配置说明

config.py 配置项

class DatabaseConfig:
    database_path: str = "sample_data.db"  # 数据库文件路径
    connection_timeout: int = 30           # 连接超时时间
    query_timeout: int = 60               # 查询超时时间
    max_query_results: int = 1000         # 最大查询结果数

class SecurityConfig:
    allowed_operations: List[str] = ["SELECT"]  # 允许的SQL操作
    forbidden_tables: List[str] = []           # 禁止访问的表
    enable_sql_injection_protection: bool = True  # SQL注入防护

class MCPConfig:
    server_name: str = "database-query-server"  # 服务器名称
    server_version: str = "1.0.0"              # 服务器版本

class LoggingConfig:
    log_file: str = "mcp_server.log"  # 日志文件路径
    log_rotation: str = "1 day"       # 日志轮转周期
    log_level: str = "INFO"           # 日志级别

🔒 安全特性

SQL注入防护

  • 参数化查询
  • SQL语句验证
  • 危险关键词过滤

访问控制

  • 操作类型限制(仅允许SELECT)
  • 表访问控制
  • 查询结果数量限制

错误处理

  • 详细的错误信息
  • 安全的错误响应
  • 日志记录

🔌 客户端集成

Claude Desktop

在Claude Desktop配置文件中添加:

{
  "mcpServers": {
    "database-query": {
      "command": "python",
      "args": ["/path/to/mcp_database_server.py"],
      "cwd": "/path/to/mcp_learn"
    }
  }
}

Cursor IDE

  1. 打开Cursor设置
  2. 添加MCP服务器配置
  3. 指定服务器路径和参数

其他MCP客户端

任何支持MCP协议的客户端都可以连接此服务器。

📊 示例数据库

示例数据库包含以下表:

users (用户表)

  • id, username, email, full_name, age, city, registration_date, is_active

products (产品表)

  • id, name, category, price, stock_quantity, description, created_date

orders (订单表)

  • id, user_id, order_date, total_amount, status, shipping_address

order_items (订单详情表)

  • id, order_id, product_id, quantity, unit_price

activity_logs (活动日志表)

  • id, user_id, action, description, ip_address, timestamp

🐛 故障排除

常见问题

  1. 依赖安装失败

    pip install --upgrade pip
    pip install -r requirements.txt
    
  2. 数据库文件不存在

    python create_sample_database.py
    
  3. 权限错误 确保对项目目录有读写权限

  4. 端口占用 MCP使用stdio通信,不涉及端口问题

调试模式

修改config.py中的日志级别:

log_level: str = "DEBUG"

🤝 贡献指南

  1. Fork 项目
  2. 创建功能分支
  3. 提交更改
  4. 推送到分支
  5. 创建Pull Request

📄 许可证

MIT License - 详见LICENSE文件

📞 支持

如有问题或建议,请:

  1. 查看文档和FAQ
  2. 提交Issue
  3. 联系维护者

注意: 这是一个示例项目,用于演示MCP协议的数据库查询功能。在生产环境中使用前,请确保进行充分的安全评估和测试。

Recommended Servers

playwright-mcp

playwright-mcp

A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.

Official
Featured
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.

Official
Featured
Local
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.

Official
Featured
Local
TypeScript
VeyraX MCP

VeyraX MCP

Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.

Official
Featured
Local
graphlit-mcp-server

graphlit-mcp-server

The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.

Official
Featured
TypeScript
Kagi MCP Server

Kagi MCP Server

An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.

Official
Featured
Python
E2B

E2B

Using MCP to run code via e2b.

Official
Featured
Neon Database

Neon Database

MCP server for interacting with Neon Management API and databases

Official
Featured
Exa Search

Exa Search

A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.

Official
Featured
Qdrant Server

Qdrant Server

This repository is an example of how to create a MCP server for Qdrant, a vector search engine.

Official
Featured