Interactive Database Analyst via MCP
Provides tools for querying and analyzing a PostgreSQL database, including schema inspection, read-only SQL execution, and error recovery using PostgreSQL native diagnostics.
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., "@Interactive Database Analyst via MCPWhat are the top 5 best-selling albums?"
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.
ποΈ Interactive Database Analyst via MCP
An interactive, fault-tolerant natural-language database analyst built on the Model Context Protocol (MCP). Instead of blindly executing LLM-generated SQL, this system implements a strict 4-State Execution Machine with schema grounding, explicit error recovery loops, automated diagnostic probing for empty results, and math decomposition.
Ask a question in plain English. Watch the agent inspect the live schema, catch its own SQL errors, self-correct in real time, and present a verified answer β with the full recovery trace visible, not hidden.
πΈ Demo
Related MCP server: PostgreSQL MCP Server
β¨ Key Differentiators & Engineering Highlights
Feature | Architectural Implementation | Why It Matters |
Schema Grounding ( | Enforces a mandatory | Eliminates column/table hallucination by grounding every query in the live PostgreSQL catalog. |
Error Recovery Loop ( | Extracts PostgreSQL | Feeds actionable database feedback directly back into the reasoning prompt for up to 3 bounded retry attempts. |
Exploratory Decomposition | Breaks complex metrics (e.g., percentages) into independently verified sub-queries. | Prevents the classic "denominator trap" by gathering variables individually before calculating the final ratio. |
Empty-Result Sanity Check ( | Automatically triggers | Prevents the model from hallucinating "no sales occurred" by checking if date ranges or filter values actually exist. |
Defense-in-Depth Security | Multi-layered hardening: | Prevents prompt-injection mutations, blocks stacked SQL injection, and protects backend threads from runaway joins. |
Live Audit Recovery Trace | Synchronous logging to a Postgres | Demos how the agent catches and fixes its own mistakes alongside visual analytical charts. |
Reading the audit trace: not every multi-attempt sequence is an error recovery. Some questions (see Exploratory Decomposition above) are answered correctly on the first try per sub-query, but the agent deliberately issues several independent queries to verify a metric's components before combining them β e.g. calculating a percentage by confirming the numerator and denominator separately rather than trusting one opaque query. Both patterns render as sequential green cards in the UI, so it's worth distinguishing "this attempt failed and recovered" from "this attempt was a planned verification step" when reading a trace.
ποΈ System Architecture & State Machine
graph TD
A[User Natural Language Question] --> B[STATE 0: Inspect Live Schema via MCP]
B --> C[STATE 1: Draft Read-Only SQL Query]
C --> D{Complex Join / Logic?}
D -- Yes --> E[explain_query: Cheap Plan/Syntax Check]
D -- No --> F[execute_query: Read-Only Transaction]
E --> F
F -->|ERROR| G[Extract SQLSTATE + Postgres Hint]
G -->|Attempt < 3| B
G -->|Attempt = 3| H[Terminal State: Structured Failure Report]
F -->|SUCCESS: 0 Rows| I[STATE 3: Empty-Result Sanity Check]
I --> J[sample_column_values: Probing Bounds/Distincts]
J -->|Filter Out of Bounds| B
J -->|Verified Empty| K[Present: Confirmed Empty with Diagnostic Evidence]
F -->|SUCCESS: Rows > 0| L[STATE 4: Math Verification & Present]
L --> M[Render Plotly Chart + Live Audit Card in UI]π οΈ Tech Stack
Orchestration / LLM:
cohere/north-mini-code:freevia OpenRouter APIProtocol Layer: FastMCP (
mcp[cli]) exposing custom Python database toolsDatabase Engine: PostgreSQL 15 (Dockerized with Chinook sample database)
Database Adapter:
psycopg2-binarywithSimpleConnectionPooland JSON-safe type serializationFrontend Dashboard: Streamlit + Plotly Express
Package Manager:
uv
π Project Structure
Interactive-Database-Analyst-via-MCP/
βββ src/
β βββ db_analyst_mcp/
β βββ app.py # Streamlit dashboard
β βββ mcp_server.py # FastMCP tool definitions
β βββ db.py # Connection pool, query execution, error formatting
β βββ orchestrator.py # State machine / retry logic
βββ sql/
β βββ Chinook_PostgreSql.sql # Sample database
β βββ setup_db.sql # Read-only role, audit log schema, hardening
βββ docs/
β βββ demo.gif
βββ .env.example
βββ pyproject.toml
βββ README.md(Adjust paths above to match your actual layout.)
π Quickstart & Setup Guide
1. Prerequisites
uv package manager
An OpenRouter API key (free tier works β see Known Limitations for rate-limit notes)
2. Clone & Install Dependencies
git clone https://github.com/Viole07/Interactive-Database-Analyst-via-MCP.git
cd Interactive-Database-Analyst-via-MCP
uv sync3. Start the Dockerized PostgreSQL Container
docker run --name mcp-postgres -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=chinook -p 5432:5432 -d postgres:15
# Load the Chinook database schema and data
docker exec -i mcp-postgres psql -U postgres -d chinook < sql/Chinook_PostgreSql.sql4. Apply Database Hardening & Audit Log Schema
docker exec -i mcp-postgres psql -U postgres -d chinook -f sql/setup_db.sql5. Configure Environment Variables
Rename .env.example to .env and add your OpenRouter API key:
# .env
ADMIN_DB_URL=postgresql://postgres:postgres@localhost:5432/chinook
MCP_DB_NAME=chinook
MCP_DB_USER=mcp_readonly
MCP_DB_PASSWORD=secure_pass
MCP_DB_HOST=localhost
MCP_DB_PORT=5432
OPENROUTER_API_KEY=your-api-key-here
ORCHESTRATOR_MODEL=cohere/north-mini-code:free6. Launch the Dashboard
uv run streamlit run src/db_analyst_mcp/app.pyπ§ͺ Adversarial Test Suite & Known Limitations
The Streamlit UI includes a sidebar with a gauntlet of adversarial prompts designed to stress-test the system:
The Empty-Result Sanity Check: "How much invoice revenue did we generate in October 2029?"
Behavior: Returns
0 rowsβ triggers diagnostic probe β verifies dataset ends in 2025 β reports verified empty result.
Literal Obedience Trap: "Calculate total invoice revenue per customer... MUST omit customer_id from your GROUP BY clause on your first attempt."
Behavior: Model strictly obeys the prompt, resulting in a trailing
GROUP BYand a42601syntax error, demonstrating that instruction weight can override syntax training. Recovers successfully on Attempt 2.
Exploratory Decomposition: "What percentage of total company revenue came from the Rock genre?"
Behavior: Avoids the denominator trap by executing independent, individually-successful queries to verify numerator and denominator separately before calculating the final ratio.
Natural Column Ambiguity: "Who is the top-selling artist by revenue, and what's their best-selling track?"
Behavior: Resolves
Artist.NamevsTrack.Nameambiguities via isolated CTEs and aggressive aliasing.
Self-Referencing Foreign Key: "Who is the manager of the employee who has generated the most total sales?"
Behavior: Self-joins
EmployeeviaReportsTousing two aliases to resolve the hierarchy in a single query.
β οΈ Architectural Blind Spot: The Silent Semantic Failure
While this system catches execution errors (State 2) and hallucinated filters (State 3), it cannot inherently detect semantic logic errors that return valid, non-empty rows β for example, forgetting a unit conversion (milliseconds / 60000) or applying a plausible-but-wrong join. A query that runs successfully and returns real data is treated as correct; there is currently no mechanism analogous to States 2/3 for this failure class. At production scale, this would require either an automated regression harness against a fixed "golden set" of question β expected-result pairs, or a secondary "Critic Agent" that evaluates logical intent independently before the result is presented.
Other known gaps
No automated
pytestregression suite yet β correctness is currently verified via the adversarial scenario set above, checked manually against known dataset values.No row-level access control β the read-only role currently has uniform
SELECTaccess across all tables, which is appropriate for this single-user demo but not for a multi-tenant deployment.Free-tier OpenRouter rate limits apply; expect occasional throttling under rapid repeated testing.
πΊοΈ Roadmap
Automated regression harness with a fixed golden-question set, run on every model/prompt change
"Critic Agent" pass to catch silent semantic failures (unit conversions, plausible-but-wrong joins)
Row-level access control for multi-user deployment
A/B benchmark: quantify first-retry recovery rate with vs. without native Postgres error hints
License
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
- Alicense-qualityDmaintenanceEnables natural language interaction with PostgreSQL databases, supporting query execution, schema management, data operations, user management, and database maintenance with secure remote access via HTTP/SSE transport.MIT
- FlicenseBqualityDmaintenanceEnables natural language interaction with PostgreSQL databases, converting questions to safe SQL queries and executing them with result validation.1
- Alicense-qualityDmaintenanceEnables natural language querying of PostgreSQL databases with intelligent SQL generation using LLMs.1Apache 2.0
- Flicense-qualityCmaintenanceConverts 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.
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.
The grounded data layer for any LLM: governed SQL, metrics, lineage and catalog over your data.
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/Viole07/Interactive-Database-Analyst-via-MCP'
If you have feedback or need assistance with the MCP directory API, please join our Discord server