Skip to main content

API reference (live operations)

Base URL: http://localhost:8001/api/ops. Interactive docs: http://localhost:8001/docs. All bodies are JSON unless stated otherwise. There is no authentication; this is a prototype, so expose it only on a trusted network (e.g. a tailnet).

Intake​

MethodPathBodyNotes
POST/intake/text{text, channel="voice", caller{}, lat?, lon?, address?, lang?, idempotency_key?, emergency_types?}Any transcript (e.g. from a telephony gateway). emergency_types: as on /intake/sos.
POST/intake/sms{"from": "+91…", body, received_at?, message_id?, lang?}Threads by sender: a repeat SMS from the same number joins the open incident (threaded: true), and the AI call-taker replies in the thread. message_id makes gateway retries idempotent. Coordinates in the body (LOC:13.04,80.23, a geo: URI, a Google / OSM / Apple maps link with coordinates, 13.04 N, 80.23 E, a bare 13.0418, 80.2341) locate the incident with location_source: sms (verified); on a threaded message the answer carries location: true (applied), false (held by precedence) or the reason it was refused.
POST/intake/sos{device_id, lat, lon, accuracy_m?, note?, profile{}, event_id?, lang?, location_source?, emergency_types?, cannot_speak?, silent_s?}One-tap SOS with GPS. A fix with accuracy_m above config/locating.yaml network_accuracy_m is a coarse network fix, verified only up to network_verified_max_m. location_source: "manual_pin" = the caller tapped the map (no GPS, or the emergency is elsewhere). A repeat SOS from the same device is a new fix for the open incident (precedence below). event_id makes it idempotent. emergency_types: any of medical, police, fire (default ["medical"]); police / fire are paged at once (agency.requested, actor caller), and a repeat SOS adding one pages it on the open incident. A call whose caller chose only police / fire and whose triage finds no medical finding is held for the dispatcher (pending_approval, flag non_medical_sos) instead of an automatic ambulance. cannot_speak: "timeout" | "button" (with silent_s) = the caller could not talk on the call after the SOS: police and an ambulance are paged to this position at once and the call is flagged silent (policy R15; docs/DISPATCH.md). A phone-number device_id is kept as the caller's number for the location SMS.
POST/intake/voicemultipart: audio file, caller, lat?, lon?, lang?Recorded audio. Server-side Whisper, then the same pipeline.
WS/voice/ws?caller=<id>&lang=ta|en&incident=<id?>see belowReal-time two-way voice call with the AI call-taker.

Intake responses include incident_id. Processing (triage, dispatch) continues in the background; follow it with GET /incidents/{id} or the event stream.

curl -s localhost:8001/api/ops/intake/sms -H 'content-type: application/json' \
-d '{"from":"+919800000001","body":"Appa ku nenju vali, Mylapore tank kitta","lang":"ta"}'

Voice WebSocket protocol​

  • Client → server
    • Binary frames: PCM16 mono 16 kHz audio (send continuously; silence is fine).
    • Text: {"type":"start","lang":"ta","msisdn":"…"} once.
  • Server → client
    • Binary frames: PCM16 mono 16 kHz audio of the agent's voice.
    • Text JSON:
typeMeaning
greeting / prompt / statusA sentence the agent is about to speak (text, lang). status is a proactive dispatch announcement.
transcriptWhat the caller said (Whisper).
listeningThe caller started speaking.
vad{"speaking": false}: the server decided the caller's turn ended.
unclearSpeech was heard but could not be understood (the agent will ask them to repeat).
interruptThe caller talked over the agent: drop any queued agent audio.
incidentIncident summary (id, status, severity, …) after each turn.
errorFatal error text.

Conversation​

MethodPathBodyNotes
GET/incidents/{id}/messages?after=0&channel=text|voiceThe caller conversation. channel=text gives the chat thread only; voice gives the call transcript only; no filter gives both (each message has channel).
POST/incidents/{id}/messages{text}Caller follow-up on the text channel. Re-triages, and the AI replies.
POST/incidents/{id}/reply{text, actor}A human dispatcher writes to the caller (audited).
POST/incidents/{id}/cancel{reason?}The caller cancels. Units stand down and return; status becomes cancelled.
POST/incidents/{id}/caller-location{lat, lon, source=manual_pin|gps|network|link, accuracy_m?, note?}The caller's own location (caller token, or incident.write): a fix from their phone, a pin they dropped or moved ("my location is wrong"), or the /l/<token> location-request page (link). Answer {applied, reason?, source, verified, rerouted[], status, location_label}. Precedence (ops/locating.py): a dispatcher's pin beats everything; a caller's pin / link / SMS coordinates beat the phone's automatic fix and the geocoder; the newest of equals wins. A lower-ranked fix is kept in location_history with applied: false (location.update_held); a caller pin held behind a dispatcher's pin becomes location_review for the dispatcher. Before dispatch it (re)starts dispatch; with units en route and a move over reroute_min_m they are re-routed (unit.rerouted) and the reassignment check runs. Not applied once the crew is with the patient. 409 closed incident, 422 outside the operating area.

Incidents (dispatcher)​

MethodPathBodyNotes
GET/incidents/{id}Full incident: triage, policy, decision, units, messages, vitals, timeline.
GET/incidents/{id}/publicCitizen-safe view: status, step/steps, severity, location, responding unit, eta_sec, route (remaining road [[lat,lon],…]), distance_m, hospital (when transporting), status_text, location_source, location_verified, needs_location (missing or unverified: ask the caller for a pin), crew_contact {callsign, phone} once dispatched and only when the crew set a number. No clinical internals. For a linked call it shows the primary incident's progress, with linked_to.
GET/incidents/{id}/smsText messages sent to the caller (ops/sms_out.py): {gateway, messages[{id, ts, kind, to_number, body, status, simulated, gateway_ref, error}]}. Kinds: dispatched (tracking link /caller?t=<incident>.<caller token>, callsign, crew number), location_request and silent_call (link to /l/<incident>.<caller token>). One per kind per incident. Without VAAZHVU_SMS_URL every message is simulated.
GET/incidents/{id}/fhirFHIR R4 bundle for the incident.
POST/incidents/{id}/approve{actor}Commit the recommendation of an incident in pending_approval. 409 for a call held with a run card (no engine recommendation): use override.
POST/incidents/{id}/override{actor, units[], hospital_id?, reason}Dispatch different units / hospital (audited). For a call held with a manual_runcard, hospital_id defaults to the card's nearest emergency department.
GET/incidents/{id}/runcardManual run card computed now without the dispatch engine (ops/manual.py): the nearest available ambulances by straight-line distance {id, callsign, capabilities, tier, distance_m, has_required} and the nearest emergency departments {id, name, distance_m, cardiac_ready, trauma_ready, *_diversion, er_beds}.
POST/manual-mode{enabled, reason?}Supervisor switch (permission dispatch.manual): while on, every new call is held in pending_approval with manual_runcard (cause manual_mode) and the engine is not consulted; dispatch with override. Survives a restart. Emits ops.manual_mode. When the engine itself raises, the call is held the same way (cause dispatch_engine_down) and ops.degraded names component dispatch_engine until its next good decision (ops.recovered).
POST/incidents/{id}/location{actor, lat, lon}Confirm or correct the location (location_source: dispatcher, beats every other source and clears location_review); re-dispatches if still waiting, re-routes units already driving there. Incidents carry location_source, location_accuracy_m, location_history, and when relevant location_conflict (the place the caller named is far from their phone; the named place is used), location_review and silent_call (no usable speech: kept open, location link texted).
POST/incidents/{id}/resolve{actor, outcome, disposition?, note?}Close the incident; units return. disposition records what the call was (below).
POST/incidents/{id}/disposition{disposition, note?}What the call turned out to be: genuine, duplicate, no_patient, accidental, advice, prank, abusive (GET /dispositions; config/platform.yaml callers). Closes it if still open; a correction replaces the earlier one. Only prank and abusive count against the caller.
POST/incidents/{id}/vitals{hr, spo2, resp_rate, sbp?, dbp?, temp_c?, avpu?, on_oxygen=false, source, captured_at?, ecg?, ecg_hz?}Vitals reading. NEWS2 scores only what was measured (a missing value, AVPU included, is never assumed normal; the result is flagged incomplete); deterioration triggers re-triage / re-optimisation; a FHIR bundle is posted (readings from monitor-sim go as preliminary, tagged simulated, never as real measurements). ecg (≤ 6000 samples, lead II) + ecg_hz keep the latest rhythm strip on the incident. The first reading from a real source (anything but monitor-sim) stops the simulated patient monitor for that incident.
POST/incidents/{id}/link{primary_id, actor}Merge: this call is another caller for primary_id (no second ambulance; its words are added to the primary, which re-triages). 409 if it already has units or linked calls. Calls are also linked automatically (config/dispatch.yaml clustering).
POST/incidents/{id}/unlink{actor}Split a linked call: it becomes its own incident and is dispatched.

Units and fleet​

MethodPathBodyNotes
GET/stateSnapshot: units (position, status, capabilities, agency, tier, offer: the crew's answer to its current job, {incident_id, state, offered_ts, expires_ts, remaining_sec, responded_ts, by, role, reason?}), incidents (summaries, with caller_flag, disposition, tier, offers {unit: state}, manual_hold), traffic, sim time, manual_mode {enabled, reason, by, since, engine_down}.
POST/units/{id}/offer/accept{actor?}The crew accepts the job offered to its unit (unit.status, crew sessions only for their own unit): the unit goes assigned → enroute and drives (unit.accepted). A replay answers changed: false. After the offer expired this is a late acceptance: switch back to this unit only if it arrives late_switch.min_eta_gain_sec sooner and the current unit accepted at most max_progress_sec ago and is not on scene (or has not accepted yet); otherwise state: released (thanks, stays free). unit.late_accept either way. 409 when there is nothing to accept.
POST/units/{id}/offer/decline{reason, actor?}The crew declines (reason: a config/app.yaml decline_reasons id or text): the unit is released (available, not out of service), unit.declined, dispatch.stale, then the engine decides again without every unit that declined or let this job's offer expire (dispatch.reassigned with excluded). No other unit: dispatch.failed and the call goes to the dispatcher (pending_approval, flag no_unit_accepted). An unanswered offer expires after acceptance.timeout_sec (offer.expired, same re-dispatch).
GET/units/{id}/assignmentCrew view: unit; remaining route, distance_m, eta_sec, purpose; the next action; fleet (other ambulances); incident with severity, severity_dist, symptoms, summary, findings (with evidence), ruled_out, patient, news2, vitals (last 60), hospital, team, caller, conversation (last 20, with channel). offer (as in /state; while state: offered, next is null and actions empty: Accept / Decline replace the status button) and late_offer {incident_id, expired_ts, severity, location_label} for a free unit that let an offer expire within late_switch.window_sec. A status step enroute / on_scene on an open offer accepts it first.
POST/units/{id}/status{status, lat?, lon?, note?}Crew workflow; the incident moves with it: enroute→on_scene (receiving hospitals ranked from the scene), on_scene→transporting (drive to hospital starts; a support ambulance taking the patient becomes the transport unit), transporting→at_hospital, at_hospital→idle (handover: incident resolved). Support unit on_scene→idle clears the scene. No job: out_of_service (off duty) / idle (back in service); on a job out_of_service is a breakdown (re-dispatched). Any other step is 409. Once a crew acts, the sim's scene/handover timers no longer move that job.
GET/units/{id}/hospitalsReceiving hospitals for the unit's patient, ranked now from where the patient is: [{id, name, lat, lon, rank, eta_sec, readiness, capable, diverted, why[]}]
POST/units/{id}/destination{hospital_id, reason?}Crew picks the receiving hospital. It sticks until that hospital can no longer take the patient (diversion, an escalation it cannot treat). The old ER gets hospital.released, the new one an alert and FHIR bundle.
POST/incidents/{id}/destination{hospital_id, reason?}The same, for the dispatcher (incident.write).
POST/units/{id}/position{lat, lon, accuracy_m?, speed_mps?, heading_deg?, captured_at?}Live GPS from the crew device (permission unit.status). While fresher than gps.stale_sec (config/fleet.yaml) the simulator stops moving the unit; it arrives when within gps.arrival_m of its target. A replayed fix older than stale_sec or than the last applied one returns applied: false. Units carry position_source: device|sim in /state, the assignment and fleet.positions.
GET / PUT/units/{id}/contact{phone} (PUT; empty clears)The crew's phone number shown to their caller once dispatched (crew_contact in /public, and the dispatch SMS). unit.status: a crew session sets its own unit's. Never prefilled; 8-15 digits, optional +, else 422.
POST/units/{id}/redeploy{actor, zone_id}Move an idle unit to cover a zone.
POST/units/{id}/move{lat, lon, actor}Drive a free unit to any point along the road network (crew taps the map or a hospital). It stays dispatchable while moving. 409 if it is on an incident.
POST/units/{id}/return{actor}A free unit drives back to its base.
POST/units/{id}/fail{reason, actor}Out of service; its incident is re-dispatched (failover).
POST/units/{id}/restore{actor}Back in service.
GET/nearby?lat=&lon=&limit=12&radius_m=The ambulances closest to a citizen (the nearest limit, any distance unless radius_m is given): position, available, ALS, distance, road eta_sec. No crew or incident details.
GET/coveragePer-zone coverage: nearest ALS / any-unit times, demand, gaps; demand_source, forecast_top (zones expecting the most calls next hour), forecast_hour, forecast_recent. coverage.alert recommendations carry reason: "forecast" and reason_text.
GET/metrics/hitlHuman-in-the-loop monitoring (ops/hitl_metrics.py): overall, by_language, by_channel, each with counts and rates of auto / provisional / held, review_rate, hold_timeout_rate, override_rate, median_time_to_dispatch_sec / p90_..., pending_now; outcomes (sensitivity / PPV null until a clinical outcome is recorded, dispositions on record); thresholds.

Hospitals​

MethodPathBodyNotes
GET/hospitalsEmergency-capable hospitals with capabilities, readiness and diversions. Built once per hospital-status change and sent with an ETag; a client with the current copy gets 304.
GET/facilities?south=&west=&north=&east=&limit=300&emergency_only=falseTamil Nadu facilities inside a map viewport: {id, name, name_ta, lat, lon, district, type, receiving, level, cath_lab, trauma}. Receiving (emergency-department) hospitals come first. When the view spans more than 1°, only receiving hospitals are returned.
GET/hospitals/{id}/incomingER board data: inbound patients with ETA, unit location, triage, policy, vitals, alerts, prep checklist, FHIR, and the hospital's record.
POST/hospitals/{id}/status{actor, cardiac_diversion?, trauma_diversion?, er_beds?, load_score?}ER declares capacity. Inbound patients are re-evaluated. Saved in the hospital's record (survives a restart).
GET/hospitals/{id}/recordThe hospital's own record (ops/hospital_records.py): name, location, district, address, phone, level, taei_level (I / II / III / stabilisation / none), capabilities (emergency_department, cardiac_cath_lab, trauma_care, obstetric, paediatric, ct_scan, blood_bank, icu, neurosurgery, burns), er_beds, icu_beds, ventilators, diversions, load_score, note, source (osm / portal), verified. saved: false = nobody has entered it yet (map and profile values).
PUT/hospitals/{id}/recordany of the fields aboveHospital staff enter or correct their hospital; dispatch uses capabilities, diversion and load at once.
migration 8 fieldsstroke_unit, toxicology, anti_snake_venom, scorpion_care (rest of the six pillars + snakebite / scorpion sting; hospital classes of the same name), ownership (government / private / trust / unknown; seeded unverified from OSM operator:type / operator), nk48_empanelled, cmchis_empanelled (true / false, null = not known), helpline_phone; read-only confirmed_at, capacity_reported_at, capacity_reported_by. source may also be onboarding or registry. Protocol fields are data only: using them in hospital selection belongs to the dispatch objective.
GET/hospitals/{id}/record/freshness{saved, last_confirmed, confirm_every_days, due, capacity_reported_at, ...} (config/onboarding.yaml). The ER board shows "Is this still correct?" when due.
POST/hospitals/{id}/record/confirmhospital.write, own hospital only: the record is still correct (confirmed_at). An unsaved map record is stored as shown.

A hospital account is linked to one hospital (operators.hospital_id): /status, /record and /incoming for any other hospital are 403, and an unlinked hospital account can do neither.

ER command interface (backend/app/api_hospital.py)​

All under /api/ops/hospitals/{id}/, with require_hospital. Reading a board needs er.read (hospital accounts for their own hospital; dispatcher, admin, supervisor for any): hospital.read alone (viewer, public) only lists hospitals and reads their records. GET /api/auth/status says er_board: true when the session may open one. A case route answers only for a patient pre-alerted to, arriving at or transferred from this hospital (404 otherwise).

MethodPathPermissionNotes
GETincominger.readNow also: recent[] (arrived awaiting the ER, accepted, released, declined, transferred within recent_window_h), counts, config (config/er_board.yaml), and per row case, queue flags, eta {eta_sec, basis} (to this hospital), eta_freshness, unit, presentation, news2_trend, prep with statuses, prep_summary, latest_alert, since_prealert_sec, handoff.
GETcases/{inc}er.readThe patient view: handoff, identity (unrecorded values null + "not recorded"; caller number masked), presentation, why_assessment {ai, safety}, why_ambulance, why_hospital, why_changed, deterioration, crew, map, eta, vitals, prep, timeline, referrals (with display_state, outreach, transfer), outreach.
POSTcases/{inc}/ackhospital.writeThe ER has seen the pre-alert.
POSTcases/{inc}/declinehospital.write{reason}: this ER cannot receive the patient; it is left out of the patient's ranking and the patient is rerouted. 409 for an IFT destination or a patient no longer coming here.
PUTcases/{inc}/prep/{item}hospital.write{status: not_started|in_progress|ready|not_available|not_required, note?}.
POSTcases/{inc}/accepthospital.write{department, notes?}. 409 before arrival. A simulated ambulance's job resolves (the handover); a crew-driven job stays for the crew's own "handover done".
GETcases/{inc}/ift/candidates?needs=a,ber.readReceiving hospitals: per-need match, diversion, ED status, readiness (same rule as hospital selection), beds, specialists, drive time.
POSTcases/{inc}/iftreferral.write{reason_code (config/er_board.yaml ift_reasons), reason_text?, needs, transport, urgency?, to_hospital?, patient?, notes?} → 201 {case, referral}. Only after arrival.
POSTreferrals/{rid}/redirectreferral.write (the referring hospital){to_hospital, note?} → 201: the same referral sent to another hospital (supersedes / superseded_by). 409 if that hospital already declined.
GETresourceser.readEvery figure with value, ts, source, actor, state (live|recent|stale|none), ed_status, diversions, capabilities (map_estimate until reported), specialists, visible (what hospital selection reads, with readiness per patient type), the last capacity-check call.
POSTresourceshospital.write{changes, note?, source?: er_board|integration}. The one path for live state (ER board by hand, a hospital system with an API key → integration). Fields: counts, cath_lab_available, load_score, diversions, ed_status, ed_status_reason, specialists [{specialty, state}]. Returns affected_inbound.
POSTresources/previewer.read{changes} → {affected: [{id, severity, presentation, eta_sec, readiness_before, readiness_after, can_still_receive}]}; changes nothing.
GETresources/history?field=&limit=er.readField history (hospital_resource_updates).
GETfeed?after=er.readWhat changed for this hospital, newest first, class (clinical / operational / hospital / referral) and action.
GEThistory?days=er.read{cases, actions (audit), resource_changes}.
GETstreamer.readSSE data: {event_type, incident_id, seq} for events concerning this hospital only.

POST /api/onboard/outreach-callback {attempt_id, answered, accept?, reason?} (header X-Vaazhvu-Callback-Secret, the same secret as capacity calls): the outbound voice service reports a call asking an ER to take a patient or a transfer (ops/outreach.py). A yes acknowledges / accepts, a no reroutes / declines.

Accounts and admin​

Sign-in, registration and the signed-in account (api_auth.py; cookie for the web, client: "native" returns a bearer token for iOS):

MethodPathBodyNotes
POST/api/auth/login{username, password, unit_id?, client?}Citizens sign in with their phone number in any format.
POST/api/auth/register{phone, name, password, client?}Citizen self sign-up (rate bucket account: a few per hour per client). Never needed to call for help.
GET/api/auth/meThe account; a citizen's phone and profile; a hospital account's hospital.
PUT/api/auth/me/profile{display_name?, blood_group?, conditions?, allergies?, medications?, emergency_contact_name?, emergency_contact_phone?, language?}Citizens. Every intake they make while signed in carries caller.account_id, their number and this profile to the crew.
GET/api/auth/me/incidentsA citizen's reports with their caller tokens (follow them on any device).
POST/api/auth/me/password{current, password}Every session signs out.
GET/POST/api/ops/operators?kind=staff|citizen / {username, display_name, role, password, hospital_id?}operator.manage. An admin may create the roles in its grants; never citizen (they register).
POST/api/ops/operators/{id}/hospital{hospital_id | null}Link a hospital account. Signs it out.

Admin portal (/admin; api_admin.py):

MethodPathPermissionNotes
GET/admin/summaryany admin permissionAccounts, hospitals, callers at a glance.
GET/hospital-recordshospital.manageEvery record entered so far.
POST/hospitalshospital.manageAdd a hospital the map lacks (id hs_…, source: portal, unverified).
PUT/admin/hospitals/{id}/recordhospital.manageEdit any hospital's record.
POST/hospitals/{id}/verifyhospital.manage{verified}.
GET/dispositionsThe outcomes a dispatcher can record.
GET/callers?status=ok|watch|flaggedcaller.manageCallers by reputation: masked label, counts of genuine / unclear / hoax / abusive, status. Keys are HMACs of the number; the raw number is never stored.
GET/callers/{key}caller.manageOne caller and the outcome of each call.
POST/callers/{key}/statuscaller.manage{status: ok | watch | flagged | auto, note?}. ok clears and counts only later reports.
POST/callers/prunecaller.manage{older_than_days?}: delete closed prank / abuse incidents (and vitals); audit, events and the report stay.
GET/tiersAmbulance tiers with units and available per tier, and severity → least tier.
PUT/tiers/severity/{severity}tier.manage{min_tier, note?}. Can raise a requirement, never lower the safety policy's.
PUT/tiers/{tier}tier.manage{name?, description?}. What a tier requires stays in config/fleet.yaml.

Onboarding, fleet registry and hospital data upkeep (api_onboarding.py; ops/onboarding.py, ops/fleet_sources.py, ops/hospital_checks.py). Public, no sign-in (paths under /api/onboard; the two POSTs use rate bucket onboard):

MethodPathBodyNotes
GET/api/onboard/catalogueUnit types (config/fleet.yaml unit_types), hospital capability columns, ownership values, location mechanisms.
POST/api/onboard/hospital{name, lat, lon, helpline_phone, ownership?, nk48_empanelled?, cmchis_empanelled?, capabilities: {col: bool}, district?, address?, phone?, level?, taei_level?, er_beds?, icu_beds?, note?, contact_name, contact_phone, contact_email?, username, password}201 {id, status: pending, token, username}. Creates the hospital staff account now, disabled and unlinked (username taken → 422). Nothing reaches dispatch.
POST/api/onboard/fleet{operator_name, contact_name, contact_phone, contact_email?, note?, ambulances: [{registration_no, type, capabilities?, base_lat, base_lon, base_name?, crew_phone?, location_mechanism: crew_app|avl|manual}]}201 {id, status: pending, token, ambulances}. Registry rows PV001… stay pending; a registration number already registered or an unknown type → 422.
GET/api/onboard/applications/{id}?token=The applicant's view: {status, reason, created, decided}. Wrong token → 404.
POST/api/onboard/capacity-callback{task_id, outcome: answered|no_answer|failed, er_beds?, icu_beds?, ventilators?, cardiac_diversion?, trauma_diversion?, note?}From the outbound voice service; header X-Vaazhvu-Callback-Secret = VAAZHVU_VOICE_OUTBOUND_SECRET (unset → 503, wrong → 403). An answer updates the hospital record (capacity_reported_by: voice-agent:<task>).

Admin portal (Applications, Fleet and Data checks tabs), under /api/ops:

MethodPathPermissionNotes
GET/onboarding/applications?status=&kind=hospital.manage (hospitals) / fleet.manage (fleets)Pending hospital applications carry matches (mapped hospitals nearby with a similar name).
POST/onboarding/applications/{id}/approvesame{hospital_id?, create_new?}. Hospital: links to hospital_id, else the best match, else adds it (source: onboarding); record verified + confirmed; account linked and enabled. Fleet: creates the fleet operator; ambulances whose type transports patients become live idle ems units (unit.added). 409 once decided.
POST/onboarding/applications/{id}/rejectsame{reason} (the applicant sees it). A hospital's reserved account is deleted (it never signed in).
GET/fleet/unitsfleet.manageEvery ambulance of every source: {id, callsign, source: plan|onboarded|avl, type, capabilities, tier, status, live, enabled, registration_no?, crew_phone?, location_mechanism?} and sources (unit counts, AVL poll state).
POST/fleet/units/{id}/enabledfleet.manage{enabled}: take an idle unit out of the live fleet (unit.removed; it stays out across restarts) or back in. On a call → 409; police / fire → 409.
GET/hospital-records/duehospital.manageStored records due for confirmation.
GET/hospital-checks?status=hospital.manageCapacity-check tasks (due, calling, done, failed, no_phone), counts, outbound (false: staff work the "to call" list).
POST/hospital-checks/schedulehospital.manageCreate tasks for hospitals whose capacity report is older than capacity_checks.stale_hours (the live server also does this every every_min).
POST/hospital-checks/{id}/resulthospital.manageStaff phoned the hospital: {outcome, er_beds?, icu_beds?, ventilators?, cardiac_diversion?, trauma_diversion?, note?}. Only what the hospital said is written.

Traffic, demo, config, events​

MethodPathBodyNotes
POST/traffic{lat, lon, radius_m=300, factor=1000, label, actor}Disruption. factor ≥ 50 means a closure. With OSRM it snaps to the road at that point (model: "road", road_name, snapped, road_bearing in the event and in /state.traffic) and only routes along that road re-plan; without OSRM it is a circle (model: "radius"). A route with no detour has provider osrm+traffic:no-detour.
DELETE/traffic/{tid}Clear it.
GET/demoDemo storylines (config/demo.yaml).
POST/demo/{storyline}Run one (cardiac_mylapore, surge). Step times follow the playback clock.
POST/sim/clock{multiplier?, paused?, actor}Demo playback: speed multiplier from simulation.playback in config/fleet.yaml (422 otherwise) and pause; scales the simulator and demo storylines together. /state.clock shows it.
GET/app/configClient content from config/app.yaml: emergency number, languages, quick phrases, status texts, UI texts.
GET/events?after=<seq>&incident_id=&limit=500Event log page (optionally for one incident).
GET/audit?incident_id=Human actions (approve, override, messages, hospital status, cancel).
GET/llm?incident_id=&operation=&limit=50&window_s=3600analytics.readLLMOps: provider health, whether the local fallback is serving, prompt and config versions, per-operation stats (calls, error and fallback rate, p50/p95, tokens, cost) and the latest traces with one span per provider request. No prompts, caller words, model output or keys. In memory only; Prometheus keeps the history (Monitoring and logs).
GET/streamincident.read or agency.readServer-Sent Events: every event live, each named by its type. ?all=1 sends them unnamed (one message per event, event_type in the JSON), which is what the web views use (frontend/src/live/stream.js) so a new event type is never missed. Resumes without gaps from the Last-Event-ID header or ?after=<seq>.
GET/changes?incident=<id> or ?unit=<id>public for an incident (like /incidents/{id}/public); incident.read for a unitChange pings for one incident or one unit, with no payload: data: {"event_type": …} whenever an event touches it, its linked primary call or its responding unit (positions at most once per position_every_s, default 1). The iOS apps refetch their own endpoint on each ping instead of polling, and never receive another incident's data.
curl -N localhost:8001/api/ops/stream # watch everything happen

MCP and Dispatcher Copilot​

The MCP tools are described in AI access and the Copilot. Neither endpoint can dispatch, approve, override or reroute.

MethodPathBodyNotes
POST/api/mcpJSON-RPC (MCP Streamable HTTP)MCP server: stateless, JSON responses, 14 tools and 2 prompts. An unknown or revoked API key gets 401 before any method runs. The public way in is the mcp-gateway (POST /mcp on :8790, key required; AI access and the Copilot). Tool permissions are those of the request's principal (API key, session or role header). GET / DELETE answer 405, because the server never pushes messages.
POST/api/ops/copilot{messages: [{role: user|assistant, content}], incident_id?} (incident.read)Dispatcher Copilot: one question, answered by the LLM through the MCP tools as this principal. Replies as SSE frames over the POST: data: {"type": "tool_call", id, name, args}, {"type": "tool_result", id, name, ok, ms, simulated, incident_id, error}, {"type": "answer", text, model, offline?}, {"type": "error", error}.
curl -s localhost:8001/api/mcp -H 'content-type: application/json' -H 'accept: application/json, text/event-stream' \
-H 'mcp-protocol-version: 2025-06-18' \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"find_units","arguments":{"place":"Guindy","capability":"ALS"}}}'

Traffic police, missed calls, hotspots​

backend/app/api_field.py; settings in config/field_ops.yaml.

MethodPathPermissionNotes
GET/traffic/corridors?closed=false&limit=100incident.read or agency.readGreen-corridor requests: {id, incident_id, unit_id, callsign, purpose, severity, hospital_id, hospital_name, status: requested|accepted|declined|closed, geometry [[lat,lon]…], eta_sec, distance_m, junctions [{id, name, lat, lon, source: osm_junction|route_turn, offset_m, eta_sec, alerted}], ack?}, plus signals: msiren|simulated and junction_alert_m. Raised automatically when an ambulance starts a leg matching traffic_police.purposes / severities (default: transporting a critical patient); also pages agency traffic on the incident.
POST/traffic/corridorsagency.request{incident_id, unit_id?}: ask for one by hand for the unit's current drive (any severity). 409 when no ambulance on the incident is driving.
POST/traffic/corridors/{id}/ackagency.ack (role traffic or EMS){accepted, officer?, unit?, note?}; a decline needs a note. Also answers the incident's traffic agency request.
GET/traffic/junction-alerts?after=<ts>incident.read or agency.readRecent traffic.junction_alert payloads {corridor_id, incident_id, unit_id, callsign, junction, distance_m, eta_sec, simulated, ts}: one per junction per trip, when the unit is within junction_alert_m (200 m). Forwarded to mSiren when VAAZHVU_MSIREN_URL is set (payload shape ours, unverified against the live system); otherwise simulated: true.
GET/call-attempts?status=abandoned,failed&since=&limit=incident.readVoice-line attempts (ringing, connected, abandoned, failed), newest first: {id, channel, status, caller_masked, callback_number, location?, started_ts, waited_sec, incident_id?, previous_attempts, reason?, callbacks[], called_back} and open_callbacks.
POST/call-attemptsintake.createAn app attempt that never reached the line: {channel, reason, caller{msisdn?, device_id?}, lat?, lon?, started_ts?, waited_sec?} → failed.
POST/call-attempts/{id}/callbackincident.write{outcome: reached|no_answer|busy|wrong_number|not_needed|incident_created, note?}.
GET/hotspots?limit=analytics.readTop grid cells (hotspots.cell_m) from stored incidents and imported crash history: {cell_id, rank, lat, lon, bounds, score, events, incidents, crashes, fatalities, peak_hours, by_hour, by_weekday, by_month, by_season, by_type, by_severity}; recomputed when older than refresh_every_sec. crash_history summarises the imported sources (empty until a file is imported).
POST/hotspots/refreshanalytics.readRecompute now.
GET/hotspots/suggestions?format=json|csvanalytics.readPositioning report for the ambulance service: per hotspot the nearest base and its drive time against the response target (target_met), the nearest free unit, the zone's next-hour forecast and expected coverage, peak hours, dominant season and a suggestion. Advice only.
POST/hotspots/importhotspot.manageMultipart file (iRAD / blackspot CSV, ≤ 1 MiB; larger: scripts/import_irad.py) and source. Columns: Database crash_history.

Clinical records: vitals correction, trip log, ERC consult, referrals, IFT​

backend/app/api_clinical.py (modules vitals/rts.py, vitals/corrections.py, ops/trips.py, ops/consult.py, ops/referrals.py, triage/incident_type.py). All under /api/ops.

MethodPathPermissionNotes
GET/clinical/confignoneVocabularies: incident_types [{id, label, suggested_capabilities}], hospital_services (hospital record columns), ambulance_capabilities, urgencies, helplines, time_norms (draft), ift reserve.
POST/incidents/{id}/vitalsvitals.writeNow also takes gcs (3-15) or all of gcs_eye (1-4), gcs_verbal (1-5), gcs_motor (1-6); a partial or contradictory GCS is 422. Each stored reading gets an id; one with a GCS carries rts ({complete, rts, t_rts, codes, inputs} or {complete: false, missing}), and the incident keeps the newest complete one in rts.
POST/incidents/{id}/vitals/{reading_id}/voidvitals.write (a crew session: its unit must be on the incident){reason}. Marks the reading voided: {ts, by, reason} (kept), refolds NEWS2 and the RTS from the valid readings, re-sends its FHIR Observations as entered-in-error (when FHIR is on), emits vitals.voided. Idempotent (changed: false); 404 for an unknown reading. An escalation the reading caused is not undone. Correction = void + a new reading.
GET/incidents/{id}/tripsincident.read{trips, norms}: one trip per ambulance on the incident (see trip_logs in Database) with km_odometer, km_route (estimate), km, km_source, durations [{interval, label, sec, target_sec, benchmark: within|over|pending|no_norm}], over_norm.
GET/units/{id}/tripincident.read (crew: own unit)The unit's open (or last) trip.
PUT / POST/units/{id}/trip/odometerunit.status (crew: own unit){start?, end?, remark?} in km. 409 when the unit has no trip, the end is below the start or the trip exceeds 2000 km. POST is for outboxes that only POST. Emits trip.updated.
GET/trips?from=&to=&unit=&format=json|csvexport.readTrips dispatched in [from, to) (unix seconds or ISO; default last 7 days). CSV: one row per trip with stage times (region time), durations and benchmarks, odometer, km, destination changes, police / fire remarks, crew remarks.
POST/incidents/{id}/consultconsult.write (crew: unit on the incident){question} → 201, a consult {id, incident_id, unit_id, status, messages, advice}. Emits consult.opened.
GET/incidents/{id}/consultsincident.readConsults on the incident.
GET/consults?status=open|closedconsult.writeThe ERC board: each consult with incident (summary, type, patient, latest valid vitals, NEWS2, RTS, hospital, unit status).
POST/consults/{id}/messagesconsult.write{text, advice?}; advice: true only from the ERC physician (403 for crew). Emits consult.message / consult.advice. 409 once closed.
POST/consults/{id}/closeconsult.write{note?}. Emits consult.closed.
GET/incidents/{id}/referincident.read{eligible, reasons, helplines}: eligible when the policy's effective severity is non-urgent with confidence ≥ non_emergency.min_confidence (config/dispatch.yaml), no red flag or high-risk phrase, triage did not abstain, no crew with the patient.
POST/incidents/{id}/referincident.write{helpline, note?, force?} (force needs a note). Sends the caller the line's message with its number (config/region.yaml helplines), records referred_to, emits incident.referred, closes the call with disposition advice. 409 when not eligible.
POST/referralsreferral.write (a hospital account: from its own hospital only){from_hospital?, to_hospital?, urgency: emergency|urgent|planned, needs [hospital services], transport [ALS|BLS…], incident_type?, patient {summary, diagnosis?, age_years?, sex?}, notes?} → 201. No to_hospital: an open request any hospital whose record has every needs service may accept. Emits referral.requested. Nothing is dispatched yet.
GET/referrals?status=incident.readAll referrals, plus free fleet and the IFT reserve.
GET/hospitals/{id}/referralshospital.read (hospital account: its own){outgoing, incoming, fleet}.
POST/hospitals/{id}/referrals/{rid}/acceptreferral.write (the receiving hospital){note?}. Emergency / urgent: an incident (channel ift, location = the referring hospital, destination = the accepting hospital, locked) is created and dispatched through the normal path; planned: queued until the fleet is above ift.min_free_units / min_free_als (config/fleet.yaml). 409 when this hospital may not answer.
POST/hospitals/{id}/referrals/{rid}/declinereferral.write{note} required. A named request becomes declined; an open one stays open for other hospitals.
POST/hospitals/{id}/referrals/{rid}/cancelreferral.write (the referring hospital)Withdraw before dispatch.

The crew assignment (GET /units/{id}/assignment) also carries incident.incident_type, incident.rts, incident.trip (this unit's trip) and incident.consults; incident summaries (/state, ER board) carry incident_type, rts, referral_id, referred_to. GET /api/config region.helplines lists the helplines.

Every event has {seq, type, ts, source, incident_id, payload}. Types are listed in Architecture.

Core endpoints (/api/*)​

Always mounted: /api/health, /api/config (map tiles, policy thresholds, NEWS2 response bands and per-parameter news2.bands, severities, region), /api/integrations (configured/available flag per integration), /api/asr and /api/translate.

Legacy endpoints (/api/*, VAAZHVU_LEGACY=1 only)​

The original scenario demo: /api/scenarios, /api/scenarios/run, /api/scenarios/run_full_demo, /api/incidents*, /api/optimize/vroom, /api/vitals, /api/redeploy, /api/hospitals/{id}/*, /api/operations/overview and /api/stream. They are not mounted unless the backend starts with VAAZHVU_LEGACY=1 (they return 404 otherwise). Their tests are in tests/legacy/ and build their own app. Any unknown /api/* path returns a problem+json 404, never the web UI.

Platform endpoints​

Collaboration (comments, presence, activity, attachments), sharing, drafts, search, analytics, telemetry, exports, webhooks, API keys, docs, /api/ready and /metrics are documented in Web platform, with conventions shared by every endpoint: problem+json errors, request ids, rate-limit headers, roles and permissions. The live OpenAPI reference is at /docs.