Skip to main content
Glama
mcp-postgres

mcp-postgres

by divinedev111

CI License: MIT

mcp-postgres

PostgreSQL용 MCP 서버입니다. Model Context Protocol을 통해 AI 에이전트에게 스키마 인텔리전스, 쿼리 실행 및 DBA 도구를 제공합니다.

일반적인 데이터베이스 MCP 서버와 달리, mcp-postgres는 Postgres 네이티브입니다. 테이블/컬럼 주석을 추출하고, Postgres 전용 카탈로그 뷰를 이해하며, 인덱스 분석을 제공하고, LLM에 무제한 데이터베이스 액세스 권한을 부여하지 않도록 구성 가능한 액세스 수준을 제공합니다.

기능

스키마 인텔리전스

  • 크기 및 행 수를 포함한 스키마, 테이블, 뷰 목록

  • 전체 테이블 설명: 컬럼, 타입, 제약 조건, 인덱스, 외래 키

  • COMMENT ON 메타데이터 추출 — LLM에게 컬럼 의미에 대한 의미론적 컨텍스트 제공

  • 전체 데이터베이스에서 이름이나 주석으로 객체 검색

쿼리 실행

  • 자동 행 제한이 있는 읽기 전용 query 도구

  • 액세스 수준에 따라 제어되는 쓰기 가능 execute 도구

  • 사람이 읽을 수 있는 출력의 EXPLAIN ANALYZE

DBA 도구

  • 테이블 통계: 라이브/데드 튜플, 비대화(bloat) 비율, vacuum 이력, 스캔 패턴

  • 인덱스 분석: 사용 통계, 사용되지 않는 인덱스 감지, 누락된 인덱스 제안

  • 데이터베이스 상태: 연결, 캐시 적중률, 장기 실행 쿼리, 처리량

안전성

  • 4가지 액세스 수준: readonly, readwrite, admin, unrestricted

  • SQL 문 분류(SELECT, DML, DDL, admin) 및 강제 적용

  • stderr로 감사 로깅 (JSON, 쿼리당 하나의 항목)

Related MCP server: Postgres Scout MCP

빠른 시작

npx mcp-postgres --connection-string "postgres://user:pass@localhost:5432/mydb"

또는 환경 변수 사용:

DATABASE_URL="postgres://user:pass@localhost:5432/mydb" npx mcp-postgres

Claude Desktop

claude_desktop_config.json에 추가:

{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": [
        "-y",
        "mcp-postgres",
        "--connection-string",
        "postgres://user:pass@localhost:5432/mydb"
      ]
    }
  }
}

Claude Code

프로젝트의 .mcp.json에 추가:

{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": ["-y", "mcp-postgres"],
      "env": {
        "DATABASE_URL": "postgres://user:pass@localhost:5432/mydb"
      }
    }
  }
}

도구

도구

설명

액세스

list_schemas

테이블 수와 크기가 포함된 스키마 목록

readonly

list_tables

주석, 행 수, 크기가 포함된 테이블 목록

readonly

describe_table

컬럼, 인덱스, FK, 주석이 포함된 전체 테이블 설명

readonly

search_objects

이름이나 주석으로 객체 검색

readonly

query

SELECT 쿼리 실행

readonly

execute

INSERT/UPDATE/DELETE/CREATE 등 실행

가변

explain_query

읽기 쉬운 출력의 EXPLAIN (ANALYZE)

readonly*

table_stats

테이블 통계, 비대화, vacuum 정보

readonly

index_analysis

인덱스 사용량, 사용되지 않는 인덱스, 누락된 인덱스 힌트

readonly

database_health

연결, 캐시 비율, 긴 쿼리, 비대화

readonly

*analyze=true인 explain_query는 쿼리를 실행하므로 해당 문의 액세스 수준을 따릅니다.

리소스

URI

설명

postgres://schema/{name}

스키마에 대한 전체 DDL (주석이 포함된 CREATE TABLE 문)

postgres://extensions

설치된 PostgreSQL 확장

프롬프트

프롬프트

설명

explore-database

가이드가 포함된 데이터베이스 탐색 — 스키마, 테이블, 관계

optimize-query

EXPLAIN, 인덱스 및 권장 사항을 통한 느린 쿼리 분석

health-check

포괄적인 데이터베이스 상태 평가

구성

CLI 옵션

--connection-string  PostgreSQL connection URL
--access-level       readonly|readwrite|admin|unrestricted (default: readonly)
--row-limit          Max rows returned per query (default: 500)
--schema             Default schema filter (default: public)
--audit              Enable query audit logging to stderr

환경 변수

변수

설명

DATABASE_URL

PostgreSQL 연결 URL

POSTGRES_URL

대체 연결 URL

MCP_POSTGRES_ACCESS_LEVEL

액세스 수준 재정의

MCP_POSTGRES_ROW_LIMIT

행 제한 재정의

액세스 수준

수준

SELECT

INSERT/UPDATE/DELETE

CREATE/ALTER/DROP

TRUNCATE/DROP DATABASE

readonly

예

아니요

아니요

아니요

readwrite

예

예

아니요

아니요

admin

예

예

예

아니요

unrestricted

예

예

예

예

기본값은 readonly입니다. 필요한 최소 수준을 사용하십시오.

감사 로깅

--audit으로 활성화합니다. 모든 도구 호출을 JSON으로 stderr에 기록합니다:

{"timestamp":"2026-04-03T12:00:00.000Z","tool":"query","sql":"SELECT * FROM users","statementType":"select","accessLevel":"readonly","allowed":true,"durationMs":12,"rowCount":42}

stderr를 파일로 파이프하여 캡처: mcp-postgres --audit 2>audit.log

아키텍처

src/
├── index.ts             Entry point and CLI
├── server.ts            MCP server setup
├── config.ts            Configuration parsing
├── db/
│   ├── pool.ts          Connection pool management
│   └── query.ts         Query execution with timing
├── tools/
│   ├── schema.ts        Schema exploration tools
│   ├── query.ts         Query execution tools
│   └── performance.ts   DBA and health tools
├── resources/
│   └── schema.ts        Schema DDL resources
├── prompts/
│   └── index.ts         Prompt templates
└── safety/
    ├── classifier.ts    SQL statement classification
    ├── access.ts        Access level enforcement
    └── audit.ts         Audit logging

개발

npm install
npm test           # run tests
npm run build      # compile TypeScript
npm run dev -- --connection-string "postgres://..."  # run in dev mode

라이선스

MIT

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI assistants to safely explore, analyze, and maintain PostgreSQL databases with read-only mode by default, SQL injection prevention, query performance analysis, and optional write operations.
      55 npm
      Apache 2.0
    • A
      license
      A
      quality
      D
      maintenance
      Enables AI agents to analyze, optimize, and safely interact with PostgreSQL databases, including health checks, index recommendations, query planning, and SQL execution with read-only and production protection modes.
      15
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables AI agents to interact with PostgreSQL databases through MCP, offering index tuning, query plan analysis, schema intelligence, health checks, and safe SQL execution, with support for multiple databases.
      1
      MIT