这是一个FastMCP服务器,使大型语言模型(LLMs)能够连接并与PostgreSQL数据库进行交互。该项目演示了如何使用模型上下文协议(MCP)让语言模型查询和探索数据库模式及表。
该服务器公开以下MCP资源:
database://{schema} - 获取模式中所有表的信息database://{schema}/tables/{table} - 获取特定表的详细信息query_database - 执行针对数据库的SQL查询(仅限SELECT查询)服务器包含以下预定义提示:
prompt_schema_description - 请求描述数据库模式prompt_table_description - 请求描述特定表prompt_query_database - 请求从特定表获取数据克隆仓库:
git clone <repository-url>
cd mcp-demo
创建虚拟环境:
python -m venv .venv
source .venv/bin/activate # 在Windows上:.venv\Scripts\activate
安装UV(如果尚未安装):
pip install uv
使用UV安装依赖项:
uv sync
配置环境变量:
.env.example复制为.env应用程序通过环境变量进行配置:
| 变量名 | 描述 | 默认值 |
|---|---|---|
| APP_NAME | 应用程序名称 | mcp-demo |
| DB_HOST | PostgreSQL主机 | localhost |
| DB_PORT | PostgreSQL端口 | 5432 |
| DB_USER | PostgreSQL用户名 | postgres |
| DB_PASSWORD | PostgreSQL密码 | postgres |
| DB_NAME | PostgreSQL数据库名 | postgres |
首先,在src/main.py文件底部取消注释运行函数:
# if __name__ == "__main__":
# print("启动FastMCP服务器...")
# mcp.run()
启动FastMCP服务器:
python -m src.main
服务器将可供LLMs连接并查询您的PostgreSQL数据库。在服务器运行时,MCP可以加载到客户端应用中进行交互。
要在客户端应用中使用此MCP,请向客户端的MCP配置文件(例如,.cursor/mcp.json)添加以下配置:
{
"mcpServers": {
"postgres-mcp-server": {
"command": "/path/to/your/venv/bin/mcp",
"args": ["run", "/path/to/your/postgres-mcp/src/main.py"],
"env": {
"APP_NAME": "mcp-demo",
"DB_HOST": "localhost",
"DB_PORT": "5432",
"DB_USER": "postgres",
"DB_PASSWORD": "postgres",
"DB_NAME": "postgres"
}
}
}
}
确保替换实际路径到您的虚拟环境和项目目录,并根据您的PostgreSQL配置更新环境变量。
使用UV安装开发依赖项:
uv pip install -e ".[dev]"
包含的开发工具:
使用Docker运行应用程序:
构建Docker镜像:
docker build -t mcp-demo .
运行容器:
docker run --env-file .env.docker -p 8000:8000 mcp-demo
from mcp.client import get_client
client = get_client("http://localhost:8000")
schema_info = client.get_resource("database://public")
print(schema_info)
table_info = client.get_resource("database://public/tables/users")
print(table_info)
result = client.invoke_tool("query_database", {"query": "SELECT * FROM users LIMIT 10"})
print(result)
[在此处添加您的许可证信息]