Logotipo de PostgreSQL MCP 服务器

PostgreSQL MCP 服务器

Comunidad
leixiaotian1

一款用golang实现的操作pg数据库的mcp server,支持创建表、查询表、插入数据,查看数据,分析sql语句等功能,欢迎共建!!!

Editorleixiaotian1
Repositoriopgsql-mcp-server
IdiomaGo
Forks
2
Estrellas
12
Herramientas disponibles
0
Tipo de transportestdio
Categorías
LicenciaMIT
Enlaces
  • Conecta herramientas a flujos de trabajo con IA

    PostgreSQL MCP 服务器 ofrece funciones MCP que pueden usar los clientes y agentes de IA compatibles.

  • 0 herramientas disponibles

    Explora a continuación las acciones que se pueden invocar, con sus nombres y descripciones cuando el servidor los proporcione.

  • Configuración lista para copiar

    Usa los ejemplos de instalación para configurar este servidor en tu cliente MCP preferido.

  • Indicadores de interés en el código abierto

    12 estrellas y 2 forks en el repositorio enlazado.

PostgreSQL MCP Server

GoDoc Stars Forks

中文 | English

A Model Context Protocol (MCP) server that provides tools for interacting with a PostgreSQL database. It enables AI assistants to execute SQL queries, explain statements, create tables, and list database tables via the MCP protocol.

✨ Features

  • Interact with Databases via AI: Enables LLMs to perform database operations through a structured protocol.
  • Secure Toolset: Separates read and write operations into distinct, authorizable tools (read_query, write_query).
  • Schema Management: Allows for table creation (create_table) and listing (list_tables).
  • Query Analysis: Provides a tool to analyze query execution plans (explain_query).
  • Multiple Transport Modes: Supports stdio, Server-Sent Events (sse), and streamableHttp for flexible client integration.
  • Environment-Based Configuration: Easily configurable using a .env file.

🛠️ Available Tools

The server exposes the following tools for MCP clients to invoke:

Tool NameDescriptionParameters
read_queryExecutes a SELECT SQL query.query (string, required): The SELECT statement to execute.
write_queryExecutes an INSERT, UPDATE, or DELETE SQL query.query (string, required): The INSERT/UPDATE/DELETE statement to execute.
create_tableExecutes a CREATE TABLE SQL statement.schema (string, required): The CREATE TABLE statement.
list_tablesLists all user-created tables in the database.schema (string, optional): The schema name to filter tables by.
explain_queryReturns the execution plan for a given SQL query.query (string, required): The query to explain (must start with EXPLAIN).

🚀 Quick Start

Prerequisites

  • Go 1.23 or later
  • A PostgreSQL database server

Installation

  1. Clone the repository:

    bash
    git clone https://github.com/leixiaotian1/pgsql-mcp-server.git
    cd pgsql-mcp-server
  2. Install dependencies:

    bash
    go mod download
  3. Build the MCP server:

    bash
    go build -o pgsql-mcp-server

Configuration

The pg-mcp-server requires database connection details to be provided via environment variables. Create a .env file in the project root with the following variables:

DB_HOST=localhost      # PostgreSQL server host
DB_PORT=5432           # PostgreSQL server port
DB_NAME=postgres       # Database name
DB_USER=your_username  # Database user
DB_PASSWORD=your_pass  # Database password
DB_SSLMODE=disable     # SSL mode (disable, require, verify-ca, verify-full)
SERVER_MODE=stdio      # Server mode (stdio, sse, streamableHttp)

Usage

Running the Server

bash
./pgsql-mcp-server

MCP Configuration

To use this server with an MCP-enabled AI assistant, add the following to your MCP configuration:

json
{
  "mcpServers": {
    "pgsql-mcp-server": {
      "command": "/path/to/pgsql-mcp-server",
      "args": [],
      "env": {
        "DB_HOST": "localhost",
        "DB_PORT": "5432",
        "DB_NAME": "postgres",
        "DB_USER": "your_username",
        "DB_PASSWORD": "your_password",
        "DB_SSLMODE": "disable",
        "SERVER_MODE": "stdio"
      },
      "disabled": false,
      "autoApprove": []
    }
  }
}

DOCKER DEPLOYMENT

Prerequisites

  • Docker installed

Deployment Steps

  1. Clone the project

    bash
    git clone https://github.com/leixiaotian1/pgsql-mcp-server.git
    cd pgsql-mcp-server
  2. Configure .env file

    Create a .env file in the project root directory. This file stores database connection information. Ensure the DB_HOST value matches the database container name you'll start later.

    properties
    DB_HOST=postgres
    DB_PORT=5432
    DB_NAME=postgres
    DB_USER=user
    DB_PASSWORD=password
    DB_SSLMODE=disable
    SERVER_MODE=sse
  3. Create Docker network

    To enable communication between the application container and database container, create a shared Docker network. This command only needs to run once.

    bash
    docker network create sql-mcp-network
  4. Start PostgreSQL database container

    Use this command to start a PostgreSQL container and connect it to our network.

    Note:

    • --name postgres: Container name, must exactly match the DB_HOST in your .env file.
    • --network sql-mcp-network: Connect to the shared network.
    • -p 5432:5432: Maps host's 5432 port to container's 5432 port. This means you can connect from your computer (e.g., using DBeaver) via localhost:5432, while the app container will access 5432 port directly through the internal network.
    bash
    docker run -d \
      --name postgres \
      --network sql-mcp-network \
      -e POSTGRES_USER=user \
      -e POSTGRES_PASSWORD=password \
      -e POSTGRES_DB=postgres \
      -p 5432:5432 \
      postgres
  5. Build and run the application

    Now you can use commands from the Makefile to manage the application.

    • Build image and run container:

      bash
      make build
      make run

      This will automatically stop old containers, build a new image, and start a new container.

    • View application logs:

      bash
      make logs

      If you see Successfully connected to database, everything is working correctly.

    • Stop the application:

      bash
      make stop

🔌 Server Modes

You can select the transport protocol by setting the SERVER_MODE environment variable.

stdio

The server communicates over standard input and output. This is the default mode and is ideal for local testing or direct integration with command-line-based MCP clients.

sse

The server communicates using Server-Sent Events (SSE). When this mode is enabled, the server will start an HTTP service and listen for connections.

  • SSE Endpoint: http://localhost:8088/sse
  • Message Endpoint: http://localhost:8088/message

streamableHttp

The server uses the Streamable HTTP transport, a more modern and flexible HTTP-based transport for MCP.

  • Endpoint: http://localhost:8088/mcp

🤝 Contributing

Contributions are welcome! If you find any bugs, have feature requests, or suggestions for improvement, please feel free to submit a Pull Request or open an Issue.

  1. Fork the Project.
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature).
  3. Commit your Changes (git commit -m 'Add some AmazingFeature').
  4. Push to the Branch (git push origin feature/AmazingFeature).
  5. Open a Pull Request.

📄 License

This project is open source and is licensed under the MIT License.

Instalación

TypingMind
{
  "mcpServers": {
    "pgsql-mcp-server": {
      "command": "./sql-mcp-server",
      "args": [],
      "env": {
        "DB_HOST": "<DB_HOST>",
        "DB_PORT": "<DB_PORT>",
        "DB_NAME": "<DB_NAME>",
        "DB_USER": "<DB_USER>",
        "DB_PASSWORD": "<DB_PASSWORD>",
        "DB_SSLMODE": "<DB_SSLMODE>"
      }
    }
  }
}

Usa el MCP de PostgreSQL MCP 服务器 con varios modelos de IA

TypingMind conecta las herramientas MCP a nivel del espacio de trabajo, por lo que, una vez conectado PostgreSQL MCP 服务器, puedes usarlo con distintos modelos de IA en TypingMind sin tener que configurarlo por separado para cada modelo. Esta integración MCP se ejecuta localmente en tu dispositivo a través del conector MCP de TypingMind.

Guía de configuración para usar el conector local

Usa esta opción si el servidor MCP necesita acceder a archivos locales, aplicaciones o recursos privados de tu ordenador.

1

Abre los ajustes de MCP

En TypingMind, ve a Ajustes, luego a Ajustes avanzados y a Model Context Protocol, y elige Configurar conector.

  1. Abre TypingMind en tu navegador.
  2. Haz clic en el icono de Ajustes.
  3. Ve a Ajustes avanzados.
  4. Abre la sección Model Context Protocol.
  5. Haz clic en Configurar conector y elige Este dispositivo.
Pantalla de configuración del conector MCP de TypingMind con «Este dispositivo» seleccionado
2

Ejecuta el comando del conector

Elige Este dispositivo, copia el comando de TypingMind y ejecútalo en Terminal. Mantén el proceso en ejecución mientras uses MCP.

  1. Copia el comando de configuración que muestra TypingMind.
  2. Abre Terminal en macOS o Windows Terminal en Windows.
  3. Pega y ejecuta el comando.
  4. Acepta la instalación del paquete si Terminal te pide confirmación para continuar.
  5. Mantén el proceso en ejecución en la ventana de Terminal mientras uses las herramientas MCP.
3

Añade PostgreSQL MCP 服务器 como servidor

Cuando el estado del conector sea «Listo», haz clic en «Edita servidores» y pega la configuración del servidor MCP.

  1. Espera hasta que el estado del conector indique «Listo».
  2. Haz clic en Edita servidores.
  3. Pega la configuración del servidor MCP de PostgreSQL MCP 服务器.
  4. Guarda la lista de servidores.
  5. Actualiza para comprobar que el conector sigue listo.
Ajustes de MCP de TypingMind con un servidor activo y el botón «Edita servidores»
{
  "mcpServers": {
    "pgsql-mcp-server": {
      "command": "npx",
      "args": [
        "-y",
        "<mcp-server-package>"
      ]
    }
  }
}
4

Úsala con distintos modelos

Guarda la lista de servidores, abre Plugins, activa las herramientas MCP de PostgreSQL MCP 服务器 y selecciona cualquier modelo de IA compatible en TypingMind para usar las herramientas en el chat o asignárselas a un agente de IA.

  1. Abre la página Plugins en TypingMind.
  2. Activa las herramientas MCP de PostgreSQL MCP 服务器.
  3. Inicia un chat y elige el modelo de IA que quieras usar.
  4. Usa las herramientas MCP en el chat o asígnalas a un agente de IA.
  5. Cambia a otro modelo de IA cuando lo necesites sin volver a conectar MCP.
Chat de TypingMind que usa herramientas MCP activadas con un modelo de IA seleccionado
¿Puedes usar PostgreSQL MCP 服务器 para ayudarme con esta tarea?
PostgreSQL MCP 服务器
Claro. Lo he leído.
Esto he encontrado usando PostgreSQL MCP 服务器.

Preguntas frecuentes

¿Para qué sirve el servidor MCP PostgreSQL MCP 服务器?

PostgreSQL MCP 服务器 es un servidor MCP que permite a los clientes de IA compatibles conectarse a herramientas y contexto externos. En TypingMind, basta con añadir este servidor MCP una vez para que sus herramientas estén disponibles en tu espacio de trabajo de IA.

¿Puedo usar el servidor MCP PostgreSQL MCP 服务器 con varios modelos de IA en TypingMind?

Sí. TypingMind conecta las herramientas MCP a nivel del espacio de trabajo, por lo que puedes usar PostgreSQL MCP 服务器 con distintos modelos de IA, como Claude, ChatGPT, Gemini u otros que hayas configurado en TypingMind, sin configurar el servidor MCP por separado para cada modelo.

¿Por qué usar el conector MCP de PostgreSQL MCP 服务器 con TypingMind?

TypingMind es una de las mejores interfaces de chat con LLM porque reúne varios modelos de IA, prompts, plugins, agentes de IA, claves de API y herramientas MCP en un solo espacio de trabajo. Con PostgreSQL MCP 服务器 conectado, puedes usar sus herramientas MCP con tus modelos preferidos y mantener organizado tu flujo de trabajo de chat en TypingMind.

¿Cómo conecto el servidor MCP PostgreSQL MCP 服务器 a TypingMind?

PostgreSQL MCP 服务器 funciona a través del conector MCP local de TypingMind. Es la mejor opción cuando el servidor MCP necesita acceder a archivos locales, aplicaciones de escritorio, herramientas de línea de comandos o recursos privados de tu ordenador.

¿Qué herramientas ofrece el servidor MCP PostgreSQL MCP 服务器 en TypingMind?

PostgreSQL MCP 服务器 ofrece funciones MCP que puedes activar desde la página Plugins de TypingMind y usar en el chat o asignar a agentes de IA.

¿Tengo que compartir mis claves de API con TypingMind para usar el servidor MCP PostgreSQL MCP 服务器?

No. TypingMind prioriza el funcionamiento local y te permite mantener el control de tus proveedores de modelos, claves de API, prompts y configuración MCP. Si PostgreSQL MCP 服务器 requiere autenticación, añade las cabeceras, los ajustes de OAuth o la configuración local necesarios para ese servidor MCP al crear la conexión.

Servidores MCP relacionados

Ver todos

Crea ya tu propio espacio de trabajo IA

Suscríbete a nuestro boletín para recibir avisos sobre nuevas funciones y próximos sorteos 👇