Text2SQL-MCP

Text2SQL-MCP

Converts natural language to safe SQL queries for PostgreSQL databases with read-only access and multi-layer security validation. Provides tools for running validated SELECT queries, retrieving schema, and sampling table data.

Category
Visit Server

README

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 garantisillm_reader kullanı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)

📋 Gereksinimler

Gereksinim Açıklama
Python 3.11+ python.org
Docker Desktop docker.com
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.ps1

Bu script şunları yapar:

  1. ✅ Python sanal ortamı (venv) oluşturur
  2. ✅ Bağımlılıkları yükler (pip install -r requirements.txt)
  3. .env dosyasını oluşturur (.env.example'dan kopyalar)
  4. ✅ Docker container'ını başlatır (PostgreSQL + Chinook DB otomatik yüklenir)
  5. data/schema.yaml şema dosyasını çıkarır
  6. ✅ Testleri çalıştırmaya hazır hale gelir

⚠️ ÖNEMLİ: Kurulumdan sonra .env dosyasını açıp GEMINI_API_KEY değ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
album 347 Müzik albümleri
artist 275 Sanatçılar
customer 59 Müşteriler
employee 8 Çalışanlar
genre 25 Müzik türleri
invoice 412 Faturalar
invoice_line 2240 Fatura satırları
media_type 5 Medya türleri
playlist 18 Çalma listeleri
playlist_track 8715 Çalma listesi-parça eşleşmesi
track 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 server

Server 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.py

UI üç 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 eval/results/ benchmark JSON'larını görselleştir — metrik kartları, Altair grafikleri, karşılaştırma modu.
🗄️ Şema Veritabanı şema keşfi — tablolar, kolonlar, PK/FK, index, satır sayısı, örnek veri.

Not: UI için GEMINI_API_KEY ve çalışan PostgreSQL bağlantısı gerekir (sidebar'da durum gösterilir).

Testleri Çalıştırma

.\venv\Scripts\pytest tests\ -v

Faydalı Komutlar

Komut Açıklama
.\scripts\setup.ps1 Tüm ortamı kurar
.\venv\Scripts\pytest tests\ -v Testleri çalıştırır
.\scripts\run_server.ps1 MCP server'ı başlatır
.\venv\Scripts\python scripts\extract_schema.py Şemayı günceller
docker compose up -d PostgreSQL'i başlatır
docker compose down PostgreSQL'i durdurur
make index RAG index'ini oluşturur/günceller
.\venv\Scripts\streamlit run ui/app.py Streamlit UI'ı başlatır
.\venv\Scripts\python eval/run_benchmark.py Benchmark çalıştırır (sonuçlar eval/results/)
.\scripts\teardown.ps1 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
POSTGRES_HOST localhost PostgreSQL sunucu adresi
POSTGRES_PORT 5432 PostgreSQL portu
POSTGRES_DB chinook Veritabanı adı
POSTGRES_USER llm_reader Read-only kullanıcı
POSTGRES_PASSWORD llm_reader_pass_123 Kullanıcı şifresi
GEMINI_API_KEY Google Gemini API anahtarı (pipeline için zorunlu)
QUERY_TIMEOUT_SEC 30 Sorgu zaman aşımı (saniye)
MAX_ROWS 1000 Maksimum dönen satır sayısı
MAX_RETRIES 3 LLM sorgu deneme sayısı
CONFIDENCE_THRESHOLD 60 Pipeline güven skoru eşiği
CHROMA_PERSIST_DIR ./chroma_data ChromaDB kalıcı veri dizini (Faz 2)
EMBEDDING_MODEL all-MiniLM-L6-v2 SentenceTransformers model adı (Faz 2)
LOG_LEVEL INFO 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çlar eval/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

Recommended Servers

playwright-mcp

playwright-mcp

A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.

Official
Featured
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.

Official
Featured
Local
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.

Official
Featured
Local
TypeScript
VeyraX MCP

VeyraX MCP

Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.

Official
Featured
Local
graphlit-mcp-server

graphlit-mcp-server

The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.

Official
Featured
TypeScript
Kagi MCP Server

Kagi MCP Server

An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.

Official
Featured
Python
E2B

E2B

Using MCP to run code via e2b.

Official
Featured
Neon Database

Neon Database

MCP server for interacting with Neon Management API and databases

Official
Featured
Exa Search

Exa Search

A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.

Official
Featured
Qdrant Server

Qdrant Server

This repository is an example of how to create a MCP server for Qdrant, a vector search engine.

Official
Featured