FastPostgresMCP

by llm-graph
Verified

hybrid server

The server is able to function both locally and remotely, depending on the configuration or use case.

Integrations

  • Built on Bun runtime for high performance server execution, leveraging Bun's speed and JavaScript/TypeScript capabilities.

  • Allows AI agents to interact with multiple PostgreSQL databases, including running read-only queries, executing data-modifying statements, performing transactions, listing tables, and inspecting database schemas.

  • Implements end-to-end type-safety throughout the server with TypeScript, ensuring robust and error-resistant database interactions.

FastPostgresMCP🐘⚡️(功能齐全的多数据库 MCP 服务器)

该项目实现了速度极快、类型安全且功能齐全的模型上下文协议 (MCP) 服务器,专为 AI 代理(如 Cursor、Claude Desktop)设计,可与多个 PostgreSQL 数据库交互,包括列出表和检查模式。

它使用 Bun、TypeScript、 postgres构建,并利用fastmcp框架的高级功能来构建强大的 MCP 服务器。

用途:用于 AI 代理的 MCP 服务器

不是一个需要导入到代码中的库。它是一个独立的服务器应用程序。您可以将其作为进程运行,MCP 客户端(例如 AI 代理)使用基于 JSON 的模型上下文协议 (v2.0) 与其通信,通常通过客户端应用程序(例如 Cursor)管理的stdio连接进行。

故障排除和开发

使用 CLI 进行测试

该软件包包含一个内置的 CLI 命令,用于直接测试 MCP 服务器:

# From the project repository: bun run cli # This will start an interactive MCP CLI session where you can: # - Call any of the PostgreSQL tools (query_tool, execute_tool, etc.) # - View server capabilities # - Test queries against your configured databases

使用内置 MCP 检查器进行测试

您还可以使用 MCP 检查器进行可视化测试和调试:

# From the project repository: bun run inspect

常见问题

如果在运行bunx postgres-mcp时看到此错误:

FastPostgresMCP started [warning] FastMCP could not infer client capabilities

随后是 ping 消息,这意味着:

  1. MCP 服务器启动成功
  2. 客户端连接成功
  3. 但客户端只发送 ping 请求,并没有正确协商功能

这通常表示您需要使用合适的 MCP 客户端。请尝试:

  • 使用bun run cli来测试 MCP CLI
  • 按照安装部分中的说明在 Cursor 或 Claude Desktop 中配置 MCP 服务器

如果您正在开发自定义 MCP 客户端,请确保它正确实现 MCP 协议(包括功能协商)。

✨ 核心功能

  • **🚀 极快:**基于 Bun 和fastmcp构建。
  • **🔒 类型安全:**具有 Zod 模式验证的端到端 TypeScript。
  • **🐘 多数据库支持:**连接并管理.env中定义的多个 PostgreSQL 实例之间的交互。
  • **🛡️ 安全设计:**通过postgres进行参数化查询可防止 SQL 注入。
  • **🔑 可选身份验证:**使用 API 密钥验证( fastmcpauthenticate挂钩)保护基于网络的连接(SSE / HTTP)。
  • 📄 通过 MCP 资源获取数据库架构:
    • **列出表:**通过db://{dbAlias}/schema/tables获取数据库中表的列表。
    • **检查表模式:**通过db://{dbAlias}/schema/{tableName}获取特定表的详细列信息。
  • 💬 增强工具交互:
    • **工具内日志记录:**工具将详细日志发送回客户端( log上下文)。
    • **进度报告:**长时间运行的操作报告进度( reportProgress上下文)。
  • **🧠 会话感知:**在工具执行上下文( session上下文)内访问会话信息。
  • **📡 事件驱动:**使用server.onsession.on进行连接/会话事件处理。
  • **🔧 现代开发者体验(DX):**清晰的配置、直观的 API、使用fastmcp工具轻松测试。

包含的内容(利用 fastmcp 功能)

  • FastMCP服务器核心
  • server.addTool (用于query_toolexecute_toolschema_tooltransaction_tool
  • server.addResourceTemplate (用于列出表和检查表模式)
  • server.start (以stdio为焦点,适用于sse / http )
  • 可选: authenticate Hook(用于 API 密钥验证)
  • 工具执行contextlogreportProgresssession
  • Zod 用于参数模式验证
  • server.on (用于连接日志记录)
  • (可能) session.on用于会话特定逻辑

📋 先决条件

  • **Bun (建议使用 v1.0 或更高版本):**已安装并位于 PATH 中。
  • **PostgreSQL 数据库:**访问凭据和连接。用户需要权限才能查询information_schema

⚙️ 安装

选项 1:NPM 包

# Install globally npm install -g postgres-mcp # Or install locally in your project npm install postgres-mcp

npm 包可在https://www.npmjs.com/package/postgres-mcp获取

选项 2:克隆存储库

  1. 克隆存储库:
    # Replace with your actual repository URL git clone https://github.com/llm-graph/postgres-mcp.git cd postgres-mcp
  2. 安装依赖项:
    bun install

🔑 配置(多数据库和可选身份验证)

通过环境变量进行配置,从适当的.env文件加载。

  1. 创建环境文件:
    • 对于生产环境: cp .env.example .env
    • 对于开发: cp .env.development.example .env.development
  2. **环境文件加载顺序:**服务器按照以下优先级顺序从文件加载环境变量:
    • .env.<NODE_ENV> (例如, .env.development.env.production.env.staging
    • .env.local (用于本地覆盖,不受版本控制)
    • .env (默认后备)这允许针对不同的环境进行不同的配置。
  3. 编辑环境文件以定义数据库连接和身份验证:
    • DB_ALIASES - 以逗号分隔的唯一 DB 别名列表
    • DEFAULT_DB_ALIAS - 如果在工具调用中省略了“dbAlias”,则为默认别名
    • 每个别名的数据库连接详细信息(例如DB_MAIN_HOSTDB_REPORTING_HOST
    • 可选 API 密钥认证( ENABLE_AUTHMCP_API_KEY
# Example .env file - Key Variables # REQUIRED: Comma-separated list of unique DB aliases DB_ALIASES=main,reporting # REQUIRED: Default alias if 'dbAlias' is omitted in tool calls DEFAULT_DB_ALIAS=main # OPTIONAL: Enable API Key auth (primarily for network transports) ENABLE_AUTH=false MCP_API_KEY=your_super_secret_api_key_here # CHANGE THIS # Define DB connection details for each alias (DB_MAIN_*, DB_REPORTING_*, etc.) DB_MAIN_HOST=localhost DB_MAIN_PORT=5432 DB_MAIN_NAME=app_prod_db DB_MAIN_USER=app_user DB_MAIN_PASSWORD=app_secret_password DB_MAIN_SSL=disable # Alternative: Use connection URLs # DB_MAIN_URL=postgres://user:password@localhost:5432/database?sslmode=require # --- Optional: Server Logging Level --- # LOG_LEVEL=info # debug, info, warn, error (defaults to info)

🚀 运行服务器(作为进程)

直接使用 Bun 运行此服务器。AI 客户端(例如 Cursor)通常会为您启动并管理此命令。

选项 1:使用全局安装的包

  • 手动运行: postgres-mcp

选项 2:在项目中使用该包

  • 从你的项目运行: npx postgres-mcp
  • 或者以编程方式导入:
    // server.js import { startServer } from 'postgres-mcp'; // Start the MCP server startServer();

选项 3:从克隆的存储库

  • 手动运行(用于测试): bun run src/index.ts
  • 手动开发模式: bun run --watch src/index.ts

使用fastmcp CLI 工具进行测试

  • 交互式终端: bunx fastmcp dev src/index.ts
  • Web UI 检查器: bunx fastmcp inspect src/index.ts

💻 使用编程 API(作为库)

除了作为独立的 MCP 服务器运行之外,postgres-mcp 还可以以编程方式用作 Node.js/TypeScript 应用程序中的库。

基本用法

import { createPostgresMcp } from 'postgres-mcp'; // Create the PostgresMcp instance const postgresMcp = createPostgresMcp(); // Start the server postgresMcp.start(); // Direct database operations const results = await postgresMcp.executeQuery( 'SELECT * FROM users WHERE role = $1', ['admin'], 'main' // optional database alias ); // When done, stop the server and close connections await postgresMcp.stop();

直接函数导入

对于更简单的用例,您可以直接导入特定的函数:

import { initConnections, closeConnections, executeQuery, executeCommand, executeTransaction, getTableSchema, getAllTableSchemas } from 'postgres-mcp'; // Configure database connections const dbConfigs = { main: { host: 'localhost', port: 5432, database: 'my_db', user: 'db_user', password: 'db_password' } }; // Initialize connections initConnections(dbConfigs); // Execute a query const results = await executeQuery( 'SELECT * FROM users WHERE role = $1', ['admin'], 'main' ); // Get schema for a single table const schema = await getTableSchema('users', 'main'); // Get schema for all tables in the database const allSchemas = await getAllTableSchemas('main'); // Close connections when done await closeConnections();

配置选项

const postgresMcp = createPostgresMcp({ // Custom database configurations (override .env) databaseConfigs: { main: { host: 'localhost', port: 5432, database: 'app_db', user: 'app_user', password: 'password', ssl: 'disable' } }, // Server configuration serverConfig: { name: 'Custom PostgresMCP', defaultDbAlias: 'main' }, // Transport options: 'stdio', 'sse', or 'http' transport: 'http', port: 3456 });

有关编程 API 的完整文档,请参阅docs/programmatic-api.md

🔌 与 AI 客户端连接(Cursor、Claude Desktop)

配置您的 AI 代理(MCP 客户端)以通过其命令/参数机制执行此服务器脚本。

光标 AI - 详细示例

  1. 打开光标设置/首选项(Cmd+,或 Ctrl+,)。
  2. 导航到“扩展”->“MCP”。
  3. 点击“添加 MCP 服务器”或编辑settings.json
  4. 添加以下 JSON 配置:
    // In Cursor's settings.json or MCP configuration UI { "mcpServers": { "postgres-mcp": { // Unique name for Cursor "description": "MCP Server for PostgreSQL DBs (Main, Reporting)", "command": "bunx", // Use 'bun' or provide absolute path: "/Users/your_username/.bun/bin/bun" "args": [ "postgres-mcp" // or // *** ABSOLUTE PATH to your server's entry point *** // "/Users/your_username/projects/postgres-mcp/src/index.ts" / ], "env": { // .env file in project dir is loaded automatically by Bun. // Add overrides or Cursor-specific vars here if needed. }, "enabled": true } } }
  5. 保存重新启动 Cursor或“重新加载 MCP 服务器”。
  6. 验证Cursor 的 MCP 状态/日志中的连接。

克劳德桌面

  1. 找到并编辑config.json (请参阅前面的 README 了解路径)。
  2. mcpServers下添加类似的条目,并使用args中的绝对路径
  3. 重新启动 Claude Desktop。

🛠️ MCP 功能公开

身份验证(可选)

  • 如果ENABLE_AUTH=true ,则通过与MCP_API_KEY匹配的X-API-Key标头保护网络传输(HTTP / SSE)。
  • stdio连接(Cursor/Claude 的默认连接)通常会绕过此检查。

资源

1.列出数据库表

  • URI 模板: db://{dbAlias}/schema/tables
  • **描述:**检索指定数据库别名(通常来自“公共”模式)内的用户表名称列表。
  • 资源定义( addResourceTemplate ):
    • uriTemplate"db://{dbAlias}/schema/tables"
    • arguments
      • dbAlias :(字符串,必需)- 数据库的别名(来自.env )。
    • load({ dbAlias }) :连接到数据库,查询information_schema.tables (在公共模式中筛选基表,可在实现中自定义),将结果格式化为 JSON 字符串数组["table1", "table2", ...] ,并返回{ text: "..." }

使用示例(AI 提示): “获取资源db://main/schema/tables以列出主数据库中的表。”

2. 检查表结构

  • URI 模板: db://{dbAlias}/schema/{tableName}
  • **描述:**提供特定表的详细架构信息(列、类型、可空性、默认值)。
  • 资源定义( addResourceTemplate ):
    • uriTemplate"db://{dbAlias}/schema/{tableName}"
    • arguments
      • dbAlias :(字符串,必需)- 数据库别名。
      • tableName :(字符串,必需) - 表的名称。
    • load({ dbAlias, tableName }) :连接,查询特定表的information_schema.columns ,格式化为列对象的 JSON 字符串数组,返回{ text: "..." }

使用示例(AI提示): “描述资源db://reporting/schema/daily_sales 。”

响应内容示例(JSON字符串):

"[{\"column_name\":\"session_id\",\"data_type\":\"uuid\",\"is_nullable\":\"NO\",\"column_default\":\"gen_random_uuid()\"},{\"column_name\":\"user_id\",\"data_type\":\"integer\",\"is_nullable\":\"NO\",\"column_default\":null},{\"column_name\":\"created_at\",\"data_type\":\"timestamp with time zone\",\"is_nullable\":\"YES\",\"column_default\":\"now()\"},{\"column_name\":\"expires_at\",\"data_type\":\"timestamp with time zone\",\"is_nullable\":\"YES\",\"column_default\":null}]"

工具

工具接收context对象( logreportProgresssession )。


1. query_tool

执行只读 SQL 查询。

  • **描述:**安全地执行只读 SQL,获取结果,并记录执行日志/进度。
  • 参数: statement (字符串)、 params (数组,opt)、 dbAlias (字符串,opt)。
  • 上下文用法: log.info/debug 、可选的reportProgress 、访问session
  • **返回:**行数组的 JSON 字符串。

示例请求:

{ "tool_name": "query_tool", "arguments": { "statement": "SELECT product_id, name, price FROM products WHERE category = $1 AND price < $2 ORDER BY name LIMIT 10", "params": ["electronics", 500], "dbAlias": "main" } }

响应内容示例(JSON字符串):

"[{\"product_id\":123,\"name\":\"Example Gadget\",\"price\":499.99},{\"product_id\":456,\"name\":\"Another Device\",\"price\":350.00}]"

2. execute_tool

执行数据修改 SQL 语句。

  • **描述:**安全地执行数据修改 SQL,并带有执行日志记录。
  • 参数: statement (字符串)、 params (数组,opt)、 dbAlias (字符串,opt)。
  • 上下文用法: log.info/debug ,访问session
  • **返回:**表示受影响的行的字符串。

示例请求:

{ "tool_name": "execute_tool", "arguments": { "statement": "UPDATE users SET last_login = NOW() WHERE user_id = $1", "params": [54321] // dbAlias omitted, uses DEFAULT_DB_ALIAS } }

示例响应内容(字符串):

"Rows affected: 1"

3. schema_tool

检索特定表的详细架构信息。

  • **描述:**获取数据库表的列定义和详细信息。
  • 参数: tableName (字符串), dbAlias (字符串,可选)。
  • 上下文用途: log.info ,访问session
  • **返回:**列信息对象的 JSON 字符串数组。

示例请求:

{ "tool_name": "schema_tool", "arguments": { "tableName": "user_sessions", "dbAlias": "main" } }

响应内容示例(JSON字符串):

"[{\"column_name\":\"session_id\",\"data_type\":\"uuid\",\"is_nullable\":\"NO\",\"column_default\":\"gen_random_uuid()\"},{\"column_name\":\"user_id\",\"data_type\":\"integer\",\"is_nullable\":\"NO\",\"column_default\":null},{\"column_name\":\"created_at\",\"data_type\":\"timestamp with time zone\",\"is_nullable\":\"YES\",\"column_default\":\"now()\"},{\"column_name\":\"expires_at\",\"data_type\":\"timestamp with time zone\",\"is_nullable\":\"YES\",\"column_default\":null}]"

4. transaction_tool

以原子方式执行多个 SQL 语句。

  • **描述:**在事务中执行 SQL 序列,并记录步骤/进度。
  • 参数: operations ({statement,params} 数组)、 dbAlias (字符串、opt)。
  • 上下文用法: log.info/debug/errorreportProgress``session
  • **返回:**总结成功/失败的 JSON 字符串: {"success": true, "results": [...]}{"success": false, "error": ..., "failedOperationIndex": ...}

示例请求:

{ "tool_name": "transaction_tool", "arguments": { "operations": [ { "statement": "INSERT INTO orders (customer_id, order_date, status) VALUES ($1, NOW(), 'pending') RETURNING order_id", "params": [101] }, { "statement": "INSERT INTO order_items (order_id, product_sku, quantity, price) VALUES ($1, $2, $3, $4)", "params": [9999, "GADGET-X", 2, 49.99] }, { "statement": "UPDATE inventory SET stock_count = stock_count - $1 WHERE product_sku = $2 AND stock_count >= $1", "params": [2, "GADGET-X"] } ], "dbAlias": "main" } }

成功响应内容示例(JSON字符串):

"{\"success\":true,\"results\":[{\"operation\":0,\"rowsAffected\":1},{\"operation\":1,\"rowsAffected\":1},{\"operation\":2,\"rowsAffected\":1}]}"

错误响应内容示例(JSON字符串):

"{\"success\":false,\"error\":\"Error executing operation 2: new row for relation \\\"inventory\\\" violates check constraint \\\"stock_count_non_negative\\\"\",\"failedOperationIndex\":2}"

服务器和会话事件

  • 使用server.on('connect'/'disconnect')记录客户端连接。
  • 如果需要,可以使用session.on(...)进行更精细的会话事件处理。

🔒 安全注意事项

  • **SQL注入:**通过参数化查询缓解。无需直接输入连接。
  • 数据库权限: **关键。**为每个DB_<ALIAS>_USER分配最低权限,包括对information_schema的读取权限,以获取架构/表列表资源。
  • SSL/TLS:生产必需DB_<ALIAS>_SSL=require或更严格)。
  • **机密管理:**保护.env文件(添加到.gitignore )。在生产环境中使用安全的机密管理(Vault、Doppler、云机密)。
  • 身份验证范围: authenticate钩子主要保护网络传输。stdio stdio性依赖于执行环境。
  • **数据敏感性:**注意通过连接/工具访问的数据。
  • **资源查询:**用于列出表 ( information_schema.tables ) 和模式 ( information_schema.columns ) 的查询通常是安全的,但依赖于数据库权限。请确保配置的用户拥有适当的读取权限。如果需要,出于安全性或清晰度的考虑,请自定义表列表查询(例如,模式筛选)。

📜 许可证

本项目遵循MIT 许可证。详情请参阅LICENSE文件。

📋 更新日志

1.0.0

  • 初始版本
  • 功能齐全的 PostgreSQL MCP 服务器
  • 支持多种数据库连接
  • 用于查询、执行、模式检查和事务的工具
  • 模式自省资源
  • 全面的文档和示例
ID: cu9jnv9gk1