@cosyte/mllp
HL7 v2 over MLLP for Node.js, with framing, ACK correlation, and reconnects handled for you.

An MLLP client and server for Node.js: the transport-only sibling to @cosyte/hl7.
Contents
- Why this exists
- Status
- Install
- Usage
- API
- Compatibility
- Documentation
- Support
- Security
- Contributing
- Trademarks
- License
Why this exists
HL7 v2 interfaces still move over MLLP, and the protocol stops at the frame: VT + payload + FS + CR
and nothing else. Everything that decides whether an interface survives a bad night is left to the
integrator, so every team writes the same acknowledgment correlator, the same reconnect loop, and the
same backpressure guard, and one of them is subtly wrong. The nearest alternative is a full
integration engine such as Mirth Connect, which brings a runtime, a database, and a deployment story
you may not want inside a Node.js service. @cosyte/mllp is that transport on its own: a library you
import, with zero runtime dependencies, an in-memory transport so your tests never open a socket, and
one guarantee it will not trade away, which is that a positive acknowledgment cannot precede a
durable commit.
Status
This README describes the 0.1 line. The public API is settled and safe to depend on: the client, the
server, the framing codec, the in-memory transport, and the optional ack-from-hl7 bridge are what
this release commits to. The stable warning codes and security-warning codes are part of that
surface, so renaming or removing one is a breaking change.
Named rather than implied, here is what is still moving:
- Batch acknowledgment is not built. An HL7 batch envelope (
FHS/BHS, HL7 v2.5.1 §2.10.3) or
a frame carrying more than one MSH yields a warned, non-positive AE. That is deliberate, since
a positive acknowledgment correlated to the first message would tell the sender a whole batch was
accepted while the rest went unread, but it means the surface that would carry batch support does
not exist yet.
- Verified engine coverage is a growing list, not a complete one. The differential harness runs
against freely available engines only. See Compatibility for who is in it and who
is not.
- MLLP Release 2 is not spoken, and no option selects it.
Install
pnpm add @cosyte/mllp
# optional peer, needed only for the ack-from-hl7 subpath
pnpm add @cosyte/hl7
Node.js 22 or later, tested on 22, 24, and 26 (engines.node is >=22.0.0). The package ships
dual ESM (import) and CommonJS (require) builds, each with its own type declarations, and has
zero runtime dependencies. The optional @cosyte/mllp/arbitraries entry point, fast-check
generators for
property-testing your own code,
needs fast-check installed beside it; the main entry point never loads it.
Usage
Start a server, send it a message, and read the acknowledgment it built. Auto-ACK is on by default,
and the server awaits your handler, which is the durable commit step, before it answers. The payload
API is Buffer-first everywhere: HL7 v2 messages are raw bytes with caller-managed charset decoding.
import { createStarterClient, createStarterServer } from "@cosyte/mllp";
const committed: Buffer[] = [];
// Port 0: the OS picks a free port. The host defaults to loopback, 127.0.0.1.
const server = await createStarterServer({
port: 0,
onMessage: async (payload) => {
committed.push(payload); // your durable commit: a throw here answers AE, never AA
},
});
const client = await createStarterClient({ host: "127.0.0.1", port: server.getStats().port ?? 0 });
const ack = await client.send(
Buffer.from(
"MSH|^~\\&|SENDING_APP|SENDING_FAC|RECEIVING_APP|RECEIVING_FAC|20260101120000||ADT^A01|CTRL0001|P|2.5.1\r",
),
);
// Log the shape of the acknowledgement, never its field values.
const msa = ack
.toString("utf8")
.split("\r")
.find((segment) => segment.startsWith("MSA|"))
?.split("|");
const code = msa?.[1];
console.log("acknowledgement code:", code);
console.log("MSA-2 echoes the control id sent:", msa?.[2] === "CTRL0001");
console.log("messages committed:", committed.length);
await client.close();
await server.close();
acknowledgement code: AA
MSA-2 echoes the control id sent: true
messages committed: 1
MSA-2 echoes the control id you sent, byte for byte, which is what lets the client match the answer
to the message. The acknowledgment's own MSH-7 and MSH-10 change on every run.
Framing on its own
encodeFrame and FrameReader are exported so you can frame and unframe without a socket. The
reader is a stateful decoder: feed it whatever TCP hands you, and complete frames fire on onFrame.
import { encodeFrame, FrameReader } from "@cosyte/mllp";
const payload = Buffer.from(
"MSH|^~\\&|SENDING_APP|SENDING_FAC|RECEIVING_APP|RECEIVING_FAC|20260101120000||ADT^A01|CTRL0001|P|2.5.1\r",
);
const frame = encodeFrame(payload);
console.log(frame.subarray(0, 3).toString("hex"), frame.subarray(-2).toString("hex"));
console.log("frame", frame.length, "payload", payload.length);
const reader = new FrameReader({
onFrame: (bytes, byteOffset, warnings) => {
console.log("onFrame at", byteOffset, bytes.length, "bytes,", warnings.length, "warnings");
},
});
reader.push(frame.subarray(0, 10)); // partial chunk: nothing fires
reader.push(frame.subarray(10)); // completes the frame
0b4d53 1c0d
frame 105 payload 102
onFrame at 0 102 bytes, 0 warnings
0b is the leading VT, 1c0d the trailing FS CR, and the three framing bytes are the whole
difference between 105 and 102.
The commit contract
A positive acknowledgment (AA) tells the sender "you may forget this message. I have it." So a
receiver must never send one before the message is durably handled, or the message is silently lost.
@cosyte/mllp makes that structural: pair autoAck: 'AA' with an onMessage handler and the server
awaits your handler and only then acknowledges.
Handler resolves, you get AA, unless the inbound could not carry a correlatable positive
acknowledgment (no readable MSH, an empty MSH-10, or a batch or concatenated payload). In that
case the commit still happened, but the acknowledgment is downgraded to AE and a nack event names
the reason, because a positive acknowledgment the sender cannot match is one it will resend. A frame
with a stray VT or FS inside it never reaches your handler: it is refused whole with a coded
error and the connection closes. Handler throws, you get AE, or AR via MllpAckError.
autoAck: 'AA' without a handler is documented as a transport-accept: "received and framed", not
"processed".
Transport security (MLLPS)
TLS is built on node:tls: no bundled TLS, no extra dependency. Certificate verification is on by
default, the server binds 127.0.0.1 by default, and binding all interfaces needs an explicit
allowWildcardBind: true.
import { createServer, createClient } from "@cosyte/mllp";
// Server: mutual TLS (IHE ATNA ITI-19)
const server = createServer({
tls: { cert: certPem, key: keyPem, ca: clientCaPem, clientAuth: "MUST" },
});
await server.listen(2575, "127.0.0.1");
// Client: verify the peer, and present a certificate of our own
const client = createClient({
host: "mllp.example.com",
port: 2575,
tls: { ca: caPem, cert: clientCertPem, key: clientKeyPem },
});
The TLS guide has the ClientAuth
table, the TLS 1.2 floor (IHE ATNA ITI-19), the typed failure modes (tls-verify against
tls-handshake), and the bind-safety details.
API
Four code subpaths ship, plus @cosyte/mllp/package.json:
@cosyte/mllp is the whole transport: createServer and createStarterServer, createClient
and createStarterClient, encodeFrame and FrameReader, Connection, buildRawAck, the typed
errors, and the differential harness (runDifferential).
@cosyte/mllp/testing is InMemoryTransport, a deterministic socket-free test double. Every
test that can run over it should.
@cosyte/mllp/ack-from-hl7 builds acknowledgments from a parsed message, or from raw bytes it
parses through the peer, and is the one place the optional @cosyte/hl7 peer is needed.
@cosyte/mllp/arbitraries is fast-check generators for property-testing code you build on
the transport: payload, frame, chunked and stream for canonical bytes, messyStream for
the framing quirks a lenient reader accepts, and hostileInput for streams a reader may refuse
but must never hang or crash on. It needs the optional fast-check peer, and imports nothing
from the library at run time.
What comes with them:
- Strict framing (
VT + payload + FS + CR), acknowledgment correlation, auto-reconnect with
backoff, and backpressure.
- A lenient decoder and a strict encoder (Postel's Law) with 11 stable warning codes carrying
byte offsets. Tolerance is opt-in per flag; the server ships tolerant defaults.
- An explicit 6-state connection machine
(
CONNECTING | CONNECTED | DRAINING | RECONNECTING | DISCONNECTED | CLOSED) with stateChange
events, never socket flags.
AbortSignal on every awaitable and Symbol.asyncDispose on every closeable.
- A drain on
close() that tells a message which was never written apart from one whose fate is
unknown, because only one of those is safe to resend.
- Zero runtime dependencies. Node stdlib only.
The full reference is on docs.cosyte.com/mllp; see Documentation.
Compatibility
- Node.js 22 or later, tested on 22, 24, and 26.
engines.node is >=22.0.0.
- HL7 v2 payloads are bytes here, and the exceptions are named. The transport does not parse
HL7: it reads the
MSH header its acknowledgment is built from, and the MSA of an inbound
acknowledgment, each bounded at that segment's own terminator. The opt-in ack-from-hl7 subpath
is the one place a whole message is parsed. PHI and safety sets all of that out
in full. For actual parsing, pair this with @cosyte/hl7, which
is exactly what that subpath does.
- Framing checked against canonical frames for freely available engines: Mirth Connect from
NextGen, and the Google Cloud Healthcare MLLP adapter. The frames are written from the
specification, not captured from a running engine, and no live engine runs in our CI. Epic and
Cerner are not part of that harness, and no claim about either is made here.
runDifferential ships in the published artifact, so you can aim
it at your own test or staging endpoint and get a per-exchange frame-parity and MSA-2 correlation
report for the engine you actually integrate with.
- Known gaps, stated rather than hidden. No batch acknowledgment, no MLLP Release 2, no persistent
queue of unacknowledged messages, no clinical acceptance decision, and no PKI. The
known limitations page is
the full list. Read it before you depend on this.
Documentation
The full reference lives at docs.cosyte.com/mllp, built from this
repository's docs-content/. Every page
is listed here, in the order and the groups of the site's sidebar:
Support
Questions, bug reports, and interoperability findings start on the
issue tracker, and so does any change large enough to want
agreement on the approach before a pull request. The organization's
support page covers questions that span our
libraries.
Need an MLLP integration built, or hosted and run for you? See our
integration services.
Security
Report a vulnerability privately, as the
security policy describes, never in a
public issue.
PHI and safety
An MLLP frame carries an HL7 v2 message, and an HL7 v2 message carries patient data. This package is
the transport under that traffic, so what it does with those bytes is a safety property rather than a
footnote.
What it does with your payload. It moves the buffer you hand it to the peer and hands the peer's
bytes back to your handler. It holds a message in memory only while that message is in flight: from
send() until its acknowledgment is correlated, or until close() drains it or reports it
unresolved. On the receive side your handler is given a copy. A frame that arrived across reads was
gathered in the decoder's internal accumulator, which is never zeroed: a frame of up to 4 KiB stays
in that private buffer until a later frame overwrites it, for as long as that reader lives, and the
buffer that held a larger one is dropped once the frame is delivered and left to the garbage
collector. That is buffer reuse rather than storage, and no public API hands the buffer out, but it
is not a scrub.