SQL MCP Server
SQL MCP Server
Postgresデータベースを6つの読み取り専用ツールを通じてLLMエージェント(Claude Desktop、Claude Code、または任意のMCPクライアント)に公開するModel Context Protocolサーバーです。エージェントをこのサーバーに接続して、*「どの顧客が先月5件以上注文しましたか?」*のような質問をすると、エージェントはスキーマを探索し、以下のツールを使ってデータ自体にクエリを実行します。
ツール
ツール | 説明 |
| すべてのテーブルの概要:名前、説明、サイズ、列数 |
| 1つのテーブルの列、型、外部キー関係 |
| 名前がキーワードに一致するテーブル/列を検索 |
| 実際の行を覗き見る(デフォルト5行) |
| テーブルの行数 |
| 任意の読み取り専用 |
Related MCP server: mcp-data-gateway
なぜこれは「単なるpsycopg2のラッパー」ではないのか
Text-to-SQLのデモはよくありますが、実際に難しい部分—このプロジェクトが注力している部分—は、任意のSQLを生成するLLMにexecute_selectを安全に渡せるようにすることです:
読み取り専用のPostgresロール。 サーバーは
SELECTのみの権限を持つロールmcp_readonlyとして接続します(scripts/init_schema.sqlを参照)。以下のアプリケーションレベルのチェックにバグがあっても、書き込みが発生することはありません。セッションレベルでの読み取り専用の強制。 すべての接続は
SET TRANSACTION READ ONLYを実行します(db.py)。ステートメント検証(
security.py):許可されるのは単一のSELECT/WITHステートメントのみです—連結ステートメント(; DROP TABLE ...)は不可、SQLコメントも不可(コメントを利用したステートメントのすり抜けをブロック)、さらにキーワードのブロックリストがINSERT/UPDATE/DELETE/DDL/GRANTなどをカバーし、SELECT ... INTO(静かにテーブルを作成する)も含みます。識別子の検証。
describe_table、sample_rows、count_rowsはテーブル名をパラメータとして受け取ります。SQLの識別子はプレースホルダでパラメータ化できないため、テーブル名は厳密な正規表現およびinformation_schemaから取得した動的な許可リストの両方でチェックされます—単に文字列エスケープされるだけではありません。リソース制限。 Postgresの
statement_timeoutが暴走クエリを防ぎ、サーバーサイドの行数上限がすべてのクエリ結果に適用されます(LLMのクエリがLIMITを指定していない場合でも)。
クイックスタート
git clone <this-repo>
cd sql-mcp-server
pip install -r requirements.txt
# 1. Start Postgres with the sample schema
docker compose up -d
# 2. Generate sample e-commerce data (uses the postgres superuser, not mcp_readonly)
PGUSER=postgres PGPASSWORD=postgres python scripts/generate_sample_data.py
# 3. Configure the server to use the read-only role
cp .env.example .env
# edit .env if you changed the default mcp_readonly password
# 4. Run the tests
pytest
# 5. Run the server (stdio transport, for use with an MCP client)
python -m sql_mcp_server.serverClaude Desktop への接続
Claude DesktopのMCP設定(claude_desktop_config.json)に以下を追加してください:
{
"mcpServers": {
"sql-explorer": {
"command": "python",
"args": ["-m", "sql_mcp_server.server"],
"cwd": "/absolute/path/to/sql-mcp-server",
"env": {
"PGHOST": "localhost",
"PGPORT": "5432",
"PGDATABASE": "sales",
"PGUSER": "mcp_readonly",
"PGPASSWORD": "change_me"
}
}
}
}Claude Desktopを再起動し、*「どのようなテーブルが利用可能で、どの製品カテゴリの総収益が最も高いですか?」*のような質問をしてみてください。
サンプルスキーマ
orders → order_items → products → categories、さらにcustomersがあります。1件の注文の収益 = sum(order_items.quantity * order_items.unit_price)。ジェネレータは、クエリが実データを扱っているように見えるよう、~600人の顧客、~3,500件の注文、そしていくつかの意図的なデータの癖(メールアドレスの欠落、大量注文の外れ値)をシードします。
テスト
tests/test_security.pyとtests/test_tools.pyはデータベースなしで実行されます—検証レイヤーを直接テストし、DBレイヤーをモックした状態でツール関数をテストします。CIが実行するのはこれです。db.py自体(psycopg2レイヤー)は、サーバーをDocker Postgresインスタンスに対して実行することで実際に検証されます。上記のクイックスタートを参照してください。
プロジェクト構造
sql_mcp_server/
config.py Environment-based settings
security.py SQL/identifier validation (the core safety logic)
db.py psycopg2 access layer
server.py MCP tool definitions
scripts/
init_schema.sql Schema + read-only role setup
generate_sample_data.py Faker-based sample data
tests/
test_security.py Validation logic (18+ cases: injection, stacked
statements, comment smuggling, DDL/DML blocking, etc.)
test_tools.py Tool functions with mocked DBThis server cannot be deployed
Maintenance
Related MCP Connectors
- dataOAuthco.thinair
PostgreSQL, MySQL, and SQL Server in one session. 26 read-only MCP tools for AI agents.
Query PostgreSQL databases in plain English — LLM-generated, safety-validated SQL.
Text-to-SQL MCP server: read-only queries on PostgreSQL, MySQL and SQL Server with your real schema
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceEnables interaction with PostgreSQL databases through MCP, allowing users to explore database structures, inspect table schemas, and execute read-only SQL queries.-
- AlicenseNot gradedqualityDmaintenanceEnables AI agents to query a PostgreSQL database through a small set of controlled, read-only tools for schema inspection, row lookup, and aggregate statistics.1MIT
- FlicenseNot gradedqualityDmaintenanceEnables AI assistants to execute SQL queries and inspect PostgreSQL database schemas via MCP tools.-
- AlicenseNot gradedqualityDmaintenanceA read-only natural-language database agent that exposes PostgreSQL schema-discovery and SELECT tools via MCP, enabling users to query databases in plain English.MIT