> For the complete documentation index, see [llms.txt](https://horizon-scripts.gitbook.io/horizon-scripts-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://horizon-scripts.gitbook.io/horizon-scripts-docs/horizonmdt/server-exports.md). Agents can also search and read this documentation through its [MCP server](https://horizon-scripts.gitbook.io/horizon-scripts-docs/~gitbook/mcp).

# Server exports

Call server exports from server-side Lua with `exports['HorizonMDT']:ExportName(...)`. Export calls do not grant permission by themselves. The API v1 capabilities, legacy integrations, result contracts and EMS payment confirmation are documented below.

## Stable server API v1

`GetApiVersion()` returns the version string. `GetApiCapabilities()` returns `{ version, exports }`; each descriptor contains `name`, `side`, and the required `access` capability. These two discovery exports are public. Other API v1 operations require the exact calling resource to be listed in `Config.Integrations.PublicApi.AllowedResources`.

### Access configuration

```lua
Config.Integrations.PublicApi = {
    AllowedResources = {
        ['my_dispatch_resource'] = {
            readOfficerStatus = true,
            dispatch = true,
            createBolo = { police = true },
            readBolos = { police = true },
            caseUpdate = { police = true }
        }
    },
    CooldownsMs = {
        dispatch = 1500,
        createBolo = 3000,
        caseUpdate = 1000
    }
}
```

The resource name must match exactly. A capability set to `true` grants access for all agencies; an agency map scopes it. The default allowlist is empty. Grant only the capabilities a trusted server resource needs. Cooldowns apply per calling resource and capability. API v1 writes return `true, result` or `false, reason`; reads return data or `nil, reason`, except `IsOfficerOnDuty`, which returns a boolean.

### Officer status

* `GetOfficerStatus(serverId) -> status | nil, reason` requires `readOfficerStatus`. It validates that the player is online and has a configured MDT job. The returned status includes `source`, `onDuty`, `status`, `job`, `jobLabel`, and, when present, `gradeLabel`, `callsign`, `division`, `operationalStatus`, and `location`.
* `IsOfficerOnDuty(serverId) -> boolean` requires the same capability and is a compact duty check. It returns `false` for an ungranted caller or an invalid/non-officer player; use `GetOfficerStatus` when you need the reason.

```lua
local ok, officer, reason = pcall(function()
    return exports['HorizonMDT']:GetOfficerStatus(source)
end)
if ok and officer and officer.onDuty then
    print(('Officer %s is on duty'):format(officer.callsign or source))
end
```

The `source` must be a current FiveM server ID, not a citizen identifier. The caller resource must be allowlisted even when the player is authorized.

### Dispatch alerts: two different trust models

HorizonMDT does not expose a persistent dispatch-call queue through these exports. The following methods send alert notifications through the MDT's dispatch delivery path; they do not create a case or a stored call record.

#### `CreateOfficerDispatchAlert(serverId, payload)`

Use for an action taken by an actual player. Requires the `dispatch` grant, an online player with a configured MDT job, and the player's current MDT duty state to be on duty. HorizonMDT reads the player's position on the server and ignores caller-supplied coordinates, preventing a client-provided location from being trusted.

#### `CreateDispatchAlert(payload)`

Use for a trusted server resource such as an alarm or another provider. It has no player argument, so the calling resource is responsible for establishing the real-world/gameplay authorization before calling it. The resource must have the `dispatch` grant.

Both methods accept:

| Field                                                               | Contract                                                                                                                                                                                                                                                                                                                                    |
| ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `title`                                                             | Required, trimmed/sanitized, maximum 80 bytes.                                                                                                                                                                                                                                                                                              |
| `message` or `description`                                          | Required, trimmed/sanitized, maximum 220 bytes.                                                                                                                                                                                                                                                                                             |
| `code`                                                              | Optional, maximum 24 bytes, then uppercased; defaults to `DISPATCH`.                                                                                                                                                                                                                                                                        |
| `priority`                                                          | `low`, `normal`, `medium`, `high`, `urgent`, or `critical`; other values become `normal`.                                                                                                                                                                                                                                                   |
| `coords`                                                            | Optional for `CreateDispatchAlert`; ignored for `CreateOfficerDispatchAlert`. Accepts a keyed or indexed three-number table, a FiveM `vector3`, or top-level `x`, `y`, `z`. X/Y are required when coordinates are supplied; missing Z becomes `0`. Values must be finite; absolute X/Y must be at most 10,000 and absolute Z at most 3,000. |
| `details`                                                           | Optional array, at most 8 rows. Each row supports `label`, `value`, and `iconClass`; values are sanitized by the MDT alert formatter.                                                                                                                                                                                                       |
| `titlePrefix`                                                       | Optional display prefix, maximum 40 bytes.                                                                                                                                                                                                                                                                                                  |
| `duration`                                                          | Optional alert duration in milliseconds, clamped to 1,000–30,000. If omitted, uses `Config.PoliceAlerts.DefaultDuration` (then 9,000).                                                                                                                                                                                                      |
| `policeBlip`, `robberyBlip`, `vehicleBlip`                          | Optional booleans. A map blip requires coordinates and still follows the MDT's configured alert-type rules.                                                                                                                                                                                                                                 |
| `blipDuration`, `blipSprite`, `blipColor`, `blipAlpha`, `blipScale` | Optional overrides for supported blips. Bounds: duration 1,000–600,000 ms, sprite 0–1,000, color/alpha 0–255, scale 0.1–5.0.                                                                                                                                                                                                                |
| `id`                                                                | Optional sanitized alert ID. It is not an idempotency key.                                                                                                                                                                                                                                                                                  |
| `externalId` or `callId`                                            | Optional correlation ID stored in alert metadata; it does not create or link a persistent call.                                                                                                                                                                                                                                             |

A successful result is `true, { alert = normalizedAlert, recipients = count }`. If no eligible recipients exist, the API returns `false, 'no_recipients'`. Other common errors are `not_allowed`, `officer_not_on_duty`, `player_not_found`, `invalid_coords`, `coords_out_of_range`, `coords_required_for_blip`, `invalid_duration`, `cooldown`, and `dispatch_error`.

Use `vector3` for a position: FiveM's `GetEntityCoords` returns this type. `vector4` includes a fourth `w` component for orientation; dispatch alerts do not use heading, so pass `vector3(v4.x, v4.y, v4.z)` or a three-component table instead. See [FiveM vector3](https://docs.fivem.net/docs/scripting-reference/runtimes/lua/functions/vector3/) and [vector4](https://docs.fivem.net/docs/scripting-reference/runtimes/lua/functions/vector4/).

Use `vector4` only for a point whose heading/orientation is meaningful, such as a spawn or interaction point. `GetTabletLocation` returns a keyed table `{ x, y, z, w }` and normalizes a missing heading to `0.0`; its fallback accepts keyed coordinates with optional `w`, `heading`, or `h`. Dispatch and sound positions are 3D locations and accept `vector3` or keyed `{ x, y, z }` tables, not `vector4`. The legacy `SendPoliceAlert` expects table-shaped coordinates; use the API v1 dispatch export when passing a native `vector3`.

```lua
-- Trusted resource integration: use only after its own alarm validation.
local callOk, success, result = pcall(function()
    return exports['HorizonMDT']:CreateDispatchAlert({
        title = 'Store robbery',
        message = 'Silent alarm activated',
        code = '10-31',
        priority = 'high',
        coords = vector3(100.0, 200.0, 30.0), -- or { x = 100.0, y = 200.0, z = 30.0 }
        policeBlip = true,
        externalId = 'shop-alarm:store-12:0004'
    })
end)
if not callOk then
    print('HorizonMDT resource is unavailable')
elseif not success then
    print(('Alert rejected: %s'):format(result))
else
    print(('Alert sent to %s officers'):format(result.recipients))
end
```

```lua
-- Player-bound alert from a server command/event after validating its source.
local callOk, success, result = pcall(function()
    return exports['HorizonMDT']:CreateOfficerDispatchAlert(source, {
        title = 'Officer needs backup',
        message = 'Requesting another unit.',
        code = '10-78',
        priority = 'high'
    })
end)
if not callOk then
    print('HorizonMDT resource is unavailable')
elseif not success then
    print(('Alert rejected: %s'):format(result))
end
```

### BOLOs and case updates

* `CreateBolo(payload) -> true, { id, caseNumber, agency } | false, reason` requires `createBolo` for `payload.agency` (defaults to `police`). `title` (maximum 140 bytes) and `summary` or `description` (maximum 4,000 bytes) are required. Optional fields: `priority` (`low`, `normal`, `high`, `urgent`; invalid values become `normal`), `severity` (`low`, `medium`, `high`, `critical`; invalid values become `low`), `division` (80 bytes maximum), and `location` (255 bytes maximum). The case is stored as an open BOLO with an initial visible system update. Normal MDT BOLO expiry rules still apply.
* `GetActiveBolos(agency, limit) -> array | nil, reason` requires `readBolos` for that agency. Limit defaults to 50 and is bounded to 1–100. Rows contain `id`, `caseNumber`, `title`, `summary`, `status`, `priority`, `severity`, `agency`, optional `division`/`location`, `reportedAt`, and `createdAt`.
* `AddCaseUpdate(caseIdOrCaseNumber, payload) -> true, { id, caseNumber, agency } | false, reason` requires `caseUpdate` for the case's agency. The reference is a numeric case ID or case number (maximum 64 bytes). `note` or `message` is required (maximum 4,000 bytes); `title` is optional (maximum 140 bytes). The update is visible in the MDT and attributed to the calling resource.

```lua
local callOk, success, bolo = pcall(function()
    return exports['HorizonMDT']:CreateBolo({
        agency = 'police',
        title = 'Wanted vehicle',
        summary = 'Blue Sultan last seen leaving Vespucci.',
        priority = 'high',
        severity = 'medium',
        location = 'Vespucci Boulevard'
    })
end)
if callOk and success then
    pcall(function()
        return exports['HorizonMDT']:AddCaseUpdate(bolo.caseNumber, {
            title = 'Vehicle sighting',
            note = 'A unit reported a matching vehicle.'
        })
    end)
end
```

## Existing server exports

These exports predate API v1 and keep their current signatures for compatibility. They are server-only, and some rely on the caller to be a trusted server resource rather than checking an allowlist. Do not forward them from an unvalidated client event.

| Export                                                                                      | Arguments and result                                                                                                   | Purpose / access notes                                                                                                                                                                                                                                                                                                                                                         |
| ------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `SendPoliceAlert(payload)`                                                                  | `true, { alert, recipients }` or `false, reason`                                                                       | Legacy alert notification entry point. It does not have the API v1 resource allowlist/cooldown, and its coordinates must be a keyed table. Prefer `CreateDispatchAlert`.                                                                                                                                                                                                       |
| `NotifyPlayer(serverId, payload)`                                                           | `true, { target, notification }` or `false, reason`                                                                    | Sends one player's notification. Payload fields: `title` (80 bytes), `message`/`description`/`text` (220 bytes), `type` (`info`, `inform`, `success`, `warning`, `error`, `primary`, `blue`), `duration` (1,000–30,000 ms), and up to 8 `details`. Caller must be trusted.                                                                                                     |
| `GetMDTFines(serverId)`                                                                     | `{ ok=false, error, detail? }` or `{ ok=true, fines, pendingTotal, canManageTreasury, treasuryBalance, transactions }` | Reads the framework character's fines. Each fine has `id`, `amount`, `reason`, `notes`, `status`, `articles`, `officerName`, `issuedAt`, and `paidAt`. Treasury transactions are returned only when the player has manager permission. Does not independently check Police MDT access; authorize both caller and target in a trusted integration.                              |
| `PayMDTFine(serverId, fineId)`                                                              | Result table; success adds `paid` and `bank`, failures include `error`                                                 | Pays only a pending fine belonging to that player's character. Common errors: `fines_not_ready`, `invalid_fine`, `fine_busy`, `player_not_found`, `fine_not_found`, `fine_already_paid`, `insufficient_funds`, and `fine_payment_failed`.                                                                                                                                      |
| `WithdrawMDTFineTreasury(serverId, amount)`                                                 | Result table; success adds `withdrawn` and `bank`, failures include `error`                                            | Requires the online player to pass treasury manager permission checks. Common errors: `invalid_amount`, `treasury_busy`, `not_authorized`, `insufficient_treasury`, and `payment_failed`.                                                                                                                                                                                      |
| `Play3DSound(payload)`                                                                      | `true, soundId` or `false, reason`                                                                                     | Sends sound to players in range. `payload.coords` is `vector3` or keyed `{x,y,z}`. Provide `file`/`url` when the configured provider supports file playback, or both `soundName` and `soundSet` (required by the native provider). Volume, distance and duration are clamped by audio config. No API v1 allowlist is applied, so only trusted server resources should call it. |
| `Stop3DSound(soundId)`                                                                      | `true, 'stopped'` or `false, reason`                                                                                   | Stops an active sound. Only the resource that started it can stop it.                                                                                                                                                                                                                                                                                                          |
| `IsJailed(serverId)` / `GetRemainingSentence(serverId)`                                     | boolean / remaining seconds                                                                                            | Reads the prison state for a server player ID. Missing players or sentences resolve to `false` / `0`.                                                                                                                                                                                                                                                                          |
| `ReduceSentence(serverId, seconds, reason)` / `IncreaseSentence(serverId, seconds, reason)` | remaining seconds, `0` if released, or `false` if no active player sentence                                            | Adjusts sentence time through the prison module. These exports do not perform a manager permission check; call only from a trusted server integration after authorizing the action. `reason` is added to sentence notes when supplied.                                                                                                                                         |
| `GetTabletLocation(key, fallback)`                                                          | `{ x, y, z, w }` or `nil`                                                                                              | Reads one configured/admin-managed point. If no saved value exists, it normalizes `fallback`; heading may be supplied as `w`, `heading`, or `h` and defaults to `0.0`.                                                                                                                                                                                                         |
| `GetTabletLocationsByCategory(category)`                                                    | array of location definitions                                                                                          | Lists definitions for a department or category. Each row includes `key`, `category`, `labelKey`, `group`, and `type`; `coords` and fields such as `featureEnabled`, `blip`, `index`, or `photoKind` appear when relevant. `coords` is a keyed table and may be absent for feature-only rows.                                                                                   |
| `IsGroundDropExcluded(itemName, prop)`                                                      | boolean                                                                                                                | Checks item/prop names or hashes against `Config.GroundDropCleanup.ExcludedProps`; intended for a ground-drop cleanup integration.                                                                                                                                                                                                                                             |
| `CompleteOfficerHire(serverId, token)` / `CancelOfficerHire(serverId, token)`               | `true, { success, officer? }` or `false, { message }`                                                                  | Completes/cancels a pending hire for the exact target server ID and server-issued token. These are trusted server-side helpers; do not expose them through an unvalidated client event.                                                                                                                                                                                        |
| `DeleteCharacterData(identifier)`                                                           | number (`1` if the MDT citizen row was deleted, otherwise `0`)                                                         | Removes the MDT citizen row and selected linked legacy data for permanent character deletion. Use only from a trusted character-deletion server hook after validating the identifier.                                                                                                                                                                                          |

### 3D sound example

```lua
local callOk, success, soundId = pcall(function()
    return exports['HorizonMDT']:Play3DSound({
        coords = vector3(100.0, 200.0, 30.0),
        soundName = 'NAV_UP_DOWN',
        soundSet = 'HUD_FRONTEND_DEFAULT_SOUNDSET',
        volume = 0.6,
        distance = 35.0,
        duration = 8000
    })
end)
if callOk and success then
    SetTimeout(3000, function()
        pcall(function() exports['HorizonMDT']:Stop3DSound(soundId) end)
    end)
end
```

## EMS medical billing export

`MarkMedicalInvoicePaid(invoiceId, paymentReference) -> boolean, reason?` is a **server export** for a billing resource that has already verified and committed payment. Add that resource's exact name to `Config.MedicalBilling.TrustedPaymentResources`; the default list is empty. `paymentReference` must be a nonempty, unique reference from the payment provider. The export changes only a pending invoice to paid and returns `true` only for that transition. It returns `false, reason` for an untrusted caller, invalid confirmation, or an invoice that is not pending. This export is separate from API v1 discovery and grants, and must not be forwarded from an unauthenticated client event.

```lua
-- Server-side, after your billing resource confirms that payment succeeded.
local paid, reason = exports['HorizonMDT']:MarkMedicalInvoicePaid(invoiceId, receiptId)
if not paid then print(('Medical invoice confirmation failed: %s'):format(reason)) end
```

For creating invoices from the tablet, configuring ESX/QB-Core/Qbox adapters, and understanding the duplicate-service guard, see [EMS patients and billing](https://horizon-scripts.gitbook.io/horizon-scripts-docs/horizonmdt/ems-patients-and-billing.md).
