Documentation

Learn how to run SecureHospital AI locally and understand its security architecture.

Overview

SecureHospital AI is an enterprise-grade healthcare AI demonstration platform that showcases how to safely integrate Large Language Models (LLMs) with sensitive healthcare data. It implements a three-layer security architecture using Django, FastAPI, and the Model Context Protocol (MCP).

Role-Based Access Control

Fine-grained permissions based on healthcare roles (Doctor, Nurse, Admin, etc.)

Complete Audit Trail

Every data access is logged with user, timestamp, and action details

PHI Protection

Protected Health Information is access-controlled and redacted based on role

AI Integration

OpenAI GPT with MCP tools for secure healthcare data queries

Architecture

The system uses a three-layer security model where each layer provides independent protection:

┌─────────────────────────────────────────────────────────────────┐
│                        USER INTERFACE                            │
│                    (React / HTML Dashboard)                      │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                    LAYER 1: DJANGO BACKEND                       │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────────┐  │
│  │   Auth &    │  │   Session   │  │    LLM Handler          │  │
│  │    JWT      │  │  Management │  │  (OpenAI Integration)   │  │
│  └─────────────┘  └─────────────┘  └─────────────────────────┘  │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                    LAYER 2: OPENAI GPT-4                         │
│  ┌─────────────────────────────────────────────────────────┐    │
│  │  System Prompt with Security Guidelines + Tool Schemas   │    │
│  │  • Cannot reveal PHI without authorization               │    │
│  │  • Must call MCP tools for data access                   │    │
│  │  • Respects role-based restrictions                      │    │
│  └─────────────────────────────────────────────────────────┘    │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                    LAYER 3: MCP SERVER (FastAPI)                 │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────────────┐   │
│  │    RBAC      │  │    Audit     │  │    Data Access       │   │
│  │  Enforcement │  │   Logging    │  │    (PostgreSQL)      │   │
│  └──────────────┘  └──────────────┘  └──────────────────────┘   │
└─────────────────────────────────────────────────────────────────┘

Component Overview

Component Technology Purpose
Frontend HTML, JavaScript, Bootstrap User interface and chat
Backend Django 5.x, DRF Auth, sessions, API gateway
MCP Server FastAPI, Python RBAC, audit, data tools
Database PostgreSQL EHR data storage
AI OpenAI GPT-4 Natural language processing

Features

Security Features

  • JWT Authentication - Secure token-based auth with refresh tokens
  • Role-Based Access Control - 6 predefined roles with granular permissions
  • Audit Logging - Every tool call logged to database
  • PHI Redaction - Sensitive data hidden from unauthorized roles
  • Session Management - Isolated chat sessions per user

AI Features

  • Natural Language Queries - Ask questions in plain English
  • Tool Calling - AI decides which MCP tools to invoke
  • Streaming Responses - Real-time SSE streaming
  • Context Persistence - Remembers patient context across messages
  • Auto Chat Titles - Automatic naming based on first message

MCP Tools

Tool Description Required Role
get_patient_overview Basic patient demographics All roles
get_medical_records Clinical notes and diagnoses Doctor, Nurse, Auditor
get_patient_phi SSN, insurance, addresses Full: Doctor, Admin, Auditor
Insurance-only: Billing
get_appointments Patient appointments All clinical roles
get_admissions Hospital admissions Doctor, Nurse, Admin
get_my_shifts Current user's schedule All staff
get_shifts Department schedules Admin, Auditor

Prerequisites

Before running SecureHospital AI locally, ensure you have:

Required Software

Python 3.11+, PostgreSQL 14+, Node.js 18+ (optional for frontend dev), Git

Requirement Version Check Command
Python 3.11+ python --version
PostgreSQL 14+ psql --version
Git Any git --version
OpenAI API Key - From platform.openai.com

Local Setup

Follow these steps to run SecureHospital AI on your local machine:

1

Clone the Repository

Get the source code from GitHub

Bash
git clone https://github.com/yourusername/securehospital-ai.git cd securehospital-ai
2

Create Virtual Environment

Isolate Python dependencies

Bash
# Create virtual environment python -m venv venv # Activate (Linux/Mac) source venv/bin/activate # Activate (Windows) venv\Scripts\activate
3

Install Dependencies

Install all required Python packages

Bash
# Install Django backend dependencies pip install -r requirements.txt # Install MCP server dependencies pip install -r mcp_server/requirements.txt
4

Setup Environment Variables

Configure your local environment

Bash
# Copy example environment file cp .env.example .env # Edit with your settings nano .env
.env
# Django Settings DEBUG=True SECRET_KEY=your-secret-key-here ALLOWED_HOSTS=localhost,127.0.0.1 # Database DATABASE_URL=postgresql://user:password@localhost:5432/securehospital # OpenAI OPENAI_API_KEY=sk-your-openai-api-key # MCP Server MCP_SERVER_URL=http://localhost:8001
5

Setup Database

Create the PostgreSQL database and run migrations

Bash
# Create database createdb securehospital # Run migrations python manage.py migrate
6

Start the Servers

Run both Django and MCP servers

Bash
# Terminal 1: Start Django server python manage.py runserver # Terminal 2: Start MCP server cd mcp_server uvicorn main:app --port 9000 --reload
7

Import Demo Data

Populate the database with sample patients, staff, and medical records

Visit the demo data import page in your browser:

URL
http://localhost:8000/seed-data/

Click the "Import Demo Data" button and wait for the import to complete. You'll see counts for all created records:

  • 6 Demo accounts (Admin, Doctor, Nurse, Billing, Reception, Auditor)
  • 50 Patients with PHI records
  • 100 Appointments
  • 80 Medical records
  • Staff shifts and audit logs

You're Ready!

Open http://localhost:8000 in your browser and login with demo credentials (password: DemoPass123!)

Demo Data Import

SecureHospital AI includes a web-based demo data importer that creates sample patients, staff, and medical records with a single click.

Import via Web Interface

The easiest way to populate your database with demo data:

1

Navigate to Import Page

Open your browser and go to:

URL
http://localhost:8000/seed-data/
2

Click Import Button

Click "Import Demo Data" and wait for completion

3

View Results

The page will display counts of all created records

What Gets Created

Data Type Count Description
Demo Accounts 6 One for each role (Admin, Doctor, Nurse, Billing, Reception, Auditor)
Patients 50 With full PHI records (SSN, address, insurance)
Appointments 100 Mix of past and future appointments
Medical Records 80 Diagnoses and treatments
Staff Shifts 50 Schedule data for staff
Audit Logs 100 Sample audit trail entries

Demo Account Credentials

All demo accounts use the same password:

Username Role Password
demo_admin Admin DemoPass123!
demo_doctor Doctor DemoPass123!
demo_nurse Nurse DemoPass123!
demo_billing Billing DemoPass123!
demo_reception Reception DemoPass123!
demo_auditor Auditor DemoPass123!

One-Time Import

Only run the import once on a fresh database. Running it multiple times will create duplicate records.

Docker Setup

For containerized deployment, use Docker Compose:

Bash
# Build and start all services docker-compose up --build # Run in background docker-compose up -d # View logs docker-compose logs -f # Stop services docker-compose down

Docker Compose Services

Service Port Description
web 8000 Django backend
mcp 9000 MCP FastAPI server
db 5432 PostgreSQL database
redis 6379 Cache (optional)

Environment Variables

Full list of configurable environment variables:

Variable Required Description
SECRET_KEY Yes Django secret key
DEBUG No Debug mode (default: False)
DATABASE_URL Yes PostgreSQL connection string
OPENAI_API_KEY Yes OpenAI API key
OPENAI_MODEL No Model name (default: gpt-4)
MCP_SERVER_URL Yes MCP server URL
ALLOWED_HOSTS No Comma-separated hosts

Database Configuration

SecureHospital AI uses PostgreSQL for storing EHR data, audit logs, and user sessions. The database schema is managed through Django migrations.

Connection Setup

Configure your database connection in the .env file:

.env
# Option 1: Full connection URL (recommended for production) DATABASE_URL=postgresql://user:password@localhost:5432/securehospital # Option 2: Individual parameters (for development) PGHOST=localhost PGPORT=5432 PGDATABASE=securehospital PGUSER=your_username PGPASSWORD=your_password # MCP Server uses separate connection (can be same DB) DATABASE_URL_MCP=postgresql://user:password@localhost:5432/securehospital

Database Schema

The application creates several key tables:

Table Purpose PHI Level
ehr_patient Basic patient demographics Low
ehr_phidemographics Protected Health Information (SSN, address) High
ehr_medicalrecord Clinical notes and diagnoses High
ehr_admission Hospital admissions Medium
ehr_appointment Patient appointments Low
ehr_staff Hospital staff records Low
audit_auditlog Security audit trail Meta

Migrations

Bash
# Create migrations after model changes python manage.py makemigrations # Apply migrations to database python manage.py migrate # Load sample data for demo python manage.py loaddata sample_data.json

Production Warning

The sample data contains fake patient records. Never use sample data in production. Always use proper database backup and encryption for real PHI.

OpenAI Setup

SecureHospital AI uses OpenAI's GPT models for natural language processing and function calling to interact with the MCP tools.

API Key Configuration

Obtain an API key from platform.openai.com and add it to your .env file:

.env
# Required: Your OpenAI API key OPENAI_API_KEY=sk-your-api-key-here # Optional: Specify model (default: gpt-4o-mini) OPENAI_MODEL=gpt-4o-mini

Supported Models

Model Use Case Cost
gpt-4o-mini Default - Fast, cost-effective Low
gpt-4o Better reasoning, complex queries Medium
gpt-4-turbo Maximum capability High

Function Calling

The LLM uses OpenAI's function calling feature to invoke MCP tools. Tool definitions are passed in the system prompt:

Python
MCP_TOOLS = [ { "type": "function", "function": { "name": "get_patient_phi", "description": "Get Protected Health Information...", "parameters": { "type": "object", "properties": { "patient_id": {"type": "string"} }, "required": ["patient_id"] } } }, # ... other tools ]

Streaming Responses

The chat interface uses Server-Sent Events (SSE) for real-time streaming:

Python
# Streaming is handled by StreamingLLMAgent async for chunk in agent.stream_chat(user_message): yield f"data: {json.dumps(chunk)}\n\n"

Cost Management

Each message uses tokens from your OpenAI account. The default gpt-4o-mini model costs approximately $0.15 per 1M input tokens and $0.60 per 1M output tokens.

MCP Server Configuration

The Model Context Protocol (MCP) server is a FastAPI application that provides the security layer between the LLM and your database. It enforces RBAC, performs PHI redaction, and logs all access attempts.

Server Configuration

.env
# MCP Server URL (Django connects here) MCP_SERVER_URL=http://localhost:9000 # JWT Authentication (must match Django's SECRET_KEY) SECRET_KEY=your-django-secret-key # Database connection for MCP server DATABASE_URL_MCP=postgresql://user:password@localhost:5432/securehospital # Optional: SSL mode for database MCP_DB_SSLMODE=require

Starting the MCP Server

Bash
# Development mode with auto-reload cd mcp_server uvicorn main:app --host 0.0.0.0 --port 9000 --reload # Production mode uvicorn main:app --host 0.0.0.0 --port 9000 --workers 4

Available MCP Tools

The MCP server exposes these JSON-RPC tools:

Tool Description PHI Access
get_patient_overview Basic demographics (name, DOB year, gender) None
get_patient_phi SSN, address, insurance (role-based redaction) Full/Redacted/Insurance-Only
get_medical_records Clinical notes and diagnoses Clinical
get_appointments Patient appointments None
get_admissions Hospital admissions None
get_my_shifts Current user's schedule None
get_shifts Department schedules (Admin/Auditor only) None

PHI Redaction by Role

The MCP server automatically redacts PHI based on user role:

Role PHI Access Level Fields Visible
Admin, Doctor, Auditor Full All PHI fields including SSN
Nurse Redacted DOB visible, SSN/address hidden
Billing Insurance Only insurance_provider, insurance_number only
Reception Denied No PHI access

JSON-RPC Protocol

The MCP server uses JSON-RPC 2.0 for communication:

JSON Request
{ "jsonrpc": "2.0", "id": "unique-request-id", "method": "tools.call", "params": { "name": "get_patient_phi", "arguments": {"patient_id": "FCE57"} } }
JSON Response (Success)
{ "jsonrpc": "2.0", "id": "unique-request-id", "result": { "data": { "patient_id": "FCE57", "insurance_provider": "BlueCross", "insurance_number": "BC-12345", "_access_level": "insurance_only" } } }

Health Check

Verify the MCP server is running:

Bash
curl http://localhost:9000/health # Response: {"status": "ok", "service": "mcp-server", "version": "2.0"}

Security Note

The MCP server validates JWT tokens using the same SECRET_KEY as Django. This ensures only authenticated users can access data tools.

Role-Based Access Control

SecureHospital AI implements healthcare-specific RBAC with 6 predefined roles:

Role Patient Data Medical Records PHI Access Scheduling
Admin ✅ Full ✅ Full ✅ Full ✅ All Staff
Doctor ✅ Full ✅ Full ✅ Full Own Only
Nurse ✅ Full ✅ Full Limited Own Only
Auditor ✅ Read ✅ Read ✅ Read ✅ All (Read)
Reception Basic Only ❌ No ❌ No Own Only
Billing Demographics ❌ No Insurance Only Own Only

RBAC Enforcement

Access control is enforced at the MCP layer. Even if a user asks the AI for unauthorized data, the MCP server will reject the request and log the attempt.

Audit Logging

Every data access is logged to the audit_log table:

SQL Schema
CREATE TABLE audit_log ( id UUID PRIMARY KEY, timestamp TIMESTAMP NOT NULL, user_id UUID REFERENCES users(id), staff_id UUID REFERENCES staff(staff_id), action VARCHAR(50) NOT NULL, table_name VARCHAR(100), record_id VARCHAR(100), details JSONB, ip_address VARCHAR(45), user_agent TEXT );

Logged Actions

  • TOOL_CALL - MCP tool invocation
  • ACCESS_GRANTED - Successful data access
  • ACCESS_DENIED - RBAC rejection
  • PHI_ACCESS - Protected data viewed
  • LOGIN / LOGOUT - Session events

PHI Protection

Protected Health Information (PHI) includes:

  • Social Security Numbers
  • Full addresses
  • Phone numbers
  • Insurance policy numbers
  • Medical record numbers
  • Detailed diagnosis information

PHI Access Levels

Full Access: Doctor, Admin, Auditor can see all PHI including SSN.
Redacted: Nurse sees DOB but SSN/address are masked.
Insurance Only: Billing sees only insurance_provider and insurance_number.
No Access: Reception cannot access PHI data.

Troubleshooting

Common Issues

MCP Server Connection Failed

Error
ConnectionError: Unable to connect to MCP server

Solution: Ensure the MCP server is running on port 8001. Check MCP_SERVER_URL in your .env file.

OpenAI API Error

Error
openai.AuthenticationError: Invalid API key

Solution: Verify your OPENAI_API_KEY is correct and has sufficient credits.

Database Connection Error

Error
django.db.utils.OperationalError: connection refused

Solution: Ensure PostgreSQL is running and DATABASE_URL is correct.

Async/Sync Django Error

Error
SynchronousOnlyOperation: You cannot call this from an async context

Solution: Wrap Django ORM calls with @sync_to_async decorator in async functions.