Skip to main content
Glama
Proactive Data Agent MCP Server

Proactive Data Agent MCP Server

by KeriaGuma
README.md
# Proactive Data Agent

**Enterprise Proactive Data Agent with Business Ontology, Hierarchical Retrieval, Verifiable SQL AST/RLS Guardrails, and Drop-in MCP Firewall**

[English](README.md) | [中文说明](README_zh.md)

[![Python 3.12](https://img.shields.io/badge/Python-3.12-3776AB?logo=python&logoColor=white)](pyproject.toml)
[![FastAPI](https://img.shields.io/badge/FastAPI-SSE%20%2B%20MCP-009688?logo=fastapi&logoColor=white)](src/chatbi/api/app.py)
[![Tests](https://img.shields.io/badge/Tests-70%20Offline%20%2B%20Red--Team-2563eb)](tests/)
[![Benchmark](https://img.shields.io/badge/Spider%202.0--Lite-66.7%25%20(90%2F135)-16a34a)](docs/EVALUATION.md)
[![License: MIT](https://img.shields.io/badge/License-MIT-slate.svg)](LICENSE)

> **Why another Data Agent?** Most NL2SQL prototypes fail silently in production: SQL runs without error while **doubling revenue via 1:N fan-out joins (Chasm Trap)**, prompts blow up on hundreds of uncurated tables, or mid-turn model switching poisons context with anchoring bias. **Proactive Data Agent** treats analytics reliability as a **deterministic systems engineering problem**—combining a `sqlglot` AST/RLS firewall (usable drop-in via **MCP**), a 4-layer 432-table retriever, a two-stage zero-token proactive anomaly sentinel, and leakage-free evaluations across **612 Olist ablations + 135/135 Spider 2.0-Lite real SQLite tasks**.

---

## Live Workbench Preview (Runs in 30s with Zero API Keys)

![Proactive Data Agent Workbench](docs/assets/workbench_demo.png)

*Built-in zero-LLM demo mode: two-stage proactive anomaly scan, Black Friday event-calendar denoising, 2nd-order orthogonal root-cause breakdown (`SP → cama_mesa_banho`), AST multi-tenant RLS switching, Trace waterfall, and Feishu interactive card preview.*

---

## Highlights & Benchmark Results

![Spider 2.0-Lite Benchmark](docs/assets/spider2_benchmark.svg)

- **432-Table Production Hierarchical Retrieval (`-96.8%` DDL tokens, `95.8%` full-set recall)**: Combines **L0 RBAC pre-filtering** (blocking unauthorized FK bridging) → **L1 domain routing** → **L2 BM25 + dense embedding + `gte-rerank-v2` dynamic score cutoff** → **L3 verified implicit FK closure + wide-table column pruning** → **L4 runtime `inspect_schema` fallback**. Compresses `27,255` DDL tokens down to **`872` tokens (`-96.8%`)** while lifting full-table-set recall on 30 real Spider 2.0-Lite databases from `66.7%` to **`95.8%`** (`98.7%` single-table, `100%` @ top-20).
- **Spider 2.0-Lite Local-135 Full Pass@1 (`66.7%` Official EX / `99.3%` Executable)**: Evaluated on all 135 local SQLite tasks (30 databases, 432 tables, 328 official multi-equivalent gold CSVs, zero manual metric leakage, single-path 8-step cap). Enabling streaming thinking (`budget=2048`) lifts `qwen4-max` from `57.0%` (`77/135`) to **`66.7%` (`90/135`, `+9.7 pp`, Exact McNemar $p=0.0072$)** and Strict EX from `45.9%` to **`57.8%` (`+11.9 pp`, $p=0.0037$)** at only **`+3.9%`** cost (`¥6.92 → ¥7.19`, `¥0.053/task`).
- **Verifiable `sqlglot` AST Guardrails & Drop-in MCP SQL Firewall**: Statically intercepts 1:N Chasm Trap fan-out across CTEs/subqueries, injects zero-copy tenant Row-Level Security (`__rls_*` CTE rewriting with same-name CTE shadowing defense), and blocks PII leaks (`SELECT *`, DuckDB struct row projections, `COLUMNS()`). Exposed as a **JSON-RPC 2.0 MCP Server** (`validate_sql`, `execute_readonly_sql`, `query_semantic_metric`, `run_proactive_scan`) with `observe / standard / strict` rollout modes.
- **Production Reliability & Digital Employee Ops**: Per-step SQLite WAL checkpointing (`POST /api/v1/chat/resume`), idempotent query tools, SSE client-disconnect upstream cancellation, OpenTelemetry-compatible Trace spans + Prometheus `/api/v1/metrics`, zero-LLM parameterized Skill replay, and bidirectional Feishu interactive card bot.

---

## Four Counter-Intuitive Engineering Findings

![Controlled Ablation Findings](docs/assets/ablation_findings.svg)

| Finding | Controlled Evidence | Engineering Takeaway |
| :--- | :--- | :--- |
| **1. Mid-turn model switching backfires (`37.5%`)** | Escalating `flash → max` mid-turn dropped accuracy to `37.5%` (vs `87.5%` single `qwen-plus`) due to silent semantic errors, **anchoring bias** on dirty intermediate outputs, and KV cache invalidation. | Use **task-level 3-layer routing + Clean-Slate full-turn retry** (`+15.8 pp`, `-38.5%` latency, `-25%` cost on `medium-19`). |
| **2. Blindly Pushing offline semantics hurts strong models (`-14.3 pp`)** | Pre-injecting offline Verifiable RSI semantics (Push) dropped `qwen4-max` from `71.4%` (`15/21`) to `57.1%` (`12/21`) via `+32.5%` context tax and premature stopping. | Switch to **progressive Pull** (`~50`-token index + `lookup_verified_semantics` tool): `-20.1%` per-step load, `0` degradation. |
| **3. Autonomous agents beat fixed workflows on 2nd-order RCA (`86.7%` vs `0%`)** | On Exp-2 (48 tasks), fixed drilldown achieved `100%` 1st-order recall but **`0%`** 2nd-order cross-dimension recall; hypothesis-driven `InvestigationRuntime` hit **`86.7%` dev / `62.5%` holdout** with fewer DB queries (`6.10` vs `6.60`). | Reserve autonomous loops for tasks where deterministic workflows have a proven capability gap; route simple KPIs to the deterministic Fast Path. |
| **4. Static Prefix Caching yields `94.4%–96.0%` KV Cache hit** | Pinning static schema/policy prefixes and deferring dynamic RAG (`cached_planned`) achieved **`100% (48/48)`** dev clear accuracy (`93.3%` holdout) and cut effective billed tokens by `58.1%–74.9%`. | Never mutate prompt prefixes turn-by-turn; design retrieval injection around prefix-cache preservation. |

---

## Drop-in MCP SQL Firewall (Works with Cursor / Claude / LangGraph)

Reuse the AST Chasm-Trap checker, zero-copy tenant RLS, and PII column RBAC in any external MCP client **without surrendering your agent's prompt loop**:

```bash
# 1. Start the server (exposes JSON-RPC 2.0 MCP at POST /api/v1/mcp)
CHATBI_DATABASE=var/olist.duckdb .venv/bin/uvicorn --factory chatbi.api.app:create_app --host 127.0.0.1 --port 8010

# 2. Dry-run SQL pre-flight validation via MCP `validate_sql`
curl -s http://127.0.0.1:8010/api/v1/mcp \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0", "id": 1, "method": "tools/call",
    "params": {
      "name": "validate_sql",
      "arguments": {
        "sql": "SELECT SUM(i.price) FROM orders o JOIN order_items i ON o.order_id = i.order_id JOIN order_payments p ON o.order_id = p.order_id",
        "guardrail_mode": "strict"
      }
    }
  }'
```

Exposed MCP tools: `validate_sql` (dry-run AST + RLS/RBAC diagnostics with line/scope rewrite hints), `execute_readonly_sql`, `query_semantic_metric`, `search_business_knowledge`, and `run_proactive_scan` (also supports stdio transport via `ChatBIMCPServer.serve_stdio()`).

---

## System Architecture

```mermaid
flowchart TD
    subgraph Proactive["L1 Resident Proactive Sentinel (0 LLM Tokens)"]
        Cron["ProactiveScheduler"] --> Gate["Watermark & Dedup Gate"]
        Gate --> Cal["4-Layer Business Ontology & Event Calendar"]
        Cal -->|True Anomaly| OntRCA["Symmetric 2-Factor + Orthogonal 2nd-Order RCA"]
        OntRCA --> Feishu["Feishu Bidirectional Cards (HMAC-SHA256)"]
    end

    subgraph Interactive["L2 Adaptive Dual-Speed Orchestration (FastAPI SSE)"]
        User["User Query / Feishu Thread / External MCP Client"] --> Auth["scrypt Auth · HMAC Session · Tenant Scope"]
        Auth --> Router["3-Layer Task Router & Ambiguity Gate"]
        Router -->|Deterministic KPI| Fast["Fast Path: Semantic Compiler / Controlled ReAct"]
        Router -->|Complex Anomaly| Deep["Deep Path: Hypothesis-Driven InvestigationRuntime"]
        RAG["4-Layer Hierarchical RAG (RBAC → Domain → Rerank → FK Closure)"] --> Fast & Deep
    end

    subgraph Engine["Verifiable Execution & AST Firewall"]
        Fast & Deep & OntRCA --> Guard["sqlglot AST Guardrails: 1:N Fan-Out · Status · Output Contract"]
        Guard --> RLS["Zero-Copy AST Row-Level Security (RLS) + Column RBAC"]
        RLS --> DB[("DuckDB / PostgreSQL Read-Only + SQLite WAL Checkpoints")]
    end
```

---

## Benchmark Summary

> Strict anti-leakage architecture: `src/chatbi` is physically isolated from `src/chatbi_eval` (enforced by [`tests/test_architecture_isolation.py`](tests/test_architecture_isolation.py)). Development uses `dev` only; `test.jsonl` (30 tasks) and `holdout.jsonl` (16 tasks) were unsealed once after code freeze.

| Benchmark & Arm | Primary Metric | Strict / Delta | Efficiency & Cost |
| :--- | :---: | :---: | :--- |
| **Spider 2.0-Lite 432-Table Retrieval** (30 DBs) | **95.8%** Full-Set / **98.7%** Single-Table | **+29.1 pp** vs Flat Top-10 | `27,255 → 872` tokens (**-96.8%**) |
| **Spider 2.0-Lite Local-135** (`qwen4-max`, Thinking OFF) | `57.0%` (`77/135`) Official EX | `45.9%` (`62/135`) Strict EX | `5.13` steps · `17.81s` · `¥6.92` |
| **Spider 2.0-Lite Local-135** (`qwen4-max`, Streaming Thinking) | **`66.7%` (`90/135`) Official EX** | **`57.8%` (`78/135`) Strict** (**+9.7 pp**, $p=0.0072$) | **`4.33` steps** · `23.18s` · `¥7.19` (+3.9%) · `99.3%` exec |
| **Olist Clear `dev` / `test`** (`cached_planned` / `hybrid`) | **`100% (48/48)`** / **`93.3% (28/30)`** | KV Cache hit **94.4%–96.0%** | `-33.1%` raw / `-74.9%` billed tokens |
| **Olist Ambiguous `dev` / `test`** (`adaptive_agent_hybrid`) | **`31.3%`** / **`36.7%`** | **+20.8 pp** ($p=0.00195$) / **+16.7 pp** | `-28.7%` to `-30.2%` tokens |
| **Olist Exp-2 2nd-Order RCA** (`autonomous` vs `fixed_drilldown`) | **`86.7%` dev / `62.5%` holdout** | vs **`0.0%`** fixed drilldown | `100%` faithfulness · `6.10` DB queries |
| **Olist `medium-19` Cross-Model Fix** (`qwen-plus`) | `42.1% →` **`57.9%`** | **+15.8 pp**, 0 timeouts | `-38.5%` latency · `-25.0%` cost |

Full breakdowns, error taxonomy, and statistical tests: [`docs/EVALUATION.md`](docs/EVALUATION.md) · Design trade-offs: [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md).

---

## 30-Second Zero-Dependency Quickstart (No API Key Required)

```bash
# 1. Create Python 3.12 virtualenv and install
python3.12 -m venv .venv
.venv/bin/pip install -e ".[test]"

# 2. Run all 70 offline unit, architectural isolation, and AST red-team tests
.venv/bin/pytest -q

# 3. Seed the high-fidelity demo DuckDB warehouse in 1 second
.venv/bin/python scripts/seed_demo.py --output var/olist.duckdb --overwrite

# 4. Launch the Web Workbench (zero-LLM proactive scan, Feishu card preview, AST RLS)
CHATBI_DATABASE=var/olist.duckdb .venv/bin/uvicorn --factory chatbi.api.app:create_app --host 127.0.0.1 --port 8010
```

Open `http://127.0.0.1:8010` to trigger proactive anomaly scanning, inspect 2nd-order root causes (`SP → cama_mesa_banho`), test AST tenant RLS isolation, and preview Feishu cards. Copy `.env.example` to `.env` to enable live streaming NL2SQL & deep research with any OpenAI-compatible LLM endpoint.

---

## Repository Structure

```text
├── assets/
│   ├── knowledge/                  # Domain operating manuals & region mappings
│   └── semantics/                  # Metric contracts, FK graph, Business Ontology & model_catalog.yaml
├── docs/
│   ├── assets/                     # Workbench screenshot & benchmark SVGs
│   ├── ARCHITECTURE.md             # System architecture & engineering trade-offs
│   └── EVALUATION.md               # 612-case Olist & 135/135 Spider 2.0-Lite evaluations
├── evaluation/
│   ├── frozen/v1/                  # Frozen QA benchmark (dev 48 / test 30) + SHA-256 manifest
│   ├── investigation/v2/           # Frozen anomaly RCA benchmark (dev 32 / holdout 16)
│   └── results/                    # Archived experiment JSONs (routing, Spider 2.0-Lite, RSI)
├── scripts/                        # Demo seeder & reproducible benchmark runners
├── src/
│   ├── chatbi/                     # Core engine (strictly isolated from eval package)
│   │   ├── api/                    # FastAPI SSE, WAL Resume, /metrics, /mcp, scrypt + HMAC auth
│   │   ├── context/                # Hybrid BM25 + dense vector + RRF + Rerank + FK closure
│   │   ├── engine/                 # DuckDB/PG executor, AST RLS, Column RBAC, SQLite WAL
│   │   ├── guardrails/             # Semantic compiler, 3-tier sqlglot AST firewall, Sanity Gate
│   │   ├── mcp_server.py           # JSON-RPC 2.0 MCP Server (HTTP + stdio)
│   │   ├── model_router.py         # Multi-model catalog & 3-layer task-level router
│   │   ├── notifications/          # Feishu bidirectional interactive cards & WebSocket bot
│   │   ├── ontology/               # 4-layer Business Ontology & Verifiable RSI bootstrapper
│   │   ├── orchestration/          # Controllable ReAct, Ambiguity Gate, InvestigationRuntime, Skills
│   │   └── proactive/              # Resident Watchdog, Subspace Spotlight & deep research
│   └── chatbi_eval/                # Subprocess-isolated evaluator & statistical testing
└── tests/                          # 70 offline unit, isolation & AST adversarial tests
```

## License

Released under the [MIT License](LICENSE).