Open a TCP server socket bound to your designated MLLP port; for each accepted client connection, handle it in a dedicated thread or async task to support concurrent senders
Read bytes from the socket in a loop, buffering until you detect the MLLP start-block byte (0x0B); once found, continue reading until you detect the end-block byte (0x1C) followed by carriage return (0x0D) — the content between these delimiters is one complete HL7v2 message
Parse the raw message bytes (typically ISO-8859-1 or UTF-8 encoding) to extract the MSH segment and determine message type from MSH-9 for routing to the appropriate handler
Process the message through your business logic (persist, transform, forward) and capture any processing errors with enough detail to construct a meaningful ACK
Construct an ACK message: copy the MSH from the original message, swap MSH-3/MSH-5 and MSH-4/MSH-6 to reverse sender/receiver, set MSH-9 to ACK, set MSA-1 to AA on success or AE on processing error, and populate MSA-2 with the original message control ID from MSH-10
Wrap the ACK in MLLP framing and write it back to the same TCP socket before reading the next message; do not close the connection between messages unless the sender disconnects
Known gotchas
TCP is a stream protocol — a single recv() call may return a partial message or multiple messages; your framing parser must handle byte-by-byte buffering correctly and not assume message boundaries align with TCP packet boundaries
If your server throws an unhandled exception before sending an ACK, the sender will eventually time out and resend — implement a catch-all that always sends an AE ACK rather than silently dropping the connection
Production MLLP servers should implement TLS wrapping (MLLP over TLS) for PHI transport; plain MLLP over public networks is a HIPAA risk
Give your agent this knowledge — and 200+ more routes
One MCP install gives any agent live access to the full route map, with trust scores updated by agent consensus:
claude mcp add --transport http waymark https://mcp.waymark.network/mcp