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: MCP PostgreSQL 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çıpGROQ_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.
React Frontend (Modern UI)
Tamamen yeniden inşa edilmiş, Linear/Vercel kalitesinde React 19 + Vite + Tailwind v4 arayüz:
# Frontend'i geliştirme modunda başlat
cd frontend
npm install # (ilk seferde, bağımlılıkları yükler)
npm run dev # http://localhost:5173# Production build (backend ile birlikte serve edilir)
cd frontend
npm run build
# Backend, frontend/dist/ klasörünü otomatik serve eder10 sayfa, karanlık-öncelikli tasarım sistemi ile:
Sayfa | Endpoint | İçerik |
⚡ Query |
| Hero sayfa — doğal dil girişi, pipeline progress animasyonu, typewriter efektli cevap, Gauge güven skoru, SQL CodeBlock, sonuç tablosu |
📊 Dashboard |
| KPI kartları (animasyonlu count-up), aylık gelir area chart, top artists, tür dağılımı donut |
🗄️ Schema |
| Sol liste + sağ detay, PK/FK rozetleri, bağlantılı navigasyon |
📈 Benchmark |
| %96 accuracy Gauge, zorluk/kategori bar grafikleri, self-correction highlight |
🔄 dbt |
| Layer gruplı model listesi, upstream/downstream DAG, run/test |
🔗 Lineage |
| Pipeline flow görseli, ETL çalıştırma, geçmiş |
📡 Streaming |
| Canlı metrikler (5sn polling), simülatör kontrolü |
☁️ Big Data |
| 5 Spark job kartı (RFM, forecast, market-basket) |
🔬 Research |
| Tablo profilleri grid |
⚙️ Settings |
| Health status, API/DB konfigürasyonu, hassas değer maskeleme |
Tüm sayfalarda skeleton loading, empty state, error state (retry butonlu) state'leri mevcut.
Streamlit UI (Legacy)
Eski Streamlit arayüzü hâlâ ui/ klasöründe mevcut:
.\venv\Scripts\streamlit run ui/app.pyTestleri Ç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 |
| — | ✅ | Groq/LLM 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 |
GROQ_API_KEY almak için: console.groq.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(GROQ_API_KEY + PostgreSQL gerekir). Sonuçlareval/results/altına JSON olarak kaydedilir.
🔐 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
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Servers
- -license-quality-maintenanceEnables secure read-only interactions with PostgreSQL databases through natural language. Provides database inspection, table listing, and SQL query execution with built-in security validation.
- Alicense-qualityAmaintenanceEnables secure read-only access to PostgreSQL databases, allowing users to list tables, query schemas, execute SELECT statements, and inspect table structures through natural language interactions.7274MIT
- FlicenseBqualityDmaintenanceEnables natural language interaction with PostgreSQL databases, converting questions to safe SQL queries and executing them with result validation.1
- AlicenseAqualityAmaintenanceEnables read-only interaction with PostgreSQL databases through natural language queries, supporting dynamic connections and secure query validation.31582MIT
Related MCP Connectors
Query PostgreSQL databases in plain English — LLM-generated, safety-validated SQL.
Analytical memory for AI agents: a real Postgres queried in plain English over MCP. One command.
Comprehensive PostgreSQL documentation and best practices, including ecosystem tools
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- 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