クイックアンサー: Supabase MCPサーバーは、Model Context Protocolを通じてClaude Code、Cursorなどの自律型AIエージェントをPostgreSQLに安全に接続します。リアルタイムのスキーマ検証、安全なSQL実行、pgvectorベクトル検索を提供。本番環境では読み取り専用(read-only)権限、PgBouncer/Supavisorトランザクションプール(ポート6543)、クエリタイムアウト設定、AST構文解析によるSQLインジェクション対策が必須です。
1. はじめに:自律型データベースAIエージェントの進化
2026年、Claude Code (claude mcp) や Cursor などの自律型エンジニアリングエージェントは、単なるコード補全を超えてデータベース全体の運用とSRE領域へと進出しました。DDLファイルを手動で作成する代わりに、エージェント自身がPostgreSQLカタログを自律的に探索し、インデックスのボトルネックを診断し、マイグレーションの整合性をチェックします。
しかし、自律型LLMを本番データベースに直接接続することには重大なセキュリティリスクが伴います:
- 壊滅的なDDL/DMLハルシネーション: エージェントが誤って
DROP TABLE、条件なしのTRUNCATE、未インデックスのUPDATE ... WHEREを数百万行規模で実行するリスク。 - コネクションプールの枯渇(Connection Exhaustion): エージェントの並列ツール呼び出しが短時間でPostgreSQLの
max_connectionsを使い果たし、Webアプリがダウンする障害。 - SQLインジェクションと権限昇格: プロンプトインジェクションにより、意図しない管理者クエリや機密顧客データの漏洩が引き起こされる危険。
- コンテキストウィンドウの圧迫: 何百ものテーブル定義を丸ごとプロンプトに流し込み、トークン消費と推論コストを爆発させる非効率。
Anthropicが策定した Model Context Protocol (MCP) は、JSON-RPC 2.0に基づく安全で標準化されたプロトコルです。オープンソースPostgresクラウドの Supabase が備える pgvector、PgBouncer / Supavisor コネクションプーラー、行単位セキュリティ(RLS)と組み合わせることで、開発者は堅牢で自己修復可能なデータベースエージェントを構築できます。
2. アーキテクチャ:MCPがLLMとPostgreSQLを接続する仕組み
Model Context Protocolは、AIエージェントの実行環境(Claude Code CLIやCursor)とデータベースエンジンを分離し、ローカルの 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
- 動的スキーマ検証(Schema Introspection): プロンプトに関連するテーブルのみを
list_tablesやdescribe_tableで取得し、コンテキストの肥大化を防止。 - 決定論的クエリ実行: クエリをトランザクション単位で安全に実行し、
statement_timeout = '5000ms'で長時間処理を強制停止。 - pgvectorによるセマンティック検索: 外部ベクトルDBを介さず、PostgreSQL内部のHNSW/IVFFlatインデックスに直接クエリを発行。
- 認証情報の最小化: スーパーユーザー権限を直接渡さず、専用の読み取り専用ロール経由で安全に制御。
3. ベンチマーク比較:Supabase MCP vs PostgreSQL MCP vs 直接ORM呼び出し
LLMPodiumエンジニアリングチームは、Supabase公式MCPサーバー、コミュニティ版PostgreSQL MCP、Python/Prisma CLIサブプロセスの3つの手法で性能検証を実施しました。
ベンチマーク検証手法
AWS us-east-1リージョンのSupabase Pro(2 vCPU, 8GB RAM)環境において、50並列エージェントで負荷テストを実施:
- ワークロードA(スキーマ検出): 45テーブル・280外部キーのトポロジー構造を解析。
- ワークロードB(分析クエリ): 1,000回の複数テーブルJOIN集計を実行。
- ワークロードC(高並列負荷): 50のAIエージェントが同時にデータ抽出を実行。
+-----------------------------------------------------------------------------------------------------------------------+
| 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 |
+-------------------------------------+------------------+-------------+-----------+-----------+------------+-----------+
主要な性能検証結果
- Supavisorによるプーリングが不可欠: 直結ポート5432では50並列で即座に接続エラー(
FATAL: remaining connection slots are reserved)が発生。ポート6543経由のSupabase MCPは10,000仮想セッションを安定処理。 - コンテキストトークンの削減: Prismaスキーマ全文(12.5 KB)に比べ、Supabase MCPのツール定義はわずか 1.8 KB と85%以上のトークンを削減。
- 15ms未満の低レイテンシ: ローカルstdioのオーバーヘッドは1ms未満で、ボトルネックなくPostgreSQLの本来の速度を発揮。
4. 設定手順:Claude CodeおよびCursorへの導入
最小権限の原則に基づき、5分以内にClaude CodeとCursor IDEへSupabase MCPを導入できます。
事前準備:読み取り専用エージェントロールの作成とタイムアウト設定
-- 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サーバーの自動検出をネイティブサポートしており、CLIコマンドまたは設定ファイルから追加できます。
#### 方法1:対話型ターミナルコマンド
# 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"
#### 方法2:グローバル設定ファイル
{
"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. セキュリティ対策:サンドボックス、コネクションプール、SQL注入防止
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は接続ごとにOSプロセスを生成(メモリ5〜10MB消費)するため、エージェントの並列処理ですぐに上限に達します。Supavisorのポート6543(トランザクションモード)を使用することで、数万件のリクエストを少数のPostgresワーカーで安全に共有できます。
# ❌ 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診断エージェントの運用
数千万件のトランザクションを処理するECプラットフォームにおいて、Claude Codeが遅延クエリを自動特定し、安全に最適化インデックスを提案する実例です:
自律型DBAエージェントの実行ログ
$ 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のボトルネックを検出し、テーブルのインデックスを調査した上で CREATE INDEX CONCURRENTLY による安全な最適化を提示。クエリレイテンシを1.4msへと99.7%短縮させました。
7. インフラ費用とTCO(総所有コスト)の試算
データベースAIエージェントの運用コストは、クラウドDBのインフラ費用とLLM推論APIのトークン費用で構成されます:
+----------------------------------------------------------------------------------------------------+
| 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 |
+------------------------------------+--------------------------+------------------+-----------------+
経済性分析の結論
日常的なクエリ監視やスキーマ調査には、DeepSeek V3 や Qwen 2.5 Coder などのコスト効率に優れたフロンティアモデルを活用することで、運用コストを 90%以上削減(月額$569から$51へ)可能です。
8. まとめとエンタープライズ運用チェックリスト
Model Context Protocolを介してSupabaseとClaude Code/Cursorを連携することで、安全かつ迅速な開発が可能になります。本番導入時は以下を遵守してください:
- RBACの徹底:
postgresスーパーユーザー権限は絶対に渡さず、agent_readonlyロールを作成すること。 - ポート6543(Supavisor)経由で接続: トランザクションプーリングで接続数オーバーフローを防止すること。
- 5000msのクエリタイムアウト設定: 長時間クエリによるDBリソースの枯渇を防ぐこと。
- ASTパーサーによるSQL検証: DDLや更新系コマンドをMCP内部でブロックすること。
pg_stat_statementsでの監視: AIエージェントが実行したクエリをすべてロギング・分析すること。