Skip to main content
Glama
53rao

SEBI Compliance MCP System

by 53rao
README.md
# šŸ›”ļø SEBI Compliance MCP System (Working End-to-End Demo)

A deterministic regulatory compliance evaluation system built for **SEBI (Research Analyst) Regulations, 2014**.

This project exposes regulatory compliance rules as **Model Context Protocol (MCP)** tools served by a **FastMCP (`streamable-http`)** server. The rules are queried deterministically from a structured JSON file (`data/rules.json`) without any database, RAG pipeline, or vector store. A **LangGraph React Agent** powered by Groq (`ChatGroq`) acts as the MCP client, orchestrating tool calls based on natural language queries and returning verifiable, deterministic audit trails.

---

## šŸ—ļø Architecture & Core Principles

```
+-------------------------------------------------------------------------------+
|                        Streamlit Frontend (Port 8501)                         |
|   - Chat Interface & Expandable Deterministic Tool Audit Trails               |
|   - Preset Scenario Buttons for One-Click Live Demos                          |
+-------------------------------------------------------------------------------+
                                       |
                             POST /chat (JSON)
                                       v
+-------------------------------------------------------------------------------+
|                       FastAPI Backend (Port 8001)                             |
|   - MultiServerMCPClient (langchain-mcp-adapters)                             |
|   - LangGraph React Agent (langgraph.prebuilt.create_react_agent)             |
|   - Groq LLM (ChatGroq) orchestration & tool selection logic                  |
+-------------------------------------------------------------------------------+
                                       |
                   MCP Streamable HTTP Transport (Port 8000)
                                       v
+-------------------------------------------------------------------------------+
|                      FastMCP Server (`mcp_server/server.py`)                  |
|   - Tools: check_compliance, get_applicable_rules, get_audit_log              |
|   - Deterministic evaluation using safe operator map (NO eval())              |
+-------------------------------------------------------------------------------+
                                 /            \
                  Reads Rules   /              \  Writes Audit Log
                               v                v
          +------------------------+      +---------------------------+
          |    data/rules.json     |      |    audit/audit_log.json   |
          |  (14 Verified Rules)   |      |  (Persistent Log Array)   |
          +------------------------+      +---------------------------+
```

### šŸŽÆ Why Deterministic MCP?
**Compliance verdicts (`pass`, `fail`, `needs_review`) must come exclusively from deterministic code evaluating structured JSON rules — NEVER from an LLM judging raw text or hallucinating regulatory limits.**
- **The LLM's only job is:**
  1. Deciding which MCP tool(s) to call based on the user's natural-language question (`check_compliance`, `get_applicable_rules`, `get_audit_log`).
  2. Turning the structured tool output into a readable response while citing exact SEBI regulations and displaying the unique `audit_id`.
- **No `eval()`:** Numeric and boolean rule conditions are evaluated strictly via safe operator mappings (`operator.ge`, `operator.le`, `operator.eq`, `operator.contains`).
- **Qualitative Rules:** Clauses that require human judgment or documentary verification (e.g. conflict of interest policies or research rationale reasonableness) use `operator: "manual_review"` and deterministically output `needs_review`.

---

## šŸ“‚ Project Structure

```
sebi-compliance-mcp/
ā”œā”€ā”€ .env.example              # Example environment configuration
ā”œā”€ā”€ .env                      # Local environment variables (GROQ_API_KEY)
ā”œā”€ā”€ requirements.txt          # Pinned Python package dependencies
ā”œā”€ā”€ README.md                 # Project documentation & run guide
ā”œā”€ā”€ data/
│   └── rules.json            # 14 hand-authored SEBI Research Analyst rules
ā”œā”€ā”€ mcp_server/
│   └── server.py             # FastMCP server exposing compliance evaluation tools
ā”œā”€ā”€ backend/
│   └── app.py                # FastAPI backend + LangGraph React Agent + MCP Client
ā”œā”€ā”€ frontend/
│   └── streamlit_app.py      # Streamlit interactive chat UI
└── audit/
    └── audit_log.json        # Persistent JSON audit log (generated at runtime)
```

---

## šŸš€ Setup & Installation

### 1. Prerequisites
- **Python 3.11+** installed locally.
- A **Groq API Key** (`GROQ_API_KEY`). You can get one for free at [console.groq.com](https://console.groq.com).

### 2. Create Virtual Environment & Install Dependencies
```bash
# Create and activate virtual environment
python3 -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt
```

### 3. Configure Environment Variables
Copy `.env.example` to `.env` and add your Groq API key:
```bash
cp .env.example .env
```
In `.env`:
```env
GROQ_API_KEY=your_actual_groq_api_key_here
GROQ_MODEL=llama-3.3-70b-versatile
```

---

## ā–¶ļø Running the System (Exact Run Order)

> [!IMPORTANT]
> **The FastMCP server (`server.py`) MUST be running BEFORE the FastAPI backend starts**, because the backend `MultiServerMCPClient` connects and fetches available tools from the server during startup.

Open three separate terminal windows/tabs (make sure your virtual environment `venv` is activated in all three):

### Terminal 1: Start FastMCP Server (Port 8000)
```bash
python mcp_server/server.py
```
*You should see output indicating the server is running on `http://0.0.0.0:8000` (`streamable-http`).*

### Terminal 2: Start FastAPI Backend (Port 8001)
```bash
uvicorn backend.app:app --reload --port 8001
```
*On startup, the backend connects to `http://localhost:8000/mcp`, initializes the `MultiServerMCPClient`, and registers tools with the LangGraph React Agent.*

### Terminal 3: Start Streamlit Frontend (Port 8501)
```bash
streamlit run frontend/streamlit_app.py
```
*Your browser will automatically open at `http://localhost:8501` showing the interactive chat UI.*

---

## šŸ› ļø MCP Tools Reference (`mcp_server/server.py`)

1. **`check_compliance(entity_type: str, scenario: dict) -> dict`**
   - Loads rules matching `entity_type` (`individual_RA`, `partnership_RA`, `non_individual_RA`).
   - Evaluates each scenario attribute against `rules.json`.
   - Computes `overall_status`: `"fail"` if any rule failed, else `"needs_review"` if any rule requires manual verification or scenario fields are missing, else `"pass"`.
   - Generates a unique `audit_id` (e.g. `q-2026-07-12T15:30:00Z-a1b2c3`) and saves the exact execution record to `audit/audit_log.json`.

2. **`get_applicable_rules(entity_type: str) -> list`**
   - Returns all verified SEBI rules and regulatory citations applicable to the specified entity type without evaluating a scenario.

3. **`get_audit_log(audit_id: str) -> dict`**
   - Retrieves the persistent log entry from `audit/audit_log.json` by its unique `audit_id`.

---

## šŸ“‹ Rule Schema (`data/rules.json`)

Each rule adheres strictly to the following schema:
```json
{
  "rule_id": "SEBI-RA-2014-3.2-a",
  "regulation": "SEBI (Research Analysts) Regulations, 2014",
  "clause_ref": "Regulation 3(2)(a)",
  "entity_type": "individual_RA",
  "condition_type": "net_worth_min",
  "operator": ">=",
  "value": 100000,
  "unit": "INR",
  "effective_date": "2014-09-01",
  "effective_until": null,
  "source_citation": "SEBI (Research Analysts) Regulations, 2014, Reg 3(2)(a)",
  "status": "verified"
}
```

### Covered Conditions & Operators
- **Numeric Limits:** `net_worth_min`, `experience_years_min`, `trading_window_lockin_days_before/after`, `record_keeping_years_min`, `holding_in_subject_company_max_pct` (`>=`, `<=`, `==`)
- **Categorical & Set Matches:** `qualification_req` (`in` array of allowed qualifications)
- **Boolean Requirements:** `nism_certification_active`, `compliance_officer_appointed`, `compensation_from_merchant_banking` (`==`)
- **Qualitative Standards (`operator: "manual_review"`):** `conflict_of_interest_policy_quality`, `research_rationale_basis_adequacy` (returns `needs_review` with regulatory targets)

---

## šŸ’” Example Demo Queries

Try these out in the Streamlit UI or by clicking the preset sidebar buttons:
- **Individual RA (Should Fail):**
  > *"Check compliance for an individual_RA with net_worth_min of 80000 INR, qualification_req of post_graduate_degree, nism_certification_active true, experience_years_min of 5, trading_window_lockin_days_before 30, trading_window_lockin_days_after 5, compensation_from_merchant_banking false, holding_in_subject_company_max_pct 0.5, and record_keeping_years_min 5."*
- **Non-Individual RA (Should Pass / Review):**
  > *"Verify compliance for a non_individual_RA with net_worth_min 3000000, compliance_officer_appointed true, record_keeping_years_min 6, conflict_of_interest_policy_quality documented_and_effectively_enforced, and compensation_from_merchant_banking false."*
- **Missing Information (Should Trigger Clarification / Needs Review):**
  > *"Check compliance for an individual RA with ₹200,000 net worth."*