PostgreSQL多数据库MCP服务器

一个为AI代理设计的快速、类型安全且功能齐全的PostgreSQL多数据库模型上下文协议服务器,支持表结构查询和SQL操作。

  • by llm-graph
  • TypeScript
  • 本地部署
  • 更新于
在 GitHub 查看 llm-graph/postgres-mcp

使用说明

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

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

它是用Bun、TypeScript构建的, postgres,并利用 fastmcp 构建健壮的MCP服务器的框架。

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

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

故障排除和开发

使用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。
  • 🐘 多数据库支持: 连接并管理中定义的多个PostgreSQL实例之间的交互 .env.
  • 🛡️ 设计安全: 通过以下方式进行参数化查询 postgres 防止SQL注入。
  • 🔑 可选身份验证: 使用API密钥验证实现基于网络的安全连接(SSE/HTTP)(fastmcps authenticate 钩子)。
  • 📄 通过MCP资源的数据库模式:
    • 列表表格: 通过以下方式获取数据库中的表列表 db://{dbAlias}/schema/tables.
    • 检查表架构: 通过以下方式获取特定表的详细列信息 db://{dbAlias}/schema/{tableName}.
  • 💬 增强工具交互:
    • 在工具日志中: 工具将详细日志发送回客户端(log 上下文)。
    • 进度报告: 长期运行操作报告进度(reportProgress 上下文)。
  • 🧠 会话感知: 在工具执行上下文中访问会话信息(session 上下文)。
  • 📡 事件驱动: 用途 server.on 和 session.on 用于连接/会话事件处理。
  • 🔧 现代开发者体验(DX): 清晰的配置,直观的API,使用 fastmcp 工具。

包括什么(利用fastmcp功能)

  • FastMCP 服务器核心
  • server.addTool (为 query_tool, execute_tool, schema_tool,以及 transaction_tool)
  • server.addResourceTemplate (用于列出表和检查表模式)
  • server.start (与 stdio 专注,适应 sse/http)
  • 可选: authenticate 挂钩(用于API密钥验证)
  • 工具执行 context (log, reportProgress, session)
  • Zod用于参数模式验证
  • server.on (用于连接日志记录)
  • (可能) session.on 用于会话特定逻辑

📋 先决条件

  • 包子 (建议使用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 -以逗号分隔的唯一数据库别名列表
    • DEFAULT_DB_ALIAS -如果在工具调用中省略了“dbAlias”,则默认别名
    • 每个别名的数据库连接详细信息(例如。, DB_MAIN_HOST, DB_REPORTING_HOST)
    • 可选API密钥身份验证(ENABLE_AUTH, MCP_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客户端连接(光标、克劳德桌面)

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

光标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. 保存 和 重新启动游标 或“重新加载MCP服务器”。

  6. 验证 Cursor的MCP状态/日志中的连接。

克劳德桌面版

  1. 查找并编辑 config.json (路径见前面的README)。
  2. 在下面添加类似条目 mcpServers,使用 绝对路径 在 args.
  3. 重新启动克劳德桌面。

🛠️ MCP能力暴露

身份验证(可选)

  • 通过以下方式保护网络传输(HTTP/SSE) X-API-Key 标题匹配 MCP_API_KEY 如果 ENABLE_AUTH=true.
  • stdio 连接(Cursor/Claude的默认设置)通常会绕过此检查。

资源

1.列出数据库表

  • URI模板: db://{dbAlias}/schema/tables
  • 说明: 检索指定数据库别名中的用户表名列表(通常来自“公共”架构)。
  • 资源定义(addResourceTemplate):
    • uriTemplate: "db://{dbAlias}/schema/tables"
    • arguments:
      • dbAlias:(string,必填)-数据库的别名(来自 .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:(string,必填)-表的名称。
    • 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 对象(log, reportProgress, session).


1. query_tool

执行只读SQL查询。

  • 说明: 安全执行只读SQL,获取结果,并记录执行日志/进度。
  • 参数: statement (字符串), params (数组,可选), dbAlias (字符串,可选)。
  • 上下文用法: 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 (数组,可选), dbAlias (字符串,可选)。
  • 上下文用法: 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 ({语句,参数}的数组), dbAlias (字符串,可选)。
  • 上下文用法: log.info/debug/error, reportProgress,访问 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 安全性依赖于执行环境。
  • 数据敏感性: 注意可通过连接/工具访问的数据。
  • 资源查询: 用于列出表的查询(information_schema.tables)和模式(information_schema.columns)通常是安全的,但依赖于数据库权限。确保配置的用户具有适当的读取权限。如果需要安全性或清晰度,请自定义表列表查询(例如模式筛选)。

📜 许可证

该项目根据 MIT许可证。请参阅 许可证 文件以获取详细信息。

📋 更新日志

1.0.0

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