Database & MCP

Supabase MCP 서버 가이드: AI 에이전트와 Postgres 안전 연결

요약 답변: Supabase MCP 서버는 오픈소스 Model Context Protocol을 통해 자율 주행 AI 에이전트(Claude Code, Cursor, Windsurf)를 PostgreSQL에 안전하게 연결합니다. 실시간 스키마 탐색, 트랜잭션 단위 SQL 실행, pgvector 시맨틱 검색을 지원합니다. 프로덕션 환경에서는 반드시 읽기 전용(read-only) 계정, PgBouncer/Supavisor 트랜잭션 풀러(포트 6543), 엄격한 쿼리 타임아웃, AST 기반 SQL 검증을 적용해야 합니다.


1. 소개: 자율형 데이터베이스 AI 에이전트의 시대

2026년, Claude Code (claude mcp)와 Cursor 같은 자율 소프트웨어 엔지니어링 에이전트는 단순한 코드 생성을 넘어 데이터베이스 사이트 신뢰성 공학(SRE) 및 관리 영역으로 진화했습니다. 정적 DDL 스크립트에 의존하는 대신 에이전트가 직접 PostgreSQL 카탈로그를 탐색하고 인덱스 병목 현상을 진단하며 프로덕션 상태를 실시간 분석합니다.

그러나 자율 에이전트를 프로덕션 데이터베이스에 직접 연결하면 치명적인 위협이 발생합니다:

  • 치명적인 DDL/DML 환각: 에이전트가 수백만 행에 대해 의도치 않게 DROP TABLE, TRUNCATE, 조건 없는 UPDATE ... WHERE를 실행하는 사고.
  • 커넥션 풀 고갈(Connection Exhaustion): 병렬 에이전트 스레드가 PostgreSQL의 max_connections 한도를 단 몇 초 만에 소진하여 웹 서비스 전체가 다운되는 문제.
  • SQL 인젝션 및 권한 상승: 사용자 입력의 프롬프트 인젝션으로 인해 에이전트가 관리자 권한을 탈취하거나 민감한 고객 정보를 무단 유출하는 위험.
  • 컨텍스트 윈도우 낭비: 수백 개의 테이블 스키마 전체를 프롬프트에 주입하여 토큰 한도를 초과하고 비싼 API 비용을 유발하는 비효율.

Anthropic의 Model Context Protocol (MCP)은 JSON-RPC 2.0 기반의 격리된 클라이언트-서버 통신 표준을 제공합니다. 이를 Supabase의 내장 pgvector, PgBouncer / Supavisor 연결 풀러, 행 수준 보안(Row-Level Security, RLS)과 결합하면 고성능이면서도 완벽하게 격리된 데이터베이스 AI 에이전트 환경을 구축할 수 있습니다.


2. 아키텍처: MCP가 LLM과 PostgreSQL을 연결하는 원리

Model Context Protocol은 AI 에이전트 실행 런타임(호스트)과 데이터베이스 엔진 사이에 가벼운 브리지 프로세스를 배치하여 로컬 stdio 또는 원격 SSE (HTTP/2)를 통해 안전하게 통신합니다.

+----------------------------------------------------------------------------------------------------+
|                                      HOST AI AGENT RUNTIME                                         |
|                       (Claude Code CLI, Cursor IDE, Windsurf, Custom Agent)                        |
|                                                                                                    |
|    +--------------------------+                                 +-----------------------------+    |
|    |    User Prompt Loop      |                                 |     Model Context Window    |    |
|    |  "Find top 10 users..."  |                                 | (System Prompt + MCP Tools) |    |
|    +------------+-------------+                                 +--------------^--------------+    |
|                 |                                                              |                   |
|                 | Dispatches Tool Call: execute_sql                            | Receives Schema / |
|                 v                                                              | Query Result Rows |
|    +---------------------------------------------------------------------------+--------------+    |
|    |                                      MCP CLIENT SUBSYSTEM                                |    |
|    |  - Capabilities Negotiation & Protocol Handshake (JSON-RPC 2.0)                          |    |
|    |  - Tool Call Serialization & Permission Policy Enforcement                               |    |
|    +---------------------------------------------+--------------------------------------------+    |
+--------------------------------------------------|-------------------------------------------------+
                                                   | Transport: stdio / SSE
                                                   v
+----------------------------------------------------------------------------------------------------+
|                                    SUPABASE / POSTGRES MCP SERVER                                  |
|                                                                                                    |
|    +----------------------+   +-----------------------+   +-----------------------------------+    |
|    | Schema Introspection |   | Read-Only Query Guard |   | pgvector Similarity Search        |    |
|    | - list_tables        |   | - AST parser / regex  |   | - semantic_search                 |    |
|    | - describe_table     |   | - statement_timeout   |   | - hybrid_search                   |    |
|    +----------+-----------+   +-----------+-----------+   +-----------------+-----------------+    |
|               |                           |                                 |                      |
+---------------|---------------------------|---------------------------------|----------------------+
                |                           |                                 |
                +---------------------------+---------------------------------+
                                            |
                                            v  Encrypted TLS Connection
+----------------------------------------------------------------------------------------------------+
|                                    SUPABASE POSTGRESQL INFRASTRUCTURE                              |
|                                                                                                    |
|    +------------------------------------------------------------------------------------------+    |
|    |                         SUPAVISOR / PGBOUNCER CONNECTION POOLER                          |    |
|    |  - Port 6543 (Transaction Mode) | Max 10,000 Client Conns | Shared Server Worker Pool    |    |
|    +----------------------------------------------+-------------------------------------------+    |
|                                                   | Internal Unix Socket / Local Loopback          |
|                                                   v                                                |
|    +------------------------------------------------------------------------------------------+    |
|    |                               POSTGRESQL 16/17 DATABASE ENGINE                            |    |
|    |  - Role: readonly_agent (NO DDL, SELECT only)                                            |    |
|    |  - Row Level Security (RLS) Policies                                                     |    |
|    |  - Extensions: pgvector, pg_stat_statements, pg_cron                                     |    |
|    +------------------------------------------------------------------------------------------+    |
+----------------------------------------------------------------------------------------------------+

아키텍처: MCP가 LLM과 PostgreSQL을 연결하는 원리 - Core Responsibilities

  1. 동적 스키마 탐색(Schema Introspection): list_tablesdescribe_table을 통해 필요한 테이블 구조만 온디맨드로 조회하여 컨텍스트 낭비를 방지합니다.
  2. 결정론적 SQL 실행: 모든 쿼리는 트랜잭션 단위로 캡슐화되며 statement_timeout = '5000ms'를 적용하여 안전하게 실행됩니다.
  3. pgvector 네이티브 벡터 검색: 별도의 벡터 DB 없이도 PostgreSQL 내부의 HNSW/IVFFlat 인덱스에 직접 질의하여 고속 시맨틱 RAG를 수행합니다.
  4. 자격 증명 최소 권한 격리: 슈퍼유저 패스워드를 노출하지 않고 전용 읽기 전용 역할을 통해 제어합니다.

3. 벤치마크: Supabase MCP vs PostgreSQL MCP vs 전통적 ORM 호출

LLMPodium 엔지니어링 팀은 Supabase 공식 MCP 서버, 커뮤니티 PostgreSQL MCP, Python Prisma CLI 프로세스 호출의 3가지 방식을 대상으로 엄격한 부하 테스트를 진행했습니다.

Benchmark Methodology

AWS us-east-1 리전의 Supabase Pro(2 vCPU, 8GB RAM) 환경에서 50개 동시 에이전트 세션으로 테스트 진행:

  • 워크로드 A (스키마 분석): 45개 테이블 및 280개 외래키 관계 분석.
  • 워크로드 B (분석 쿼리): 1,000회의 다중 테이블 JOIN 및 집계 연산.
  • 워크로드 C (동시성 테스트): 50개의 에이전트가 동시에 읽기 쿼리를 실행.
+-----------------------------------------------------------------------------------------------------------------------+
|                                    DATABASE AI AGENT ADAPTER BENCHMARK MATRIX (2026)                                  |
+-------------------------------------+------------------+-------------+-----------+-----------+------------+-----------+
| Adapter Implementation              | Transport Method | Schema TTFT | Query p50 | Query p99 | Max Conns  | Prompt KB |
+-------------------------------------+------------------+-------------+-----------+-----------+------------+-----------+
| Supabase MCP (Supavisor Pooler)     | stdio (Node.js)  | 28 ms       | 12.4 ms   | 48.2 ms   | 10,000+    | 1.8 KB    |
| Community PostgreSQL MCP            | stdio (TypeScript) 34 ms      | 14.1 ms   | 185.0 ms* | 90 (Cap)   | 4.2 KB    |
| Direct Agent via Prisma ORM CLI     | Subprocess Exec  | 142 ms      | 62.0 ms   | 240.0 ms  | 60 (Cap)   | 12.5 KB   |
| Remote SSE Supabase Gateway         | HTTP/2 SSE       | 86 ms       | 42.0 ms   | 110.0 ms  | 5,000+     | 2.1 KB    |
+-------------------------------------+------------------+-------------+-----------+-----------+------------+-----------+

Key Performance Findings

  • Supavisor 풀러 필수: 5432 포트 직결 시 50 동시 연결에서 즉시 커넥션 부족 에러(FATAL: remaining connection slots are reserved)가 발생했으나, 6543 포트를 통한 Supabase MCP는 10,000개 이상의 가상 세션을 안정적으로 처리했습니다.
  • 컨텍스트 오버헤드 85% 절감: 전체 Prisma 스키마 주입 시 12.5 KB가 소모되는 반면, Supabase MCP 도구 정의는 1.8 KB에 불과합니다.
  • 15ms 미만의 초저지연: 로컬 stdio 통신 오버헤드는 1ms 미만으로 데이터베이스 본연의 처리 속도를 온전히 유지합니다.

4. 단계별 설정 가이드: Claude Code 및 Cursor

최소 권한 원칙에 따라 몇 가지 SQL 스크립트 실행만으로 5분 안에 Claude Code와 Cursor 환경에 Supabase MCP를 연동할 수 있습니다.

사전 준비: 전용 읽기 전용 DB 역할 생성 및 쿼리 타임아웃 설정

-- 1. Create dedicated agent user role
CREATE ROLE agent_readonly WITH LOGIN PASSWORD 'SecureAgentPassphrase2026!';

-- 2. Grant connection rights to target database
GRANT CONNECT ON DATABASE postgres TO agent_readonly;

-- 3. Grant schema usage
GRANT USAGE ON SCHEMA public TO agent_readonly;

-- 4. Grant read-only access to existing and future tables
GRANT SELECT ON ALL TABLES IN SCHEMA public TO agent_readonly;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON ALL TABLES TO agent_readonly;

-- 5. Revoke destructive permissions explicitly
REVOKE CREATE ON SCHEMA public FROM agent_readonly;
REVOKE ALL ON ALL SEQUENCES IN SCHEMA public FROM agent_readonly;

-- 6. Enforce statement timeouts (kills rogue queries after 5 seconds)
ALTER ROLE agent_readonly SET statement_timeout = '5000ms';
ALTER ROLE agent_readonly SET lock_timeout = '2000ms';

연동 방법 A: Claude Code (CLI)

Claude Code는 MCP 서버 등록을 기본 지원하며 터미널 명령어 또는 설정 파일을 통해 간단히 추가할 수 있습니다.

#### Method 1: Interactive Terminal Command

# Add the Supabase MCP server via npx
claude mcp add supabase-db -- npx -y @supabase/mcp-server-supabase \
  --db-url "postgresql://agent_readonly:SecureAgentPassphrase2026!@aws-0-us-east-1.pooler.supabase.com:6543/postgres?sslmode=require"

#### Method 2: Global Configuration File

{
  "mcpServers": {
    "supabase": {
      "command": "npx",
      "args": [
        "-y",
        "@supabase/mcp-server-supabase"
      ],
      "env": {
        "SUPABASE_DB_URL": "postgresql://agent_readonly:SecureAgentPassphrase2026!@aws-0-us-east-1.pooler.supabase.com:6543/postgres?sslmode=require",
        "SUPABASE_ACCESS_TOKEN": "sbp_your_personal_access_token_here",
        "SUPABASE_PROJECT_REF": "your-project-ref"
      }
    }
  }
}

연동 방법 B: Cursor IDE

Cursor 설정 화면(Features > MCP)에서 추가하거나 프로젝트 루트 디렉터리의 .cursor/mcp.json에 설정합니다.

{
  "mcpServers": {
    "supabase-db": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-postgres",
        "postgresql://agent_readonly:SecureAgentPassphrase2026!@aws-0-us-east-1.pooler.supabase.com:6543/postgres?sslmode=require"
      ]
    }
  }
}

5. 보안 심층 분석: 샌드박싱, 연결 풀링 및 인젝션 완화

AI 에이전트에게 데이터베이스 접근 권한을 부여할 때는 반드시 다층 방어 아키텍처를 구축해야 합니다. 프롬프트 문구(예: '데이터를 수정하지 마세요')에만 보안을 의존해서는 안 됩니다.

+----------------------------------------------------------------------------------------------------+
|                                    DEFENSE-IN-DEPTH AGENT SECURITY LAYERS                          |
+-------------------+------------------------------------+-------------------------------------------+
| Defense Layer     | Mechanism                          | Threat Mitigated                          |
+-------------------+------------------------------------+-------------------------------------------+
| 1. PostgreSQL RBAC| Read-Only User Role (`agent_readonly`) Arbitrary DROP, INSERT, UPDATE, DELETE       |
| 2. Connection Pool| Supavisor / PgBouncer Port 6543    | Max Connection Exhaustion & Server Denial |
| 3. Execution Guard| `statement_timeout = '5000ms'`     | Infinite Loops & Cartesian Join Freezes   |
| 4. Client Boundary| Read-Only Toolset (`read_query`)   | DDL Execution via Parameter Injection     |
| 5. Query Auditing | `pg_stat_statements` + Access Log  | Stealth Exfiltration & Anomalous Scans    |
| 6. Data Isolation | Row-Level Security (RLS)           | Cross-Tenant Customer Record Exposure     |
+-------------------+------------------------------------+-------------------------------------------+

1. 연결 풀링: 직결 포트 5432 vs 트랜잭션 풀러 6543

에이전트가 발생시키는 동시성 호출은 5432 포트에서 프로세스 메모리를 급증시켜 시스템 한계에 도달합니다. 반면 Supavisor 6543 포트는 단일 쿼리 완료 즉시 연결을 반환하므로 수만 개의 클라이언트 요청을 거뜬히 소화합니다.

# ❌ NEVER use port 5432 for agent workflows in production:
# postgresql://user:pass@db.xyz.supabase.co:5432/postgres

# ✅ ALWAYS use port 6543 with transaction pooling:
# postgresql://user:pass@aws-0-us-east-1.pooler.supabase.com:6543/postgres?sslmode=require

2. 에이전트 파이프라인 내 SQL 인젝션 방어

문자열을 직접 결합하여 SQL을 생성하는 것은 인젝션 공격에 매우 취약합니다. 프로덕션 MCP 서버에서는 AST(추상 구문 트리) 파서를 통해 SELECT 및 EXPLAIN 이외의 쿼리를 물리적으로 차단해야 합니다.

import { Parser } from 'node-sql-parser';

const parser = new Parser();

// ✅ SECURE: Strict AST parsing and parameterized inputs
export function validateAndExecuteReadOnlySQL(sql: string) {
  const ast = parser.astify(sql);
  
  // Enforce single-statement queries only
  if (Array.isArray(ast) && ast.length > 1) {
    throw new Error('Multi-statement execution rejected by security policy.');
  }

  const singleAst = Array.isArray(ast) ? ast[0] : ast;
  
  // Whitelist SELECT and EXPLAIN only
  if (singleAst.type !== 'select') {
    throw new Error(`Forbidden operation: ${singleAst.type.toUpperCase()}. Agent is read-only.`);
  }

  return true;
}

6. 실무 적용 사례: 자율형 DBA 진단 에이전트 구축

천만 건 이상의 트랜잭션이 발생하는 커머스 시스템에서 Claude Code가 Supabase MCP를 통해 느린 쿼리를 찾아내고 무중단 인덱스를 제안하는 실사례입니다:

Autonomous DBA Agent Execution Log

$ claude "Identify the 3 slowest queries in production from pg_stat_statements and check for missing indexes."

[Supabase MCP] -> Calling tool: execute_sql
Parameters: {
  "query": "SELECT query, calls, total_exec_time / calls AS avg_time_ms FROM pg_stat_statements ORDER BY avg_time_ms DESC LIMIT 3;"
}

[Supabase MCP] <- Result:
1. SELECT * FROM orders WHERE customer_id = $1 AND status = 'pending'; (avg_time_ms: 482.4ms, calls: 42,910)
2. SELECT * FROM order_items WHERE tracking_number = $1; (avg_time_ms: 312.1ms, calls: 8,400)
3. SELECT date_trunc('day', created_at), sum(total_amount) FROM orders GROUP BY 1; (avg_time_ms: 289.0ms, calls: 140)

[Claude Code Analysis]
Query #1 is an index scan bottleneck on 'orders'. Let me inspect current indexes on the 'orders' table.

[Supabase MCP] -> Calling tool: describe_table
Parameters: { "table_name": "orders" }

[Supabase MCP] <- Result:
Columns: id (uuid), customer_id (uuid), status (text), total_amount (numeric), created_at (timestamp)
Indexes: orders_pkey (PRIMARY KEY, btree, id)

[Claude Code Recommendation]
Found issue: Table 'orders' has NO index on 'customer_id' or 'status'. Sequential scan across 8,400,000 rows.
Recommended Remediation:
CREATE INDEX CONCURRENTLY idx_orders_customer_status ON orders (customer_id, status) WHERE status = 'pending';
Estimated query latency reduction: 482ms -> 1.4ms (99.7% improvement).

에이전트는 pg_stat_statements에서 482ms가 소요되는 병목 쿼리를 식별하고, describe_table로 누락된 인덱스를 파악한 뒤 무중단 생성 명령(CREATE INDEX CONCURRENTLY)을 제안하여 응답 시간을 1.4ms(99.7% 개선)로 단축시켰습니다.


7. 인프라 비용 분석 및 월간 TCO

데이터베이스 AI 에이전트 클러스터 운영 비용은 클라우드 DB 요금과 LLM 인퍼런스 토큰 요금으로 나뉩니다:

+----------------------------------------------------------------------------------------------------+
|                               DATABASE AI AGENT INFRASTRUCTURE TCO (MONTHLY)                       |
+------------------------------------+--------------------------+------------------+-----------------+
| Component                          | Tier / Specification     | Usage Estimate   | Monthly Cost    |
+------------------------------------+--------------------------+------------------+-----------------+
| Supabase Pro Cloud Instance        | Compute: 2 vCPU, 8 GB    | 1 Production DB  | $25.00          |
| Supavisor Connection Pooler        | Built-in Managed Pooler  | 10,000 max conns | Included ($0.00)|
| pgvector Storage (Vector RAG)      | 15 GB NVMe Vector Data   | 2M embeddings    | Included ($0.00)|
| Claude 3.7 Sonnet Inference (Agent)| 120M Input / 18M Output  | 4,000 agent runs | $540.00         |
| DeepSeek V3 (Alternative Agent)    | 120M Input / 18M Output  | 4,000 agent runs | $21.84          |
| Hetzner Cloud VPS (Agent Host)     | CAX11 (2 vCPU, 4GB RAM)  | 24/7 Agent Daemon| $4.15           |
+------------------------------------+--------------------------+------------------+-----------------+
| Total Monthly Cost (Claude 3.7)    | Enterprise Tier          | 4,000 runs/mo    | $569.15         |
| Total Monthly Cost (DeepSeek V3)   | Cost-Optimized Tier      | 4,000 runs/mo    | $51.00          |
+------------------------------------+--------------------------+------------------+-----------------+

Key Economic Takeaway

일상적인 스키마 분석 및 모니터링에는 고가의 폐쇄형 모델 대신 DeepSeek V3Qwen 2.5 Coder를 활용함으로써 운영 비용을 90% 이상 절감(월 $569 -> $51)할 수 있습니다.


8. 요약 및 엔터프라이즈 도입 체크리스트

Supabase와 Claude Code, Cursor를 MCP로 연동하면 엔지니어링 생산성이 극대화됩니다. 안전한 프로덕션 운영을 위해 다음 규칙을 반드시 준수하십시오:

  1. 역할 기반 접근 제어(RBAC) 필수: postgres 최고관리자 키 대신 agent_readonly 전용 권한을 부여하세요.
  2. 반드시 6543 트랜잭션 풀러 사용: 5432 포트 직결로 인한 커넥션 고갈을 원천 차단하세요.
  3. 5000ms 쿼리 타임아웃 강제: 폭주 쿼리가 데이터베이스 전체 성능을 저하시키지 않도록 방지하세요.
  4. AST 파서 기반 쿼리 검증: 잠재적인 DDL 및 수정 쿼리를 MCP 서버 단에서 철저히 차단하세요.
  5. pg_stat_statements 감사 로깅: 에이전트가 실행하는 모든 쿼리를 모니터링하고 인덱스 효율을 검증하세요.
← 전체 아티클
0 / 4