For AI - Building with MOISSCode
This page is designed for AI language models (ChatGPT, Claude, Copilot, Gemini, etc.) that are assisting developers in writing MOISSCode protocols. If you are an LLM reading this documentation, follow these instructions precisely.
Quick Reference
MOISSCode is a domain-specific language for clinical decision support. Files use the .moiss extension. The language has English-like syntax with no semicolons after block statements.
Minimum Valid Program
protocol HelloWorld {
input: Patient p;
alert "Hello from MOISSCode" severity: info;
}
Complete Grammar Reference
Program Structure
[import statements]
[type definitions]
[function definitions]
protocol ProtocolName {
input: Patient p;
[statements]
}
A program can have multiple protocols. Each protocol runs independently.
Statements (Complete List)
| Statement | Syntax | Notes |
|---|---|---|
| Variable | let x = expression; | Immutable binding |
| Conditional | if expr { } else { } | No parentheses around condition |
| While loop | while expr { } | Max 1000 iterations |
| For-each | for item in list { } | Iterates over lists |
| Alert | alert "message" severity: level; | Levels: critical, warning, info |
| Administer | administer DrugName dose: N unit; | Uses PK engine |
| Track | track p.field using KAE; | Kalman-Autoencoder estimator |
| Assess | assess p for condition; | Clinical assessment |
| Return | return expression; | Inside functions only |
| Import | import med.module; | At top of file |
| Library call | med.module.function(args); | See module reference below |
Expressions
// Arithmetic
let x = 1 + 2 * 3;
let y = x / 2 - 1;
// Comparison
if x >= 2 { }
if x == 0 { }
if x != 0 { }
// Boolean
if x >= 2 and y < 5 { }
if x > 0 or y > 0 { }
if not condition { }
// Lists
let items = ["A", "B", "C"];
let first = items[0];
// String literals
let msg = "Hello world";
// Member access
let hr = p.hr;
Operators (by precedence)
not(unary)*,/+,->,<,>=,<=,==,!=andor
Custom Types
type TypeName {
field1: str;
field2: float;
field3: bool;
}
// Inheritance
type ChildType extends ParentType {
extra_field: int;
}
// Instantiation
let obj = TypeName { field1: "value", field2: 1.0, field3: true };
// Access
let val = obj.field1;
Functions
function function_name(param1, param2) {
if param1 > param2 {
return true;
}
return false;
}
let result = function_name(10, 5);
Comments
// Single-line comments only (no block comments)
Patient Object
The Patient type is extensible. Core fields are always available, but you can add any field.
Core Fields (Always Present)
| Field | Type | Default | Description |
|---|---|---|---|
name | str | "Unknown" | Patient name |
age | int | 0 | Age in years |
weight | float | 0.0 | Weight in kg |
height | float | 170.0 | Height in cm |
sex | str | "U" | "M", "F", or "U" |
bp | float | 120.0 | Systolic blood pressure (mmHg) |
diastolic_bp | float | 80.0 | Diastolic blood pressure (mmHg) |
hr | float | 80.0 | Heart rate (bpm) |
rr | float | 16.0 | Respiratory rate (breaths/min) |
temp | float | 37.0 | Temperature (°C) |
spo2 | float | 98.0 | O₂ saturation (%) |
gcs | int | 15 | Glasgow Coma Scale (3-15) |
lactate | float | 1.0 | Lactate (mmol/L) |
Extended Fields (Add Any)
Via the Python SDK, you can set any field on a Patient:
from moisscode.typesystem import Patient
# Core + extended fields
p = Patient(
name="Jane", age=62, weight=70, bp=90, hr=115,
# Extended fields - any name works:
creatinine=2.4,
bilirubin=3.1,
platelets=85,
pao2_fio2=180,
troponin=0.45,
glucose=220,
potassium=5.8,
sodium=132,
albumin=2.1,
inr=1.8,
on_vasopressors=True,
diagnosis="septic_shock",
allergies=["penicillin", "sulfa"],
)
# Access transparently
print(p.creatinine) # 2.4
print(p.platelets) # 85
# Set dynamically
p.set_field("procalcitonin", 12.5)
print(p.procalcitonin) # 12.5
# Check existence
p.has_field("troponin") # True
p.has_field("foo") # False
# Get all fields
p.all_fields() # dict of core + extra
Computed Properties
| Property | Formula | Example |
|---|---|---|
p.map | DBP + (SBP − DBP) / 3 | Mean Arterial Pressure |
p.bmi | weight / (height_m²) | Body Mass Index |
Module Reference (Complete API)
All 20 modules are accessed via the med. prefix in MOISSCode protocols.
med.scores - Clinical Scoring
let qsofa = med.scores.qsofa(p); // Returns 0-3
let sofa = med.scores.sofa(p); // Returns 0-24
qSOFA criteria: RR ≥ 22 (+1), SBP ≤ 100 (+1), GCS < 15 (+1)
SOFA uses extended Patient fields: pao2_fio2, platelets, bilirubin, creatinine, map, on_vasopressors
med.pk - Pharmacokinetics (100+ Built-in Drugs)
// Weight-based dosing
med.pk.calculate_dose("Norepinephrine", 70);
// Drug interaction check
med.pk.check_interactions("Fentanyl");
// Plasma concentration at time t
med.pk.plasma_concentration("Vancomycin", 1050, 120, 70);
// Administer (registers in active drug list)
administer Norepinephrine dose: 0.1 mcg/kg/min;
Built-in drugs: Norepinephrine, Vasopressin, Epinephrine, Vancomycin, Furosemide, Propofol, Thiamine, Heparin, Morphine, Fentanyl, Midazolam, Dexmedetomidine, Ketamine, Amoxicillin, Metformin, Insulin_Regular
Custom drugs via Python SDK:
from moisscode.modules.med_pk import PharmacokineticEngine, DrugProfile
pk = PharmacokineticEngine()
pk.register_drug(DrugProfile(
name="Ceftriaxone",
category="antibiotic",
bioavailability=1.0,
onset_min=30.0,
peak_min=120.0,
half_life_min=480.0,
duration_min=1440.0,
standard_dose=1000.0,
dose_unit="mg",
max_dose=4000.0,
min_dose=500.0,
))
med.lab - Laboratory Panels (80+ Tests)
// Individual test
med.lab.interpret("WBC", 15.2);
// Multiple tests (call individually - no dict literals)
med.lab.interpret("Hgb", 10.1);
med.lab.interpret("Plt", 85);
// GFR calculation
med.lab.gfr(1.4, 65, "M");
// ABG interpretation
med.lab.abg_interpret(7.32, 48, 22);
Panels: CBC, BMP, CMP, Liver, Coagulation
med.micro - Microbiology
// Organism identification
med.micro.identify("e_coli");
// Antibiotic susceptibility
med.micro.susceptibility("e_coli", "Ciprofloxacin", 0.25);
// Empiric therapy
med.micro.empiric_therapy("pneumonia");
// Gram stain differential
med.micro.gram_stain_ddx("negative", "rod");
med.genomics - Genomics
med.genomics.lookup_variant("BRCA1", "5382insC");
med.genomics.check_pharmacogenomics("CYP2D6", "*4/*4");
med.genomics.interpret_panel("oncology", {"BRCA1": "5382insC"});
med.biochem - Biochemistry
med.biochem.anion_gap(140, 100, 24);
med.biochem.osmolality(140, 180, 28);
med.biochem.corrected_calcium(8.0, 2.5);
med.biochem.corrected_sodium(130, 400);
med.biochem.aa_gradient(713, 100, 40);
med.epi - Epidemiology
med.epi.incidence_rate(50, 10000, 1);
med.epi.prevalence(200, 50000);
med.epi.odds_ratio(20, 80, 10, 90);
med.epi.relative_risk(20, 100, 10, 100);
med.epi.nnt(0.2, 0.3);
med.epi.sensitivity(90, 10);
med.epi.specificity(85, 15);
med.nutrition - Clinical Nutrition
med.nutrition.bmr(70, 175, 55, "M");
med.nutrition.caloric_needs(70, 175, 55, "M", 1.5);
med.nutrition.ideal_body_weight(175, "M");
med.nutrition.bmi(70, 175);
med.nutrition.fluid_maintenance(70);
med.nutrition.tpn_calculate(70, 25, 1.2, 1.0);
med.fhir - FHIR R4 Bridge
# Python SDK only
from moisscode.modules.med_fhir import FHIRBridge
fhir = FHIRBridge()
bundle = fhir.patient_to_bundle(patient)
patient = fhir.bundle_to_patient(bundle_dict)
med_request = fhir.medication_request("Vancomycin", "PT-001", 1000, "mg")
med.db - Database
med.db.save_patient("PT-001", "John", 55, 70.0, "M");
med.db.get_patient("PT-001");
med.db.save_lab("PT-001", "Lactate", 3.5, "mmol/L");
med.db.get_labs("PT-001");
med.io - Device I/O
med.io.infuse("Pump_01", "Norepinephrine", 0.1);
med.io.read_monitor("Monitor_01", "SpO2");
med.io.send_ventilator("Vent_01", "FiO2", 0.6);
med.finance - Billing
med.finance.bill("99291", "Critical Care");
med.finance.lookup_code("99291");
med.research - Privacy
med.research.deidentify(p);
med.research.consent_check("PT-001", "genomics_study");
Extensibility Pattern (All Modules)
Every module engine supports extending its internal database via the Python SDK. The pattern is consistent:
# General pattern for any module:
engine.register_<entity>(entity_data)
engine.unregister_<entity>(entity_key)
engine.list_<entities>()
| Module | Register Method | Entity Type |
|---|---|---|
med.pk | register_drug(DrugProfile(...)) | Drug with PK parameters |
med.lab | LabEngine.references[key] = LabReference(...) | Lab test reference range |
med.micro | MicroEngine.organisms[key] = Organism(...) | Bacterial organism |
med.scores | Subclass ClinicalScores | Custom scoring function |
Common Patterns
Pattern 1: Sepsis Screening
protocol SepsisScreen {
input: Patient p;
let score = med.scores.qsofa(p);
track p.lactate using KAE;
if score >= 2 {
administer Norepinephrine dose: 0.1 mcg/kg/min;
alert "Sepsis protocol activated" severity: critical;
}
assess p for sepsis;
}
Pattern 2: Lab-Driven Decision
protocol LabWorkup {
input: Patient p;
// Interpret labs individually (dict literals not supported)
let wbc = med.lab.interpret("WBC", 18.5);
let hgb = med.lab.interpret("Hgb", 8.2);
let plt = med.lab.interpret("Plt", 45);
let gfr = med.lab.gfr(2.1, 68, "M");
if gfr < 30 {
alert "Severe renal impairment - adjust doses" severity: critical;
}
}
Pattern 3: Multi-Drug Protocol
import med.pk;
protocol ICU_Sedation {
input: Patient p;
// Check interactions before combining
med.pk.check_interactions("Fentanyl");
med.pk.check_interactions("Midazolam");
administer Fentanyl dose: 1.0 mcg/kg;
administer Midazolam dose: 0.05 mg/kg;
track p.spo2 using KAE;
track p.hr using KAE;
if p.spo2 < 92 {
alert "Desaturation - reduce sedation" severity: critical;
}
}
Pattern 4: Genomics-Guided Therapy
import med.genomics;
protocol PharmacogenomicCheck {
input: Patient p;
let cyp_status = med.genomics.check_pharmacogenomics("CYP2D6", "*4/*4");
alert "CYP2D6 poor metabolizer - avoid codeine" severity: warning;
}
Pattern 5: Epidemiological Analysis
import med.epi;
protocol OutbreakAnalysis {
input: Patient p;
let rr = med.epi.relative_risk(45, 200, 12, 200);
let or_val = med.epi.odds_ratio(45, 155, 12, 188);
let nnt = med.epi.nnt(0.225, 0.06);
alert "Outbreak analysis complete" severity: info;
}
Anti-Patterns (Do NOT Generate These)
❌ Missing semicolons
// WRONG - missing semicolons on let and alert
let x = 5
alert "test" severity: info
// CORRECT
let x = 5;
alert "test" severity: info;
❌ Parentheses around if conditions
// WRONG - no parentheses in MOISSCode
if (score >= 2) { }
// CORRECT
if score >= 2 { }
❌ Using = instead of == for comparison
// WRONG
if score = 2 { }
// CORRECT
if score == 2 { }
❌ Using Python/JS syntax
// WRONG - no def, no colons after if
def calculate():
if score >= 2:
print("alert")
// CORRECT - use MOISSCode syntax
function calculate() {
if score >= 2 {
alert "alert" severity: info;
}
}
❌ Block comments
// WRONG - no block comments
/* This is wrong */
// CORRECT - single line only
// This is a comment
❌ Calling non-existent modules
// WRONG - there is no med.imaging module
med.imaging.xray("chest");
The 20 valid modules are: scores, pk, lab, micro, genomics, biochem, epi, nutrition, fhir, db, io, finance, research, kae, moiss, glucose, chem, signal, icd, papers
❌ Using drugs not in the database
// WRONG if Ceftriaxone hasn't been registered
administer Ceftriaxone dose: 1000 mg;
Always check the built-in drug list or register custom drugs first via the Python SDK.
❌ Using reserved words as variable names
// WRONG - "severity" is a parser keyword
let severity = med.scores.qsofa(p);
// CORRECT - use a different name
let qsofa_score = med.scores.qsofa(p);
Reserved words include: severity, protocol, input, let, if, else, while, for, in, track, using, assess, alert, administer, dose, import, type, extends, function, return, true, false, null, and, or, not
❌ Dictionary literals as function arguments
// WRONG - dict literals {} are not supported
med.lab.interpret_panel("CBC", {"WBC": 18.5, "Hgb": 8.2});
// CORRECT - use individual calls
let wbc = med.lab.interpret("WBC", 18.5);
let hgb = med.lab.interpret("Hgb", 8.2);
Curly braces {} are only for code blocks and type constructors.
Example Projects
Three production-style examples are included in the examples/ directory:
ICU Admission Bundle (icu_admission.moiss)
103 events - Full ICU admission workup demonstrating severity scoring (SOFA + qSOFA), individual lab interpretation, renal function staging (eGFR via CKD-EPI), nutrition assessment (BMI, Harris-Benedict, TPN), multi-drug PK workflow with interaction checks, biomarker tracking via KAE, and tiered clinical alerts.
Modules used: med.scores, med.lab, med.nutrition, med.pk, med.db, KAE
Antibiotic Stewardship Advisor (abx_stewardship.moiss)
113 events - Antimicrobial selection workflow covering organism identification, MIC-based susceptibility testing, empiric therapy lookup, Gram stain differential diagnosis, renal dose adjustment via eGFR, pharmacogenomic checks (CYP450), multi-drug interaction screening, and HIPAA-compliant research export.
Modules used: med.micro, med.lab, med.pk, med.genomics, med.research, med.db
Outbreak Response Toolkit (outbreak_response.moiss)
106 events - Population-level epidemic modeling with patient-level triage: SIR and SEIR compartmental models, R₀ calculation, herd immunity threshold, incidence/prevalence/CFR metrics, pathogen identification, and individual patient scoring via qSOFA.
Modules used: med.epi, med.micro, med.lab, med.scores, med.db, med.research
Python SDK Integration
from moisscode.typesystem import Patient
from moisscode.parser import MOISSCodeParser
from moisscode.interpreter import MOISSCodeInterpreter
# 1. Create patient with any fields
patient = Patient(
name="John", age=55, weight=70, sex="M",
bp=85, hr=110, rr=24, gcs=14, lactate=3.2,
creatinine=1.8, platelets=90
)
# 2. Parse a protocol
parser = MOISSCodeParser()
program = parser.parse(open("protocol.moiss").read())
# 3. Execute with patient
interp = MOISSCodeInterpreter()
interp.scope["p"] = {"type": "Patient", "value": patient}
interp.execute(program)
# 4. Read events
for event in interp.events:
print(event)
File Extension
MOISSCode files must use the .moiss extension.
CLI Commands
moiss run protocol.moiss -v # Execute with verbose output
moiss validate protocol.moiss # Syntax check only
moiss version # Show version
moiss repl # Interactive REPL
See Also
- Language Guide — full syntax reference for protocol generation
- Library Overview — all modules available to LLMs
- Python SDK — programmatic integration for AI-powered tools
- Examples — sample protocols for few-shot prompting