CC逆引きリファレンス

PostgreSQL MCP を使いたい

7. MCP(Model Context Protocol)

コマンド / 機能

claude mcp add postgres -- npx @anthropic/mcp-postgres

DB接続

概要

Anthropic 公式の PostgreSQL MCP サーバーです。データベースへの接続、スキーマ情報の取得、SQL クエリの実行(読み取り専用)などの機能を提供します。

設定例

# 接続 URL を使用して追加
claude mcp add -s project \
  -e DATABASE_URL=postgresql://user:password@localhost:5432/dbname \
  postgres -- npx -y @anthropic/mcp-postgres

# 各パラメータを環境変数で指定
claude mcp add -s project \
  -e PGHOST=localhost \
  -e PGPORT=5432 \
  -e PGUSER=myuser \
  -e PGPASSWORD=mypassword \
  -e PGDATABASE=mydb \
  postgres -- npx -y @anthropic/mcp-postgres

# SSL 接続が必要な場合
claude mcp add -s project \
  -e DATABASE_URL=postgresql://user:pass@host:5432/db?sslmode=require \
  postgres -- npx -y @anthropic/mcp-postgres

# 利用可能なツール例
# - query: SQL クエリ実行(SELECT のみ)
# - list_tables: テーブル一覧
# - describe_table: テーブル構造

こんな時に使う

  • データベースのクエリを実行したい時
  • DB スキーマを確認・操作したい時

使い方

  1. 1データベースの接続情報(URL または個別パラメータ)を用意
  2. 2claude mcp add で接続情報を環境変数として設定
  3. 3セキュリティのためプロジェクトスコープ(-s project)推奨
  4. 4/tools で query, list_tables などのツールを確認

Tips

  • 読み取り専用(SELECT)のみ実行可能でデータは安全
  • 本番 DB への接続はリードレプリカ使用を推奨
  • パスワードに特殊文字がある場合は URL エンコードが必要
  • .claude/ を .gitignore に追加して認証情報を保護