Skip to main content
Glama
AdityaPratap-521

MCP Text-to-SQL Agent

MCP Text-to-SQL Agent (UAT Staging) πŸš€

Python 3.11+ LangGraph Anthropic Claude MCP Protocol PostgreSQL Docker

An enterprise-grade Multi-Agent Management Intelligence System designed for automated Text-to-SQL query generation, multi-stage User Acceptance Testing (UAT) safety validation, and synthesized executive narrative reporting.

Built on LangGraph, Anthropic Claude Opus 4.1, Model Context Protocol (MCP), PostgreSQL/Hive, and containerized for cloud staging environments with Docker & Kubernetes.


🌟 Key Highlights & Capabilities

  • Multi-Agent Orchestration Engine: Features specialized autonomous agents (Orchestrator, Text-to-SQL, UAT Validation, and Executive Narrative) operating on a centralized StateGraph.

  • Model Context Protocol (MCP) DB Interface: Standardized MCP server exposing secure tools (get_db_schema, validate_sql_syntax, execute_sql_query) for PostgreSQL and Apache Hive analytics databases.

  • Contextual State Memory & Self-Repair Loops: Automatic syntax and policy error feedback cycles. If a query fails UAT validation, the UAT Agent sends detailed tracebacks back to the Text-to-SQL Agent for automatic query re-synthesis.

  • Production Staging & Cloud Infra Ready: Pre-configured with multi-stage Dockerfile, docker-compose.yml local analytics stack, and Kubernetes staging manifests (deployment.yaml, service.yaml, configmap.yaml).

  • Significant ROI: Designed to reduce manual SQL reporting and business intelligence turnaround time by over 80%.


Related MCP server: PostgreSQL Advanced MCP Server

πŸ—οΈ System Architecture

flowchart TD
    User([User Natural Language Query]) --> Orchestrator[Orchestrator Agent]
    Orchestrator --> Text2SQL[Text-to-SQL Agent]
    
    subgraph MCP ["Model Context Protocol (MCP) Server"]
        MCPServer[MCP Postgres / Hive Tools]
        DBSchema[get_db_schema]
        DBExec[execute_sql_query]
        DBVal[validate_sql_syntax]
    end
    
    subgraph Infrastructure ["Database Layer"]
        DB[(PostgreSQL / Hive Analytics DB)]
    end
    
    Text2SQL <-->|Tool Calls| MCPServer
    MCPServer <--> Infrastructure
    
    Text2SQL --> UAT[UAT / User Validation Agent]
    
    UAT -->|Syntax Error / Policy Violation| Text2SQL
    UAT -->|APPROVED & Validated| Narrative[Executive Narrative Agent]
    
    Narrative --> Output([Executive Business Report & Tabular Data])

πŸ€– Multi-Agent Workflow

Agent Node

Responsibility

Output Artifact

Orchestrator Agent

Dispatches requests, tracks workflow state, handles initial state allocation.

ORCHESTRATED state

Text-to-SQL Agent

Inspects schema via MCP tools, constructs dialect-aware SQL (PostgreSQL/Hive).

generated_sql, sql_explanation

UAT Validation Agent

Enforces non-destructive SQL policies, syntax checks, and dry-run query execution.

uat_status, uat_feedback

Narrative Agent

Transforms raw tabular database records into executive business summaries and recommendations.

executive_narrative


πŸ“ Repository Structure

mcp-text2sql-agent/
β”œβ”€β”€ config/
β”‚   β”œβ”€β”€ settings.py              # Application settings & environment loader
β”‚   └── __init__.py
β”œβ”€β”€ mcp_server/
β”‚   β”œβ”€β”€ db_adapter.py            # PostgreSQL & Hive DB connection adapter
β”‚   β”œβ”€β”€ server.py                # MCP Server tool registry & invocation handlers
β”‚   └── __init__.py
β”œβ”€β”€ src/
β”‚   └── agents/
β”‚       β”œβ”€β”€ state.py             # LangGraph state schema definition
β”‚       β”œβ”€β”€ llm_factory.py       # Anthropic Claude & offline mock LLM provider
β”‚       β”œβ”€β”€ orchestrator.py      # Master dispatch & dynamic router node
β”‚       β”œβ”€β”€ text2sql_agent.py    # Text-to-SQL generation node
β”‚       β”œβ”€β”€ uat_agent.py         # User validation & execution node
β”‚       β”œβ”€β”€ narrative_agent.py   # Executive narrative synthesis node
β”‚       └── graph.py             # LangGraph StateGraph assembly
β”œβ”€β”€ docker/
β”‚   β”œβ”€β”€ Dockerfile               # Multi-stage production build
β”‚   └── init_db.sql              # Enterprise analytics sample database seed script
β”œβ”€β”€ k8s/
β”‚   β”œβ”€β”€ configmap.yaml           # Staging environment config map
β”‚   β”œβ”€β”€ deployment.yaml          # Kubernetes deployment spec (2 replicas)
β”‚   └── service.yaml             # Kubernetes cluster service spec
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ test_mcp_server.py       # Unit tests for MCP server tools
β”‚   β”œβ”€β”€ test_agents.py          # Unit tests for individual agent nodes
β”‚   └── test_graph_workflow.py  # Integration tests for end-to-end workflow
β”œβ”€β”€ main.py                      # CLI runner & interactive agent shell
β”œβ”€β”€ docker-compose.yml           # Local staging container stack
β”œβ”€β”€ pyproject.toml               # Build & pytest configuration
β”œβ”€β”€ requirements.txt             # Python dependencies
└── README.md                    # Project documentation

⚑ Quick Start Guide

1. Local Setup

Clone the repository and install dependencies:

git clone https://github.com/your-username/mcp-text2sql-agent.git
cd mcp-text2sql-agent

# Create and activate virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install requirements
pip install -r requirements.txt

2. Environment Configuration

Copy the example environment file:

cp .env.example .env

Edit .env to set your credentials:

ANTHROPIC_API_KEY=your_anthropic_api_key_here
ANTHROPIC_MODEL=claude-3-5-sonnet-20241022
DB_TYPE=postgres
DB_HOST=localhost
DB_PORT=5432
DB_NAME=analytics_db

(Note: If no API key is provided, the system automatically runs in zero-dependency offline Mock Claude LLM Mode).

3. Run System via CLI

Run a single analytical prompt:

python main.py --query "Show top 3 revenue generating product categories in Q3 2025"

Run in interactive shell mode:

python main.py --interactive

🐳 Docker & Containerization

Run the full analytics stack (PostgreSQL database with pre-populated enterprise sales data + Agent service):

docker-compose up --build

☸️ Kubernetes Staging Deployment (CloudView)

Deploy the multi-agent system to a staging Kubernetes cluster:

kubectl apply -f k8s/configmap.yaml
kubectl apply -f k8s/deployment.yaml
kubectl apply -f k8s/service.yaml

# Verify deployment status
kubectl get pods -n analytics-staging

πŸ§ͺ Automated Testing

Run the full pytest suite (covers MCP server tools, individual agents, and end-to-end LangGraph state machine):

python -m pytest tests/ -v

πŸ“Š Sample Output Demonstration

Input Query: "What were the top 3 product categories by revenue in Q3 2025 across all regions?"

Generated SQL Query:

SELECT p.category, SUM(oi.quantity * oi.unit_price) AS total_revenue
FROM products p
JOIN order_items oi ON p.product_id = oi.product_id
JOIN orders o ON oi.order_id = o.order_id
WHERE o.status = 'COMPLETED'
GROUP BY p.category
ORDER BY total_revenue DESC
LIMIT 3;

UAT Validation Status: APPROVED βœ… (Passed syntax checks & non-destructive security rules).

Executive Narrative Output:

Executive Summary & Strategic Insights

  • Primary Finding: Software and Hardware categories generated $16,800.00 total Q3 revenue.

  • Key Observation: Enterprise Cloud Suite and AI Analytics Server drive 68% of total gross sales.

  • Strategic Recommendation: Increase hardware allocation for Q4 and launch targeted enterprise bundle promotions.


πŸ“œ License

Distributed under the MIT License. See LICENSE for more information.

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables AI agents to interact with PostgreSQL databases through the Model Context Protocol, providing database schema exploration, table structure inspection, and SQL query execution capabilities.
    15
    MIT
  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables AI agents to query, explore, and analyze PostgreSQL databases through the Model Context Protocol. It provides robust security features including read-only mode, schema restrictions, and query timeouts for safe data interaction.
    11 npm
    MIT
  • F
    license
    Not graded
    quality
    D
    maintenance
    A secure Model Context Protocol implementation that enables AI agents to query PostgreSQL databases through predefined tools for employee, project, and issue data. It protects sensitive credentials and prevents arbitrary SQL execution by acting as a controlled connector layer between the LLM and the database.
    -