postgres-mcp

postgres-mcp

A Python MCP server that provides PostgreSQL database connectivity for Text-to-SQL workflows, enabling AI agents to explore schemas and execute parameterized SQL queries across multiple data marts.

Category
Visit Server

README

postgres-mcp

PostgreSQL과 Text-to-SQL에 필요한 데이터베이스 기능을 제공하는 작은 Python MCP 서버입니다. 여러 PostgreSQL 데이터 마트를 한 MCP 연결로 제공하며, 패키지와 가상환경은 uv로 관리합니다.

서비스 경계

이 서비스는 데이터베이스 어댑터 역할만 담당합니다.

AI / MCP client
       |
       | one MCP connection
       v
postgres-mcp
  ├─ defects -> PostgreSQL connection pool
  └─ voc     -> PostgreSQL connection pool

MCP를 호출하는 AI가 자연어 질문을 SQL로 변환합니다. 이 서버는 그 변환에 필요한 실제 스키마·컬럼·인덱스·외래키 컨텍스트와 제한된 SQL 실행 기능을 제공합니다. LLM SDK, 프롬프트 실행, ApeRAG collection 개념은 포함하지 않습니다.

한 SQL 문장은 한 data_source에서만 실행됩니다. 서로 다른 데이터베이스의 대규모 조인이 반복해서 필요하다면 MCP 내부 분산 조인보다 별도의 통합 분석 마트를 만드는 편이 적절합니다.

도구

외부 도구 계약은 두 개만 유지합니다.

도구 역할
search_objects 데이터소스와 스키마·테이블·뷰·컬럼·인덱스·함수·프로시저·외래키 탐색
execute_sql 선택한 데이터소스에서 파라미터화 PostgreSQL 단일 문장 실행

권장 Text-to-SQL 흐름:

  1. search_objects(object_type="data_source")로 DB 목록을 확인합니다.
  2. 관련 DB에서 table, view를 names 수준으로 찾습니다.
  3. 관련 테이블만 detail_level="full"로 조회합니다. 컬럼, 인덱스, 외래키 관계가 함께 반환됩니다.
  4. 확인된 이름만 사용해 SQL을 만들고 execute_sql로 실행합니다.

단일 DB 구성

Python 3.12 이상과 uv가 필요합니다.

uv sync
$env:DATABASE_URL = "postgresql://readonly:password@localhost:5432/app"
uv run postgres-mcp

기존 DATABASE_URL 방식은 그대로 지원하며 데이터소스 id는 default가 됩니다. .env 파일도 자동으로 읽습니다.

단일 DB의 여러 스키마

하나의 PostgreSQL 데이터베이스에서 여러 스키마를 함께 탐색하려면 POSTGRES_SCHEMA를 설정하지 마십시오. 먼저 schema를 검색하고, 이후 스키마를 명시해 테이블을 탐색하거나 스키마 한정 SQL을 실행합니다.

$env:DATABASE_URL = "postgresql://readonly:password@localhost:5432/appdb"
uv run postgres-mcp
SELECT COUNT(*) FROM voc_normalization_v02.raw_voc;
SELECT COUNT(*) FROM dataset_factory_v01.internal_dev_test_result;

여러 DB 구성

postgres-mcp.example.toml을 복사해 데이터소스를 등록합니다. DSN은 TOML에 직접 넣기보다 dsn_env로 환경 변수를 참조하십시오.

default_source = "defects"

[defaults]
read_only = true
max_rows = 200
pool_size = 2

[[sources]]
id = "defects"
description = "Product defect data mart"
dsn_env = "DEFECTS_DATABASE_URL"
default_schema = "quality"

[[sources]]
id = "voc"
description = "Voice-of-customer data mart"
dsn_env = "VOC_DATABASE_URL"
default_schema = "public"
$env:POSTGRES_MCP_CONFIG = "D:/secure/postgres-mcp.toml"
$env:DEFECTS_DATABASE_URL = "postgresql://db_mcp:...@host:5432/defects"
$env:VOC_DATABASE_URL = "postgresql://db_mcp:...@host:5432/voc"
uv run postgres-mcp

각 소스는 처음 사용될 때 독립적으로 연결됩니다. 한 DB의 연결 실패가 다른 DB의 서버 시작을 막지 않습니다. 연결 풀 크기는 각 소스에 적용되므로 전체 최대 연결 수는 대략 모든 pool_size의 합입니다.

TOML의 [defaults]와 각 [[sources]]에서 사용할 수 있는 설정:

설정 기본값 설명
read_only true 읽기 전용 트랜잭션
max_rows 200 반환 가능한 최대 행
statement_timeout_ms 30000 SQL 제한 시간
connection_timeout_ms 10000 연결 제한 시간
pool_size 4 해당 DB의 연결 풀 최대 크기
default_schema 없음 객체 검색의 기본 스키마

default_source가 없고 소스가 여러 개면 모든 DB 도구 호출에 data_source를 명시해야 합니다.

MCP 클라이언트 설정

클라이언트에서는 MCP 서버 하나만 등록합니다.

{
  "mcpServers": {
    "databases": {
      "command": "uv",
      "args": [
        "--directory",
        "D:/Works/postgres-mcp",
        "run",
        "postgres-mcp",
        "--config",
        "D:/secure/postgres-mcp.toml"
      ],
      "env": {
        "DEFECTS_DATABASE_URL": "postgresql://db_mcp:...@host:5432/defects",
        "VOC_DATABASE_URL": "postgresql://db_mcp:...@host:5432/voc"
      }
    }
  }
}

안전 기본값

  • asyncpg.prepare()로 SQL 문장 하나만 허용
  • 기본적으로 PostgreSQL READ ONLY 트랜잭션에서 실행
  • 읽기 전용 실행은 성공해도 롤백하여 세션 변경을 남기지 않음
  • 소스별 행 수와 statement/connection timeout
  • 큰 정수, 날짜, UUID, bytea를 JSON 안전 형식으로 변환
  • DSN은 MCP 도구 인자나 결과로 노출하지 않음

read_only는 방어 계층이지 권한 경계가 아닙니다. 운영에서는 postgres 슈퍼유저를 사용하지 말고, 각 데이터 마트마다 필요한 테이블에 SELECT 권한만 가진 별도 로그인 역할을 사용하십시오. 스키마별 접근 통제도 PostgreSQL GRANT/REVOKE로 설정해야 합니다.

개발

uv sync
uv run pytest
uv run ruff check src tests
uv run ruff format --check src tests
uv run pyright
uv build

현재 안정판 MCP Python SDK v1과 asyncpg를 사용합니다.

프로젝트 구조

src/postgres_mcp/  Python MCP 구현
tests/             Python 단위·MCP 계약 테스트
docs/              설계 및 서비스 경계 기록

현재 버전의 개발 배경, 책임 경계와 상세 구조는 v0.3.0 설계 문서에 정리되어 있습니다.

파생 코드에 적용되는 MIT 저작권 고지는 LICENSE에 유지합니다.

Recommended Servers

playwright-mcp

playwright-mcp

A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.

Official
Featured
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.

Official
Featured
Local
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.

Official
Featured
Local
TypeScript
VeyraX MCP

VeyraX MCP

Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.

Official
Featured
Local
graphlit-mcp-server

graphlit-mcp-server

The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.

Official
Featured
TypeScript
Kagi MCP Server

Kagi MCP Server

An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.

Official
Featured
Python
E2B

E2B

Using MCP to run code via e2b.

Official
Featured
Neon Database

Neon Database

MCP server for interacting with Neon Management API and databases

Official
Featured
Exa Search

Exa Search

A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.

Official
Featured
Qdrant Server

Qdrant Server

This repository is an example of how to create a MCP server for Qdrant, a vector search engine.

Official
Featured