Text2SQL-MCP
Allows read-only SQL queries on PostgreSQL databases, with 5-layer validation for safe SELECT execution.
Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Text2SQL-MCPWho are the top 5 customers by total spending?"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Text2SQL-MCP
Doğal dili, çok katmanlı güvenlik validasyonu ile güvenli SQL'e çeviren MCP (Model Context Protocol) sunucusu.
Text2SQL-MCP, LLM tabanlı ajanların PostgreSQL veritabanlarına sadece okuma (read-only) erişimle sorgu yapabilmesini sağlar. MCP protokolü üzerinden üç tool sunar:
run_query(sql)— Güvenli SELECT sorgusu çalıştırma (5 katmanlı validasyon).get_schema(tables)— Veritabanı şema bilgisi.get_table_sample(table, limit)— Tablodan örnek veri.
Detaylı mimari için ARCHITECTURE.md dosyasına bakın.
✨ Özellikler
✅ 5 katmanlı SQL validasyonu (syntax, statement type, schema cross-check, injection detection, resource guard)
✅ Read-only garantisi —
llm_readerkullanıcısı sadece SELECT yetkisine sahip✅ Defense in depth — multi-statement tespiti,
statement_timeout, row limit, LIMIT otomatik ekleme✅ MCP Protocol — Claude Desktop, Cursor ve diğer MCP istemcileriyle uyumlu
✅ Chinook DB — 11 tablolu, 600KB örnek müzik veritabanı (DVD Rental alternatifi)
✅ RAG desteği — glossary + gold queries + schema ile ChromaDB tabanlı bağlam geri getirme (MMR + threshold)
Related MCP server: PostgreSQL MCP Server
📋 Gereksinimler
Gereksinim | Açıklama |
Python 3.11+ | |
Docker Desktop | |
PowerShell 5.1+ | Windows ile birlikte gelir |
Google Gemini API Key | aistudio.google.com — ücretsiz kayıt |
⚡ Windows'ta Hızlı Kurulum (PowerShell)
Yönetici PowerShell'de proje kök dizininde şu komutu çalıştırın:
.\scripts\setup.ps1Bu script şunları yapar:
✅ Python sanal ortamı (venv) oluşturur
✅ Bağımlılıkları yükler (pip install -r requirements.txt)
✅
.envdosyasını oluşturur (.env.example'dan kopyalar)✅ Docker container'ını başlatır (PostgreSQL + Chinook DB otomatik yüklenir)
✅
data/schema.yamlşema dosyasını çıkarır✅ Testleri çalıştırmaya hazır hale gelir
⚠️ ÖNEMLİ: Kurulumdan sonra
.envdosyasını açıpGEMINI_API_KEYdeğerini mutlaka girin! API anahtarı olmadan pipeline çalışmaz.
Adım Adım Kurulum (Manuel)
# 1. Python sanal ortamı
python -m venv venv
# 2. Bağımlılıklar
.\venv\Scripts\pip install -r requirements.txt
# 3. Ortam değişkenleri
Copy-Item .env.example -Destination .env
# Şimdi .env dosyasını düzenleyip ANTHROPIC_API_KEY ekleyin!
# 4. PostgreSQL + Chinook DB'yi başlat (Docker)
docker compose up -d
# 5. Şemayı çıkar
.\venv\Scripts\python scripts\extract_schema.py
# 6. Testleri çalıştır
.\venv\Scripts\pytest tests\ -v🗄️ Kullanılan Veritabanı: Chinook
Bu proje Chinook müzik veritabanı ile birlikte gelir. DVD Rental yerine ücretsiz ve açık kaynak bir alternatiftir.
Chinook tabloları (11 adet):
Tablo | Kayıt | Açıklama |
| 347 | Müzik albümleri |
| 275 | Sanatçılar |
| 59 | Müşteriler |
| 8 | Çalışanlar |
| 25 | Müzik türleri |
| 412 | Faturalar |
| 2240 | Fatura satırları |
| 5 | Medya türleri |
| 18 | Çalma listeleri |
| 8715 | Çalma listesi-parça eşleşmesi |
| 3503 | Müzik parçaları |
💡 İpucu: Chinook, DVD Rental'a benzer bir e-ticaret yapısına sahiptir (müşteri, fatura, ödeme). Bu sayede aynı türde SQL sorguları (JOIN, aggregation, filtering) çalıştırabilirsiniz.
🚀 Kullanım
MCP Server'ı Başlatma
# PowerShell
.\scripts\run_server.ps1# Linux/Mac veya WSL
./scripts/run_server.sh
# veya
make serverServer stdio üzerinden MCP protokolü ile konuşur. Claude Desktop, Cursor veya özel bir MCP istemcisi ile entegre edilebilir.
Pipeline ile Sorgu Çalıştırma (Faz 3)
from pipeline.orchestrator import Orchestrator
pipeline = Orchestrator()
response = pipeline.process("En çok satan 5 sanatçı kimdir?")
print(response.formatted_answer)Orchestrator doğal dili alır, RAG bağlamı ile birleştirir, Gemini üzerinde SQL üretir, güven skoru hesaplar ve sonucu markdown olarak formatlar.
Streamlit UI (Bonus Faz)
Pipeline'ı görsel arayüzle kullanın — sorgu, benchmark ve şema keşfi:
.\venv\Scripts\streamlit run ui/app.pyUI üç sayfa sunar (sidebar navigasyon):
Sayfa | İçerik |
🔍 Sorgu | Doğal dil sorusu → SQL + sonuç + güven skoru (renk kodlu). Örnek soru butonları ve sorgu geçmişi. |
📊 Benchmark |
|
🗄️ Şema | Veritabanı şema keşfi — tablolar, kolonlar, PK/FK, index, satır sayısı, örnek veri. |
Not: UI için
GEMINI_API_KEYve çalışan PostgreSQL bağlantısı gerekir (sidebar'da durum gösterilir).
Testleri Çalıştırma
.\venv\Scripts\pytest tests\ -vFaydalı Komutlar
Komut | Açıklama |
| Tüm ortamı kurar |
| Testleri çalıştırır |
| MCP server'ı başlatır |
| Şemayı günceller |
| PostgreSQL'i başlatır |
| PostgreSQL'i durdurur |
| RAG index'ini oluşturur/günceller |
| Streamlit UI'ı başlatır |
| Benchmark çalıştırır (sonuçlar |
| Ortamı temizler |
🔧 Proje Yapısı
text2sql-mcp/
├── .env.example # Ortam değişkenleri şablonu
├── .github/workflows/ci.yml # GitHub Actions CI pipeline
├── README.md # Bu dosya
├── ARCHITECTURE.md # Mimari dokümanı
├── docker-compose.yml # PostgreSQL + Chinook DB
├── requirements.txt # Python bağımlılıkları
├── data/
│ ├── Chinook_PostgreSql.sql # Chinook veritabanı dump'ı (otomatik yüklenir)
│ ├── schema.yaml # Çıkarılan şema (otomatik oluşturulur)
│ ├── glossary.yaml # Chinook terimleri sözlüğü (RAG)
│ └── gold_queries.yaml # Soru-SQL örnek çiftleri (RAG)
├── mcp_server/
│ ├── server.py # MCP Protocol Server (3 tool)
│ └── validators.py # 5 katmanlı SQL validasyonu
├── scripts/
│ ├── setup.ps1 # PowerShell: Ortam kurulumu (WINDOWS)
│ ├── run_server.ps1 # PowerShell: Server başlatma (WINDOWS)
│ ├── teardown.ps1 # PowerShell: Ortam temizliği (WINDOWS)
│ ├── setup.sh # Bash: Ortam kurulumu (Linux/Mac/WSL)
│ ├── run_server.sh # Bash: Server başlatma (Linux/Mac/WSL)
│ ├── teardown.sh # Bash: Ortam temizliği (Linux/Mac/WSL)
│ ├── setup_db.sh # Docker init: llm_reader kullanıcısı
│ ├── extract_schema.py # Şema çıkarıcı
│ └── index_glossary.py # RAG index oluşturucu
├── tests/
│ ├── test_validators.py # Validasyon testleri (49 test)
│ ├── test_server.py # Server handler testleri (24 test)
│ ├── test_extract_schema.py # Schema extractor testleri (3 test)
│ ├── test_glossary_yaml.py # Glossary YAML testleri (15 test)
│ ├── test_gold_queries_yaml.py # Gold queries YAML testleri (40 test)
│ ├── test_embedder.py # Embedding wrapper testleri (16 test)
│ ├── test_indexer.py # ChromaDB indexer testleri (19 test)
│ └── test_retriever.py # Context retriever testleri (19 test)
├── rag/ # RAG sistemi (Faz 2)
│ ├── embedder.py # SentenceTransformers embedding wrapper
│ ├── indexer.py # ChromaDB index yöneticisi
│ └── retriever.py # MMR + threshold ile bağlam geri getirme
├── pipeline/ # NL2SQL pipeline (Faz 3+)
│ ├── orchestrator.py # 7 adımlı pipeline orkestratörü
│ ├── confidence.py # Güven skoru hesaplayıcı
│ └── formatter.py # Markdown response formatter
├── eval/ # Benchmark sistemi (Faz 5)
│ ├── run_benchmark.py # Benchmark runner (CLI + kütüphane)
│ ├── metrics.py # Metrik hesaplayıcı + rapor
│ ├── test_set.yaml # 25 test sorusu (5 kategori)
│ └── results/ # Benchmark sonuç JSON'ları (otomatik)
├── ui/ # Streamlit arayüzü (Bonus Faz)
│ ├── app.py # Ana giriş — multi-page navigation
│ └── pages/
│ ├── query.py # 🔍 Sorgu sayfası
│ ├── benchmark.py # 📊 Benchmark sayfası
│ └── schema.py # 🗄️ Şema sayfası🌐 Çevre Değişkenleri
.env.example dosyasını .env olarak kopyalayıp düzenleyin:
Değişken | Varsayılan | Zorunlu | Açıklama |
|
| ✅ | PostgreSQL sunucu adresi |
|
| ✅ | PostgreSQL portu |
|
| ✅ | Veritabanı adı |
|
| ✅ | Read-only kullanıcı |
|
| ✅ | Kullanıcı şifresi |
| — | ✅ | Google Gemini API anahtarı (pipeline için zorunlu) |
|
| ❌ | Sorgu zaman aşımı (saniye) |
|
| ❌ | Maksimum dönen satır sayısı |
|
| ❌ | LLM sorgu deneme sayısı |
|
| ❌ | Pipeline güven skoru eşiği |
|
| ❌ | ChromaDB kalıcı veri dizini (Faz 2) |
|
| ❌ | SentenceTransformers model adı (Faz 2) |
|
| ❌ | Log seviyesi |
GEMINI_API_KEY almak için: aistudio.google.com adresine gidin, ücretsiz API key oluşturun.
🔬 Test Durumu
✅ 277/277 test geçiyor — Validasyon, server handler, schema extractor, RAG (glossary, gold queries, embedder, indexer, retriever), Faz 3 pipeline/agent, Faz 5 benchmark ve Streamlit UI testleri.
Testler unittest.mock kullanır, gerçek PostgreSQL bağlantısı gerektirmez.
📅 Fazlar
Faz | Durum | İçerik |
Faz 0 | ✅ Tamamlandı | Proje iskeleti, MCP server, 5 katmanlı validasyon |
Faz 1 | ✅ Tamamlandı | Şema çıkarma, environment setup, 76/76 test |
Faz 2 | ✅ Tamamlandı | RAG sistemi: glossary (32 terim), gold queries (25 çift), ChromaDB index, MMR retriever, 179/179 test |
Faz 3 | ✅ Tamamlandı | NL2SQL pipeline + LLM entegrasyonu |
Faz 5 | ✅ Tamamlandı | Benchmark sistemi (25 test, metrik hesaplayıcı, CLI runner) |
Bonus | ✅ Tamamlandı | Streamlit UI (Sorgu + Benchmark + Şema sayfaları) |
Benchmark sonuçları: Henüz çalıştırılmayı bekliyor. Çalıştırmak için
python eval/run_benchmark.py(GEMINI_API_KEY + PostgreSQL gerekir). Sonuçlareval/results/altına JSON olarak kaydedilir ve UI'ın Benchmark sayfasından görselleştirilir.
🔐 Güvenlik Mimarisi
Katman | Açıklama |
L1 Syntax | sqlglot ile SQL parse + multi-statement tespiti |
L2 Statement | Sadece SELECT (ve UNION/INTERSECT/EXCEPT) izinli |
L3 Schema | Sorgudaki tablo/kolonlar schema.yaml ile karşılaştırılır |
L4 Injection | pg_sleep, lo_import, COPY, XP_ vs. pattern eşleştirme |
L5 Resource | LIMIT yoksa otomatik ekle, subquery sınırı |
Ek olarak: conn.set_session(readonly=True) + statement_timeout=30s + fetchmany(max_rows=1000)
🐳 Docker ile Çalıştırma
# Container'ı başlat
docker compose up -d
# Logları izle
docker compose logs -f
# Container'ı durdur
docker compose down
# Tamamen sıfırla (volume dahil)
docker compose down -v📦 CI/CD
GitHub Actions workflow'u (.github/workflows/ci.yml):
Python 3.11 kurulumu
pip install -r requirements.txt
pytest tests/ -v --tb=short
Lint check (ruff, optional)
📄 Lisans
MIT
This server cannot be installed
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Latest Blog Posts
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/YusuffEren/text2sql-mcp'
If you have feedback or need assistance with the MCP directory API, please join our Discord server