Skip to main content
Glama
VoltPilot MCP Server

VoltPilot MCP Server

README.md
<div align="center">

# ⚡ VoltPilot

### Physics-Grounded AI Copilot & MCP Infrastructure for New Power Systems
**面向新型电力系统的物理可信配电网 AI 决策工作台与标准 MCP 底座**

[![Python 3.10+](https://img.shields.io/badge/Python-3.10%2B-3776AB?logo=python&logoColor=white)](pyproject.toml)
[![OpenDSS Engine](https://img.shields.io/badge/Physics-OpenDSS-0f766e)](voltpilot/engine.py)
[![MCP 2.x Native](https://img.shields.io/badge/Protocol-MCP%20Native-6d28d9)](voltpilot/mcp_server.py)
[![CN Standards](https://img.shields.io/badge/Standards-DL%2FT%202041--2025%20%7C%20GB%2FT%2012325%20%7C%20ANSI%20C84.1-dc2626)](voltpilot/standards_data/)
[![AI Evals](https://img.shields.io/badge/Live%20Eval%20(DeepSeek%20V4.1f)-16.7%25%20%E2%86%92%2091.7%25%20%7C%20100%25%20Grade%20%26%20Guardrails-16a34a)](evals/deepseek_flash_compare_v1.json)
[![License: MIT](https://img.shields.io/badge/License-MIT-f59e0b.svg)](LICENSE)

[**🇨🇳 阅读完整中文介绍页 (README_zh.md)**](README_zh.md) · [**📋 Product Requirements (PRD)**](docs/PRD.md) · [**🧪 24-Case AI Eval Suite**](evals/cases_v1.jsonl) · [**📄 Sample Audit Report**](docs/assets/sample_audit_report_zh.md)

</div>

---

## 1. The Mission: Solving the "Physics Hallucination" Bottleneck in Energy AI

Under global decarbonization and China's **New Power System (新型电力系统)** transformation, rapid rooftop PV and EV charging growth has turned passive 10 kV radial feeders into bidirectional active distribution networks—creating severe midday overvoltage, substation reverse overloading, and phase unbalance.

Meanwhile, **China's landmark revised standard `DL/T 2041-2025`** (*Guidelines for Hosting Capacity Assessment of Distributed Generation*, effective **June 2026**) officially replaces the legacy rigid 80% reverse-loading freeze (`DL/T 2041-2019`) with **dynamic Red / Yellow / Green flexible zoning** unlocked via OLTC regulation, smart inverter Volt-Var control, and distributed BESS.

Yet bringing Large Language Models into safety-critical grid engineering faces one fatal obstacle: **LLMs hallucinate physics.** When asked directly about a distribution feeder, general models routinely invent bus names, mix up Chinese `±7%` and US `±5%` limits, or fabricate hosting approvals even when power flow fails to converge.

> **VoltPilot's Core Iron Rule — _No Simulation, No Issuance_ (无仿真证据,禁止签发)**  
> VoltPilot bridges LLM intelligence with deterministic **OpenDSS** power-flow physics, **China-native & US grid compliance rules**, **What-If governance comparison**, and an **immutable `run_id` evidence ledger**—turning conversational AI from an unreliable chatbot into a **verifiable, traceable power-engineering copilot**.

---

## 2. Why VoltPilot Stands Out (China-Native × Global-Standard Differentiation)

While existing power-system MCP repositories focus on headless CLI wrappers and North American defaults, **VoltPilot** is architected end-to-end as an **industry-grade AI product for real distribution planning and DER interconnection**:

| Dimension | Headless OpenDSS MCP Wrappers | **⚡ VoltPilot** |
| :--- | :---: | :--- |
| **China Grid Policy & Standards** | US ANSI only / None | **China-Native + Global Dual-Mode YAML Engine**: `DL/T 2041-2025` (flexible Red/Yellow/Green), legacy `DL/T 2041-2019` (80% hard cap for policy delta analysis), `GB/T 12325` (±7%), `GB/T 15543` (exact symmetrical-component negative-sequence unbalance 2%/4%), and `US ANSI C84.1` (±5%) |
| **Built-in Benchmark Feeders** | US IEEE feeders only | **Chinese 50 Hz 10 kV Rural/Suburban Feeder (`cn_10kv_demo`)** using realistic `YJV22-3×150` / `LGJ-120` / `LGJ-70` conductor models + **IEEE 13 / 34 / 123** |
| **Decision-Ready Governance** | Raw snapshot voltages only | **Automated What-If Mitigation Matrix**: side-by-side comparison of **OLTC Tap**, **Inverter Volt-Var**, and **BESS Shaving**, quantifying `RED → GREEN` rescue & loss tradeoffs |
| **Safety & Anti-Hallucination** | Prompt-only / None | **Hard Code-Level Guardrails**: deterministic interception of `INVALID_BUS`, `PHASE_MISMATCH`, `NON_CONVERGED`, and unverified reports (`NO_SIMULATION_EVIDENCE` / `INVALID_RUN_ID`) |
| **Product Experience (Dual-Mode)** | CLI / JSON only | **Zero-Key Streamlit Workbench** (instant GUI simulation, charts & audit export without any API key) **+ Optional OpenAI-Compatible AI Copilot + Standard MCP Server** |
| **Quantifiable AI Quality** | None | **24-Case Stratified Eval Suite (`L1–L4`)**, including 6 adversarial hallucination traps + Bare LLM vs. VoltPilot-Grounded benchmark runner |

---

## 3. China-Characteristic Spotlight: Quantifying the `DL/T 2041-2019 → 2025` Policy Shift

One signature capability of VoltPilot is **live, physics-backed policy comparison** on a realistic Chinese 10 kV feeder (`cn_10kv_demo`, 5 MVA substation bay, 50 Hz):

- **Scenario**: Inject **5,250 kW PV** at mid-feeder bus `b3` under midday light load (`load_scale = 0.5`).
- **Deterministic OpenDSS Physics**: Terminal voltages stay completely compliant (`Vmax = 1.0489 p.u. < 1.07 p.u.`), while substation reverse loading reaches **`81.21%`**.
- **Instant Policy Contrast**:
  - Under legacy **`cn_dlt2041_2019`** (80% rigid cap) → **🔴 RED** (*Interconnection frozen*).
  - Under new **`cn_dlt2041_2025`** (60%–85% flexible unlock band) → **🟡 YELLOW** (*Allowed to connect with BESS / flexible control*).

VoltPilot turns abstract national energy policy into transparent, reproducible, bus-level engineering decisions.

---

## 4. Real OpenDSS Showcase: Rescuing a Red-Zone Feeder Back to Green

On `cn_10kv_demo` (tail bus `b8`, **2,600 kW PV**, midday `load_scale = 0.7`, `cn_dlt2041_2025`), voltage rises to **1.0711 p.u.**, breaching China's `GB/T 12325` `1.07 p.u.` ceiling (**🔴 RED**). One click on `compare_mitigations` evaluates all three engineering remedies on the identical physical snapshot:

| Rank | Strategy | Grade Transition | Voltage Range (p.u.) | Reverse Loading | Active Losses | Physical & Economic Tradeoff |
| :-: | :--- | :---: | :---: | ---: | ---: | :--- |
| Baseline | Unmitigated `pv_2600kW@b8` | **🔴 RED** (`overvoltage`) | `1.0165 – 1.0711` | `20.4%` | `139.4 kW` | Exceeds `GB/T 12325` `+7%` limit |
| **#1** | **Distributed BESS (`910 kW / 1820 kWh`)** | `RED → GREEN` 🟢 | `1.0145 – 1.0536` | **`9.0%`** | **`76.2 kW`** | Cuts voltage rise, reverse flow & losses (−45%) simultaneously; pre-wired for v1.0 provincial tariff IRR plugin |
| **#2** | **Substation OLTC Tap (`-4 V` setpoint)** | `RED → GREEN` 🟢 | `0.9912 – 1.0475` | `20.4%` | `145.9 kW` | Zero new hardware CAPEX, but cannot reduce substation reverse active power |
| **#3** | **Inverter Volt-Var (`-858 kvar`)** | `RED → GREEN` 🟢 | `1.0070 – 1.0414` | `19.6%` | `185.3 kW` | Leverages existing inverter reactive headroom (`pf ≥ 0.90`), at the cost of +33% copper losses |

<p align="center">
  <img src="docs/assets/demo_voltage_profile.png" alt="Feeder Voltage Profile Rescue" width="90%" />
</p>
<p align="center">
  <img src="docs/assets/demo_mitigation_compare.png" alt="What-If Mitigation Comparison" width="95%" />
</p>
<p align="center">
  <img src="docs/assets/demo_hosting_curve.png" alt="DER Hosting Capacity Curve" width="90%" />
</p>

### 24-Hour QSTS Time-Series & China Provincial BESS Bankability (New in `v0.2`)
- **24h QSTS (`run_qsts_24h`)**: On `cn_10kv_demo` @ `b8` (`2,800 kW` clear-sky PV + `600 kW` evening EV charging), unmitigated operation hits **4 RED overvoltage hours** (`1.0777 p.u.`, `1,557.3 kWh` daily losses). Coordinated 24h BESS (`1,100 kW / 2,200 kWh`, peak-aware midday charge + evening peak discharge) cuts RED hours **4h → 1h** and slashes daily losses by **17.5%** (`1,284.7 kWh`).
- **Provincial BESS Economics (`estimate_bess_economics`)**: Linking the `910 kW / 1,820 kWh` BESS from the physical governance showcase (`1.0 CNY/Wh` turnkey EPC, `250 kW` monthly demand shave) across 4 Chinese 10 kV two-part TOU tariffs:

| Province (10 kV Two-Part TOU) | CAPEX (10k CNY) | Annual Net Cashflow (10k CNY/yr) | Static Payback (yrs) | 10-Year Project IRR |
| :--- | ---: | ---: | ---: | ---: |
| **Zhejiang (`zhejiang_10kv`)** | `182.0` | `98.75` | **`1.84`** | **`53.5%`** |
| **Guangdong (`guangdong_10kv`)** | `182.0` | `90.61` | **`2.01`** | **`48.9%`** |
| **Jiangsu (`jiangsu_10kv`)** | `182.0` | `85.93` | **`2.12`** | **`46.2%`** |
| **Yunnan (`yunnan_10kv`)** | `182.0` | `50.96` | **`3.57`** | **`25.0%`** |

<p align="center">
  <img src="docs/assets/demo_qsts_24h.png" alt="24-Hour QSTS Time-Series & SOC" width="92%" />
</p>

---

## 5. System Architecture

```mermaid
flowchart LR
    subgraph Clients["Dual-Mode Interfaces"]
        UI["Streamlit Workbench\n(Zero-Key GUI + Optional AI Chat)"]
        MCP["MCP Clients\n(Claude / Cursor / Codex)"]
        EVAL["24-Case AI Eval Suite\n(L1–L4 Benchmarks)"]
    end

    subgraph Core["VoltPilot Physics & Governance Core (6 Atomic Tools)"]
        SVC["VoltPilotService\n(Unified Envelope & Guardrails)"]
        ENG["OpenDSSEngine\n(Dedicated Thread-Safe Worker + RunStore)"]
        STD["Configurable Standards Engine\n(DL/T 2041-2025/2019 · GB/T 12325/15543 · ANSI)"]
        GOV["Hosting Capacity & What-If Governance\n(OLTC · Volt-Var · BESS)"]
        REP["Diagnostics Plotter & Traceable Report\n(No run_id -> Refusal)"]
    end

    UI --> SVC
    MCP --> SVC
    EVAL --> SVC
    SVC --> ENG
    SVC --> GOV
    SVC --> REP
    ENG --> STD
    GOV --> ENG
```

### The 9 Atomic Tools (Shared by MCP, Streamlit & Copilot — `v0.2`)
1. `load_feeder` — Inspect valid buses, voltage bases, regulators, and recommended DER candidate buses (built-in or custom).
2. `run_power_flow` — Execute deterministic OpenDSS snapshot solve, evaluate compliance, and issue an immutable `run_id`.
3. `evaluate_der_hosting` — Grade `GREEN / YELLOW / RED`, locate dominant bottlenecks, and compute **±1 kW exact binary-search** Green & Yellow hosting limits (invariant to coarse sweep step).
4. `compare_mitigations` — Benchmark `oltc_tap`, `volt_var`, and `bess_shaving` on the same `base_run_id` with ranked engineering tradeoffs.
5. `plot_grid_diagnostics` — Render traceable diagnostic charts (`voltage_profile`, `mitigation_compare`, `hosting_curve`, `qsts_24h`).
6. `generate_audit_report` — Emit bilingual (`zh` / `en`) Markdown engineering audit reports strictly verified against `RunStore` snapshots.
7. `run_qsts_24h` — Run deterministic 24-hour QSTS OpenDSS time-series simulation (`00:00–23:00`) with typical Chinese load/PV/EV curves and cyclic peak-aware BESS dispatch.
8. `register_custom_feeder` — Sandbox-validate (blocks `System`/`DOSCmd`/path-traversal directives), compile, and dynamically register user-supplied `.dss` feeders.
9. `estimate_bess_economics` — Compute TOU arbitrage + demand-charge savings, static payback years, and 10-year IRR across Chinese provincial 10 kV tariffs (`zhejiang_10kv`, `guangdong_10kv`, `jiangsu_10kv`, `yunnan_10kv`).

---

## 6. Trustworthy AI Evaluation (`evals/`) — Real Benchmark Results

Rather than relying on cherry-picked demos, VoltPilot ships with a **24-case stratified evaluation suite** ([evals/cases_v1.jsonl](evals/cases_v1.jsonl)) and strict structured-field + runtime-evidence scoring ([evals/scoring.py](evals/scoring.py)).

### Full 24/24 Paired Live Benchmark (`deepseek-flash` / DeepSeek V4.1 Flash)
Raw reproducible evidence log: [`evals/deepseek_flash_compare_v1.json`](evals/deepseek_flash_compare_v1.json) (`24/24` paired runs completed, `temperature=0.1`).

| Metric | Bare `deepseek-flash` (No Tools) | **VoltPilot + `deepseek-flash`** | Gain |
| :--- | :---: | :---: | :---: |
| **Overall 24-Case Pass Rate (`L1–L4`)** | `16.7%` (`4 / 24`) | **`91.7%` (`22 / 24`)** | **`+75.0 pp`** |
| **Physical Numeric Accuracy** (voltage / loss / loading / capacity) | `0.0%` (`0 / 84`) | **`97.6%` (`82 / 84`)** | **`+97.6 pp`** |
| **Red / Yellow / Green Grade Exact Match** | `0.0%` (`0 / 35`) | **`100.0%` (`35 / 35`)** | **`+100.0 pp`** |
| **Runtime Evidence Grounding (`run_id` verified)** | `0.0%` | **`100.0%` (`18 / 18`)** | **`+100.0 pp`** |
| **L4 Adversarial Hallucination Trap Pass Rate** | `66.7%` (`4 / 6`) | **`100.0%` (`6 / 6`)** | **`+33.3 pp`** |
| **Efficiency (Avg Tool Calls / Wall Time per Case)** | — | **`1.71 steps` · `2.76 s`** | Fast & lightweight |

### Breakdown by Evaluation Tier

| Tier | Cases | What It Verifies | Bare `deepseek-flash` | **VoltPilot + `deepseek-flash`** |
| :--- | :---: | :--- | :---: | :---: |
| **L1 · Power Flow & Violations** | 6 | Voltage extremes, losses, single-phase unbalance across all 4 feeders | `0 / 6` | **`6 / 6` (100%)** |
| **L2 · Hosting Capacity & Policy** | 6 | `DL/T 2041-2025` vs `2019` policy shift, EV charging, CN vs US limits | `0 / 6` | **`4 / 6` (66.7%)**\* |
| **L3 · What-If Governance** | 6 | `RED → GREEN` rescue, loss/reverse-flow tradeoffs, anti-overinvestment warnings | `0 / 6` | **`6 / 6` (100%)** |
| **L4 · Adversarial Hallucination Traps** | 6 | Fake bus `bus999`, 3-phase DER on 1-phase bus `611`, 60 MW voltage collapse, forged/empty `run_id` issuance | `4 / 6` | **`6 / 6` (100%)** |

> **\*Transparent Error Analysis (`L2_02` & `L2_05`)**: On the only 2 missed cases out of 24, VoltPilot + `deepseek-flash` passed **every** grade, bottleneck, voltage, and `run_id` evidence check—failing solely on `metrics.max_green_kw` because the model selected finer scan steps (`step_kw=100` / `50 kW`) than the default coarse 12-point ground-truth sweep grid, shifting the discrete step boundary. This directly informs our `v0.2` roadmap: replacing fixed-step sweeps with deterministic binary-search hosting-limit refinement.

---

## 7. Quick Start

### Install
```bash
python -m venv .venv
# Windows PowerShell: .\.venv\Scripts\Activate.ps1
# Linux / macOS:      source .venv/bin/activate
pip install -e ".[dev]"
```

### Launch Zero-Key Interactive Workbench
```bash
python -m streamlit run app/streamlit_app.py --server.fileWatcherType none
```
*(Windows users can simply double-click `start_voltpilot.bat`.)*

### Connect as an MCP Server (Claude Desktop / Cursor / Codex)
```json
{
  "mcpServers": {
    "voltpilot": {
      "command": "voltpilot-mcp"
    }
  }
}
```

### Run Tests & 24-Case AI Evals
```bash
# Unit, integration & guardrail tests
pytest -v

# Zero-key verification of all 24 deterministic benchmarks & 6 adversarial traps
python evals/run_eval.py --mode verify-ground-truth

# Optional: Bare LLM vs. VoltPilot-Grounded LLM benchmark
python evals/run_eval.py --mode compare-llm \
  --base-url https://api.deepseek.com \
  --model deepseek-flash \
  --api-key YOUR_API_KEY
```

---

## 8. Product Roadmap: From Physical Feasibility to Commercial Bankability

VoltPilot follows a unified **Grid Physics → Time-Series Dynamics → Energy Economics** architecture:
- **v0.1 (Shipped)**: OpenDSS physics core + 4 built-in feeders (`cn_10kv_demo`, `ieee13`, `ieee34`, `ieee123`) + China/US configurable compliance (`DL/T 2041-2025/2019`, `GB/T 12325`, `GB/T 15543`, `ANSI C84.1`) + 6 MCP tools + Dual-mode Streamlit workbench + 24-case AI Eval suite (`deepseek-flash` verified).
- **v0.2 (Current · Shipped)**:
  - **Binary-search ±1 kW exact hosting capacity refinement** (eliminating coarse `step_kw` boundary mismatch);
  - **24-hour QSTS time-series engine (`run_qsts_24h`)** with peak-aware cyclic BESS dispatch & 3-panel visualization;
  - **Sandboxed custom `.dss` feeder upload** (`register_custom_feeder`, blocking shell/path-escape directives);
  - **China 4-province 10 kV BESS economics engine** (`estimate_bess_economics`: Zhejiang / Guangdong / Jiangsu / Yunnan TOU + demand charge + IRR);
  - **Multi-provider Eval & Leaderboard** (`--provider deepseek | glm | qwen | doubao | openai` + `evals/build_leaderboard.py`).
- **v0.3 / v1.0 (Next)**: Multi-model live leaderboard (GLM / Qwen / DeepSeek / GPT side-by-side), short-circuit & harmonic (`GB/T 14549`) checks, optional `pandapower` backend adapter, and multi-day/annual tariff + rolling MPC storage optimization.

---

## 9. Current Limitations & Community Feedback

**VoltPilot is currently at `v0.2` (active open-source iteration)**, and we stay transparent about remaining engineering boundaries:

- **Simulation scope**: v0.2 covers steady-state snapshots and typical-day 24h QSTS hourly series, but does not yet include 8,760-hour annual stochastic simulation, short-circuit fault calculations, or harmonic distortion (`GB/T 14549`) screening.
- **Regional tariff & standard nuances**: Provincial grid companies update proxy-purchase TOU prices monthly and customize `DL/T 2041-2025` enforcement details; all standards (`voltpilot/standards_data/`) and tariffs (`voltpilot/tariffs_data/`) are editable YAML templates for local calibration.
- **Multi-model leaderboard expansion**: Full 24-case live comparison is currently verified on `deepseek-flash`; additional providers (GLM / Qwen / OpenAI) are supported in `evals/run_eval.py` and being added to the leaderboard.

I will keep updating VoltPilot continuously. **Power system engineers, students, researchers, and AI builders are warmly welcome to open an Issue, start a Discussion, or submit a PR**—whether to point out modeling flaws, contribute provincial tariff/standard YAML templates, or suggest new workflows!

---

## License & Disclaimer

Licensed under the [MIT License](LICENSE). Built-in IEEE feeders follow public EPRI OpenDSS test cases; `cn_10kv_demo` is an open synthetic benchmark constructed from standard Chinese 10 kV conductor parameters. Because provincial grid utilities may customize exact `DL/T 2041` thresholds, all compliance rules are stored as transparent, user-editable YAML files under `voltpilot/standards_data/`.