Skip to main content
Glama
README.md
# Healthcare Revenue Cycle Management (RCM) Multi-Agent MCP Server

An AI-native multi-agent Revenue Cycle Management (RCM) MCP server implementing **Eligibility Verification**, **Prior Authorization**, and a **Shared Reasoning Trace** backed by **Supabase** and **pgvector**.

---

## Architecture Overview

```
                          ┌────────────────────────────┐
                          │    RCM Multi-Agent System  │
                          │   (Eligibility / PriorAuth)│
                          └─────────────┬──────────────┘
                                        │ (SSE / HTTP / stdio)
                          ┌─────────────▼──────────────┐
                          │   FastMCP Server (Port 8000)│
                          │  trace.* | eligibility.*   │
                          │        priorauth.*         │
                          └─────────────┬──────────────┘
                                        │
                 ┌──────────────────────┴──────────────────────┐
                 ▼                                             ▼
     ┌────────────────────────┐                   ┌────────────────────────┐
     │  Supabase Relational   │                   │  pgvector / Semantic   │
     │  (Payers, Coverage,    │                   │  (Historical Clinical  │
     │   Rules, Traces)       │                   │   Precedents & Cases)  │
     └────────────────────────┘                   └────────────────────────┘
```

---

## 1. Supabase Database Setup

### Step 1.1: Create a Supabase Project
1. Log in to [Supabase](https://supabase.com) and create a new project.
2. Under **Project Settings -> Database**, note your **Project URL** and **API Keys** (`anon` or `service_role`).

### Step 1.2: Enable `pgvector` & Apply Schema
1. Open the **SQL Editor** in your Supabase Dashboard.
2. Copy and paste the contents of `supabase/schema.sql` and run it:
   - Enables `vector` extension (`CREATE EXTENSION IF NOT EXISTS vector;`).
   - Creates tables: `payers`, `appointments`, `patient_coverage`, `benefit_accumulators`, `payer_pa_rules`, `pa_requests`, `agent_trace` (append-only), and `escalations`.
   - Creates the `match_pa_cases` cosine similarity vector search function.

### Step 1.3: Load Seed Data

You can seed synthetic data into Supabase using either option:

**Option A (Python Seeder Script)**:
Once you configure `.env` with your `SUPABASE_URL` and `SUPABASE_KEY`:
```bash
python seed_data.py
```

**Option B (SQL Editor)**:
In the **SQL Editor**, copy and paste the contents of `supabase/seed.sql` and run it.

This seeds:
- **5 Payers**: Aetna Commercial, Blue Cross Blue Shield, UnitedHealthcare, Medicare Part B, Cigna.
- **5 Appointments**: Scheduled visits with target Dates of Service (DOS).
- **Coverage Records**: Active vs. terminated policies for edge-case testing.
- **Benefit Accumulators**: Deductibles, copays, coinsurance for specific CPT codes.
- **PA Rules & Precedents**: Prior authorization guidelines and historical cases with embeddings.

---

## 2. Environment Configuration

Copy `.env.example` to `.env`:

```bash
cp .env.example .env
```

Update your `.env` file with your credentials:

```env
# Supabase Configuration
SUPABASE_URL=https://<your-project-ref>.supabase.co
SUPABASE_KEY=<your-supabase-service-role-or-anon-key>

# Server Configuration
MCP_SERVER_HOST=0.0.0.0
MCP_SERVER_PORT=8000

# Optional Embedding Key
OPENAI_API_KEY=
```

---

## 3. Installation

Install project dependencies:

```bash
pip install -r requirements.txt
```

---

## 4. MCP Tools Reference

### A. Shared Trace Tools (`trace.*`)
Used across all agents to maintain an append-only, auditable decision log.

| Tool Name | Description | Key Inputs | Output |
| :--- | :--- | :--- | :--- |
| `trace_write_decision` | Appends a decision record to the trace log | `entity_id`, `agent_name`, `decision_type`, `decision_payload`, `confidence`, `evidence_refs` | `status`, `trace_id` |
| `trace_query` | Pulls chronological decision history for an encounter | `entity_id` | `count`, list of trace entries |
| `trace_escalate_to_human` | Queues a case for human supervisor review | `entity_id`, `agent_name`, `reason`, `context` | `escalation_id`, `status` |

### B. Eligibility Tools (`eligibility.*`)
Verifies patient coverage on the actual appointment Date of Service (DOS) and estimates patient cost.

| Tool Name | Description | Key Inputs | Output |
| :--- | :--- | :--- | :--- |
| `eligibility_check_coverage` | Validates active policy window against target service date | `patient_id`, `payer_id`, `service_type`, `service_date` | `coverage_status`, `is_valid_on_service_date`, `deductible_met_pct` |
| `eligibility_get_benefit_details` | Retrieves accumulator balances | `patient_id`, `payer_id`, `cpt_code` | `copay`, `coinsurance_pct`, `deductible_remaining`, `estimated_patient_responsibility` |
| `eligibility_flag_coverage_gap` | Logs a detected coverage gap to trace | `patient_id`, `gap_reason`, `confidence` | `status`, `trace_id` |

### C. Prior Authorization Tools (`priorauth.*`)
Automates procedure rule lookup, precedent search, and clinical justification submission.

| Tool Name | Description | Key Inputs | Output |
| :--- | :--- | :--- | :--- |
| `priorauth_check_requirement` | Checks if procedure code requires prior authorization | `payer_id`, `cpt_code` | `requires_pa`, `rule_text` |
| `priorauth_submit_request` | Submits clinical justification and receives status | `patient_id`, `payer_id`, `cpt_code`, `clinical_summary` | `id`, `status` (`approved`/`denied`/`pending`), `payer_notes` |
| `priorauth_check_status` | Polls submitted authorization status | `pa_request_id` | `id`, `status`, `payer_notes` |
| `priorauth_search_similar_cases` | Semantic vector search over historical PA cases | `cpt_code`, `clinical_summary`, `top_k` | `match_count`, ranked `precedents` with similarity scores |

---

## 5. Running the MCP Server

### Option A: SSE Transport (Default)
Starts the FastMCP server over Server-Sent Events (SSE):

```bash
python run_server.py
```
* The SSE endpoint will be available at: `http://localhost:8000/sse`

### Option B: Custom Host/Port or Stdio
You can customize transport parameters directly:

```bash
# Run over stdio (e.g. for Claude Desktop / CLI clients)
python src/mcp_server/server.py --transport stdio

# Run over SSE on custom port
python src/mcp_server/server.py --transport sse --port 8080
```

---

## 6. Testing & Verification

Run the test suite with `pytest`:

```bash
pytest tests/
```
Expected output:
```
tests\test_mcp_tools.py ..........                                       [100%]
============================= 10 passed in 0.07s ==============================
```

---

## 7. Connecting to Agent Clients

### Claude Desktop Configuration
Add the following to your `claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "rcm-server": {
      "command": "python",
      "args": ["<path-to-repo>/src/mcp_server/server.py", "--transport", "stdio"]
    }
  }
}
```