MCP数据库工具服务器
📋 目录
______________________________________________________________________
🎯 概述
这个项目是 模型上下文协议(MCP)服务器 它自动化了Django数据库的设置和管理任务。它提供了以下工具:
- 创建PostgreSQL数据库
- 启用PostgreSQL扩展(hstore)
- 更新Django.env配置文件
- 执行Django管理命令
服务器与VS Code Copilot集成,可以通过以下方式访问:
- VS代码MCP集成
- 自动化工作流脚本
______________________________________________________________________
🏗️ 建筑
┌─────────────────────────────────────────────────────────────────┐
│ MCP Client Layer │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ VS Code │ │ Workflow │ │
│ │ Copilot │ │ Scripts │ │
│ └──────┬───────┘ └──────┬───────┘ │
└─────────┼──────────────────┼──────────────────┼──────────────────┘
│ │ │
└──────────────────┼──────────────────┘
│
┌────────▼────────┐
│ MCP Server │
│ (server.py) │
│ │
│ - list_tools() │
│ - call_tool() │
└────────┬────────┘
│
┌──────────────────┼──────────────────┐
│ │ │
┌─────▼─────┐ ┌─────▼─────┐ ┌─────▼─────┐
│PostgreSQL │ │ Django │ │ .env │
│ Database │ │ Backend │ │ File │
└───────────┘ └───────────┘ └───────────┘______________________________________________________________________
📁 项目结构
MCP_project/
│
├── server.py # Main MCP server implementation
├── mcp.json # MCP server metadata
├── requirements.txt # Python dependencies
│
* Web and CLI clients removed: The project no longer includes web_client.py or test_client.py files.
├── run_workflow.py # Automated workflow executor
│
├── tools/ # Utility modules (legacy/reference)
│ ├── __init__.py
│ ├── db_tools.py # PostgreSQL database operations
│ ├── env_tools.py # Environment file management
│ └── django_tools.py # Django command execution
│
├── templates/ # Web UI templates
│ └── index.html # Main web interface
│
└── venv/ # Python virtual environment______________________________________________________________________
🔄 组件流程
1. 核心服务器(Server.py)
系统的核心,实现MCP协议:
┌─────────────────────────────────────────────────────────┐
│ server.py │
├─────────────────────────────────────────────────────────┤
│ │
│ Configuration: │
│ ├─ PG_USER, PG_PASSWORD, PG_HOST │
│ ├─ DB_NAME (default: sample_project_db) │
│ ├─ ENV_PATH (Django .env location) │
│ ├─ MANAGE_PY (Django manage.py location) │
│ └─ PYTHON_EXEC (Virtual environment Python) │
│ │
│ MCP Server Decorators: │
│ ├─ @server.list_tools() → Returns available tools │
│ └─ @server.call_tool() → Executes tool operations │
│ │
│ Tools Implemented: │
│ ├─ create_database(db_name) │
│ ├─ enable_hstore(db_name) │
│ ├─ update_env(db_name) │
│ └─ django(cmd) │
└─────────────────────────────────────────────────────────┘主要特点:
- 异步/等待架构 符合MCP协议
- stdio通信 (非HTTP)用于MCP客户端集成
- 自动小写转换 PostgreSQL数据库名称
- 环境变量加载 Django命令的.env文件
- 虚拟环境Python 执行以确保依赖关系
______________________________________________________________________
2. 工具:create_database
Input: { db_name: "mydb" }
│
├─ Converts db_name to lowercase ("mydb")
│
├─ Connects to PostgreSQL server (postgres database)
│ └─ Uses: PG_USER, PG_PASSWORD, PG_HOST
│
├─ Executes: CREATE DATABASE mydb;
│
└─ Returns: "Database mydb created."PostgreSQL连接:
psycopg2.connect(
dbname="postgres",
user=PG_USER,
password=PG_PASSWORD,
host=PG_HOST
)______________________________________________________________________
3. 工具:enable_hstore
Input: { db_name: "mydb" }
│
├─ Converts db_name to lowercase
│
├─ Connects to the specified database
│
├─ Executes: CREATE EXTENSION IF NOT EXISTS hstore;
│
└─ Returns: "hstore extension enabled in mydb."目的: 启用PostgreSQL的hstore扩展用于键值对存储。
______________________________________________________________________
4. 工具:update_env
Input: { db_name: "mydb" }
│
├─ Converts db_name to lowercase
│
├─ Reads ENV_PATH file
│
├─ Finds line: POSTGRES_DB_NAME=old_value
│ └─ Skips commented lines (#)
│
├─ Replaces with: POSTGRES_DB_NAME=mydb
│
└─ Returns: ".env updated: POSTGRES_DB_NAME=mydb"文件操作:
- 保留所有其他.env内容
- 仅更新未注释的POSTGRES_DB_NAME行
- 维护文件结构和格式
______________________________________________________________________
5. 工具:django
Input: { cmd: "migrate" }
│
├─ Loads environment from ENV_PATH using dotenv
│ └─ Merges with os.environ
│
├─ Executes: PYTHON_EXEC MANAGE_PY migrate
│ └─ In working directory: dirname(MANAGE_PY)
│ └─ With loaded environment variables
│
├─ Captures stdout and stderr
│
└─ Returns: Command output with exit code执行流程:
subprocess.run(
[PYTHON_EXEC, MANAGE_PY] + cmd.split(),
cwd=workdir,
env=env, # Loaded from .env
capture_output=True,
text=True
)为什么选择虚拟环境Python?
- 虚拟环境中安装的Django和依赖项
- 系统Python缺少必需的包
- 确保一致的执行环境
______________________________________________________________________
客户端接口
访问服务器主要是通过VS Code MCP集成和自动化工作流脚本。
C 工作流自动化(run_Workflow.py)
Complete Database Setup Workflow
┌─────────────────────────────────────────┐
│ Step 1: Create database │
│ Step 2: Enable hstore extension │
│ Step 3: Update .env file │
│ Step 4: Run create_text_search_config │
│ Step 5: Run migrations │
│ Step 6: Run update_fixtures │
└─────────────────────────────────────────┘用途:
python run_workflow.py mydb它的作用:
- 创建PostgreSQL数据库“mydb”
- 启用hstore扩展
- 使用POSTGRES_DB_NAME=mydb更新.env
- 按顺序运行Django设置命令
- 报告每个步骤的成功/失败
______________________________________________________________________
🛠️ 安装和设置
先决条件
- Python 3.12+
- PostgreSQL服务器正在运行
- Django项目(可选,用于Django命令)
步骤1:克隆/设置项目
cd /home/chaitanyaphani/MCP_project第二步:创建虚拟环境
python3 -m venv venv
source venv/bin/activate # Linux/Mac
# or
venv\Scripts\activate # Windows步骤3:安装依赖项
pip install -r requirements.txt依赖关系:
mcp-模型上下文协议SDKFlask-Web UI框架psycopg2-binary-PostgreSQL适配器python-dotenv-环境文件支持
步骤4:配置PostgreSQL
编辑 server.py:
PG_USER = "postgres"
PG_PASSWORD = "your_password" # Update this!
PG_HOST = "localhost"步骤5:配置Django路径
编辑 server.py:
ENV_PATH = "/path/to/your/django/.env"
MANAGE_PY = "/path/to/your/django/manage.py"
PYTHON_EXEC = "/path/to/your/django/venv/bin/python"步骤6:配置VS代码(可选)
编辑VS代码设置(settings.json):
{
"mcpServers": {
"dbtools": {
"command": "python",
"args": ["server.py"],
"cwd": "/home/chaitanyaphani/MCP_project"
}
}
}______________________________________________________________________
🚀 用法
方法1:自动化工作流程
python run_workflow.py database_name方法2:VS代码复制
配置后,只需询问: 配置后,只需询问:
"Create a database named myproject, enable hstore,
update the .env file, and run migrations"______________________________________________________________________
⚙️ 配置
环境变量
服务器使用这些配置常量:
| 变量 | 目的 | 默认值 |
|---|---|---|
PG_USER | PostgreSQL用户名 | postgres |
PG_PASSWORD | PostgreSQL密码 | root |
PG_HOST | PostgreSQL主机 | localhost |
PG_PORT | PostgreSQL端口 | 5432 |
DB_NAME | 默认数据库名称 | sample_project_db |
ENV_PATH | Django.env文件路径 | /path/to/.env |
MANAGE_PY | Django manage.py路径 | /path/to/manage.py |
PYTHON_EXEC | 虚拟环境Python | /path/to/venv/bin/python |
Django.env文件格式
预期格式:
POSTGRES_DB_HOST=localhost
POSTGRES_DB_PORT=5432
POSTGRES_DB_NAME=mydb
POSTGRES_DB_USER=postgres
POSTGRES_DB_PASSWORD=password______________________________________________________________________
🔍 故障排除
问题1:“AttributeError:'服务器'对象没有属性'define_tool'”
原因: 使用不正确的MCP装饰器语法。\ 解决方案: 使用 @server.list_tools() 和 @server.call_tool() 而不是 @server.define_tool.
问题2:“用户'postgres'的密码验证失败”
原因: PostgreSQL密码不正确。\ 解决方案: 更新 PG_PASSWORD 在 server.py 使用您的实际PostgreSQL密码。
问题3:“ModuleNotFoundError:没有名为'django'的模块”
原因: 使用系统Python而不是虚拟环境Python。\ 解决方案: 确保 PYTHON_EXEC 指向Django项目的虚拟环境Python。
问题4:“数据库'XX'不存在”(大写名称)
原因: PostgreSQL将未加引号的标识符转换为小写。\ 解决方案: 服务器现在自动将数据库名称转换为小写。
问题5:“.env已更新,但数据库名称未更改”
原因: 在.env文件中查找错误的变量名。\ 解决方案: 确保您的.env使用 POSTGRES_DB_NAME= (不是 POSTGRES_DB=).
问题6:“迁移后未创建表”
原因: 未加载环境变量,或Python可执行文件错误。\ 解决:
- 验证
PYTHON_EXEC指向正确的虚拟环境 - 检查
.env文件已加载并包含正确的数据库名称 - 手动运行migrate以查看详细错误
______________________________________________________________________
📊 数据流图
完整工作流示例
User Request: "Create database 'myapp'"
│
├─ VS Code Copilot/Web UI/CLI
│ └─ Sends MCP request to server.py
│
├─ server.py receives call_tool("create_database", {"db_name": "myapp"})
│ │
│ ├─ Step 1: create_database
│ │ ├─ Convert "myapp" → "myapp" (lowercase)
│ │ ├─ Connect to PostgreSQL
│ │ ├─ Execute: CREATE DATABASE myapp;
│ │ └─ Return: "Database myapp created."
│ │
│ ├─ Step 2: enable_hstore
│ │ ├─ Connect to "myapp" database
│ │ ├─ Execute: CREATE EXTENSION IF NOT EXISTS hstore;
│ │ └─ Return: "hstore extension enabled in myapp."
│ │
│ ├─ Step 3: update_env
│ │ ├─ Read /path/to/.env
│ │ ├─ Find: POSTGRES_DB_NAME=olddb
│ │ ├─ Replace with: POSTGRES_DB_NAME=myapp
│ │ ├─ Write back to file
│ │ └─ Return: ".env updated: POSTGRES_DB_NAME=myapp"
│ │
│ └─ Step 4: django("migrate")
│ ├─ Load .env into environment
│ ├─ Execute: /venv/bin/python manage.py migrate
│ │ └─ Django reads POSTGRES_DB_NAME=myapp from env
│ │ └─ Connects to "myapp" database
│ │ └─ Applies migrations
│ └─ Return: Migration output
│
└─ Result returned to user______________________________________________________________________
🎓 关键概念
模型上下文协议(MCP)
- 协议 让AI助手与工具进行交互
- 基于stdio 通信(非HTTP)
- 异步/等待 需要图案
- 工具注册 通过
list_tools() - 工具执行 通过
call_tool()
为什么是这种架构?
- 关注点分离:服务器逻辑与客户端接口分开
- 多个接口:相同的服务器,不同的访问方法
- 类型安全:带模式验证的MCP协议
- 错误处理:全面的错误报告
- 环境隔离:使用虚拟环境Python
PostgreSQL命名规则
- 转换为小写的无引号标识符
CREATE DATABASE MyDB创造mydb- 服务器自动处理此转换
______________________________________________________________________
📝 工具参考
create_database
{
"name": "create_database",
"arguments": {
"db_name": "string (optional, default: sample_project_db)"
},
"returns": "Database {db_name} created."
}enable_hstore
{
"name": "enable_hstore",
"arguments": {
"db_name": "string (optional, default: sample_project_db)"
},
"returns": "hstore extension enabled in {db_name}."
}update_env
{
"name": "update_env",
"arguments": {
"db_name": "string (optional, default: sample_project_db)"
},
"returns": ".env updated: POSTGRES_DB_NAME={db_name}"
}姜戈
{
"name": "django",
"arguments": {
"cmd": "string (required) - Django management command"
},
"returns": "Command output (stdout/stderr)"
}常见的Django命令:
migrate-应用数据库迁移makemigrations-创建新的迁移create_text_search_config-自定义命令update_fixtures-定制夹具管理runserver-启动开发服务器
______________________________________________________________________
🤝 贡献
要使用新工具扩展此服务器,请执行以下操作:
- 在中添加工具定义
list_tools():
Tool(
name="my_new_tool",
description="What it does",
inputSchema={
"type": "object",
"properties": {
"param1": {"type": "string", "description": "..."}
},
"required": ["param1"]
}
)- 在中添加工具实现
call_tool():
elif name == "my_new_tool":
param1 = arguments.get("param1")
# Your logic here
return [TextContent(type="text", text="Result")]______________________________________________________________________
📞 支持
对于问题或疑问:
- 检查故障排除部分
- 验证中的配置
server.py - 测试用
run_workflow.py用于调试/自动化 - 检查PostgreSQL日志中的数据库问题
- 检查Django日志中的Django命令问题
______________________________________________________________________
📄 许可证
该项目是Altiushub后端基础设施的一部分。
______________________________________________________________________
最后更新时间: 2025年12月12日\ 版本: 1.0.0\ MCP协议版本: 与MCP SDK最新版本兼容
