@cosyte/cli 0.0.5 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +416 -0
- package/README.md +111 -45
- package/dist/bin/cosyte-mcp.cjs +461 -106
- package/dist/bin/cosyte-mcp.cjs.map +1 -1
- package/dist/bin/cosyte-mcp.mjs +461 -106
- package/dist/bin/cosyte-mcp.mjs.map +1 -1
- package/dist/bin/cosyte.cjs +824 -140
- package/dist/bin/cosyte.cjs.map +1 -1
- package/dist/bin/cosyte.mjs +825 -141
- package/dist/bin/cosyte.mjs.map +1 -1
- package/dist/index.cjs +592 -102
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +515 -281
- package/dist/index.d.ts +515 -281
- package/dist/index.mjs +574 -104
- package/dist/index.mjs.map +1 -1
- package/dist/io-C9bSG2zF.d.cts +381 -0
- package/dist/io-C9bSG2zF.d.ts +381 -0
- package/dist/mcp.cjs +435 -103
- package/dist/mcp.cjs.map +1 -1
- package/dist/mcp.d.cts +70 -9
- package/dist/mcp.d.ts +70 -9
- package/dist/mcp.mjs +435 -103
- package/dist/mcp.mjs.map +1 -1
- package/package.json +61 -37
- package/dist/io-B2EobRzC.d.cts +0 -57
- package/dist/io-B2EobRzC.d.ts +0 -57
package/dist/mcp.mjs
CHANGED
|
@@ -6,27 +6,35 @@ import { parseArgs } from 'util';
|
|
|
6
6
|
// src/mcp/server.ts
|
|
7
7
|
|
|
8
8
|
// src/core/version.ts
|
|
9
|
-
var VERSION = "0.0
|
|
9
|
+
var VERSION = "0.1.0";
|
|
10
10
|
|
|
11
11
|
// src/core/exit-codes.ts
|
|
12
12
|
var EXIT = {
|
|
13
13
|
/** Success: the operation completed; `validate` found the input **valid**. */
|
|
14
14
|
OK: 0,
|
|
15
|
-
/** Operation-level failure: `validate` found the input **invalid** (parseable but non-conformant)
|
|
16
|
-
* a real, expected CI signal that the
|
|
17
|
-
* unparseable input (that is `DATAERR`). */
|
|
15
|
+
/** Operation-level failure: `validate` found the input **invalid** (parseable but non-conformant),
|
|
16
|
+
* or `redact` could not de-identify every locus: a real, expected CI signal that the tool worked
|
|
17
|
+
* and the operation did not complete. Never emitted for unparseable input (that is `DATAERR`). */
|
|
18
18
|
INVALID: 1,
|
|
19
|
-
/** Usage error: unknown command, bad flag, missing argument
|
|
19
|
+
/** Usage error: unknown command, bad flag, missing argument. A value specific to this CLI, not a
|
|
20
|
+
* `sysexits.h` constant. */
|
|
20
21
|
USAGE: 2,
|
|
21
22
|
/** Data error: input could not be parsed or its format could not be detected (`EX_DATAERR`). */
|
|
22
23
|
DATAERR: 65,
|
|
23
24
|
/** No input: the named file does not exist or is unreadable (`EX_NOINPUT`). */
|
|
24
25
|
NOINPUT: 66,
|
|
25
|
-
/** Unavailable: a required capability is not
|
|
26
|
-
*
|
|
26
|
+
/** Unavailable: a required capability is not wired for this input (e.g. `redact` on a format
|
|
27
|
+
* `@cosyte/deid` has no adapter for, or with that optional library absent), a distinct non-zero
|
|
28
|
+
* signal that is never a fake success (`EX_UNAVAILABLE`). */
|
|
27
29
|
UNAVAILABLE: 69,
|
|
28
30
|
/** Internal error: an unexpected exception (a bug), distinct from a handled bad input (`EX_SOFTWARE`). */
|
|
29
|
-
SOFTWARE: 70
|
|
31
|
+
SOFTWARE: 70,
|
|
32
|
+
/** Output error: the stream the CLI was writing to closed before the output had been delivered, so
|
|
33
|
+
* the consumer holds nothing or holds only part of the answer. The shape a downstream consumer
|
|
34
|
+
* that exits early produces (a pager quit, a `head` that has seen enough). A handled condition the
|
|
35
|
+
* consumer owns, never a defect in the CLI, so it is deliberately distinct from `SOFTWARE`
|
|
36
|
+
* (`EX_IOERR`). */
|
|
37
|
+
IOERR: 74
|
|
30
38
|
};
|
|
31
39
|
|
|
32
40
|
// src/core/diagnostics.ts
|
|
@@ -50,9 +58,27 @@ var CLI_CODES = {
|
|
|
50
58
|
CLI_PARSER_UNAVAILABLE: "CLI_PARSER_UNAVAILABLE",
|
|
51
59
|
/** The wrapped parser rejected the input. Positional context only, never the offending bytes. Exit `65`. */
|
|
52
60
|
CLI_PARSE_FAILED: "CLI_PARSE_FAILED",
|
|
53
|
-
/**
|
|
54
|
-
*
|
|
61
|
+
/** The input is larger than the documented size limit the CLI reads in one invocation. Raised
|
|
62
|
+
* against the running byte count while the input is read, so the refusal always arrives before an
|
|
63
|
+
* allocation ceiling could. Names the limit, never the input. Exit `65`, never `70`. */
|
|
64
|
+
CLI_INPUT_TOO_LARGE: "CLI_INPUT_TOO_LARGE",
|
|
65
|
+
/** The output stream could not be written: a consumer that closes the pipe ends the invocation
|
|
66
|
+
* here rather than as an unhandled platform error, whether it went away part way through a record
|
|
67
|
+
* stream or before a single-result write was delivered. Names no input, and never the platform's
|
|
68
|
+
* own error text. Exit `74`. */
|
|
69
|
+
CLI_OUTPUT_WRITE_FAILED: "CLI_OUTPUT_WRITE_FAILED",
|
|
70
|
+
/** The BYO ConceptMap supplied to `map-codes` is not valid JSON or not a loadable FHIR ConceptMap.
|
|
71
|
+
* Names the stable terminology-loader code, never the map's bytes. Exit `65`. */
|
|
72
|
+
CLI_MAP_INVALID: "CLI_MAP_INVALID",
|
|
73
|
+
/** A command whose ground-layer library does not cover the resolved format (e.g. `redact` on a
|
|
74
|
+
* format `@cosyte/deid` ships no adapter for). Never a fake success: a distinct, value-free
|
|
75
|
+
* "unavailable" signal. Exit `69`. */
|
|
55
76
|
CLI_NOT_IMPLEMENTED: "CLI_NOT_IMPLEMENTED",
|
|
77
|
+
/** The delegated de-identifier reported that it could not handle every element of the input (a
|
|
78
|
+
* fail-closed `blocked` locus, or its own fatal). The run is **not** a de-identified copy, so no
|
|
79
|
+
* output is emitted: an operation-level failure, never a bug. Names loci and codes, never a
|
|
80
|
+
* value. Exit `1`. */
|
|
81
|
+
CLI_DEID_INCOMPLETE: "CLI_DEID_INCOMPLETE",
|
|
56
82
|
/** An unexpected internal error (a bug). Exit `70`. */
|
|
57
83
|
CLI_INTERNAL: "CLI_INTERNAL"
|
|
58
84
|
};
|
|
@@ -90,7 +116,8 @@ function toCliError(err) {
|
|
|
90
116
|
}
|
|
91
117
|
|
|
92
118
|
// src/core/format.ts
|
|
93
|
-
var
|
|
119
|
+
var DETECT_PREFIX_BYTES = 512;
|
|
120
|
+
var SNIFF_BYTES = DETECT_PREFIX_BYTES;
|
|
94
121
|
function leadingText(bytes) {
|
|
95
122
|
const slice = bytes.subarray(0, SNIFF_BYTES);
|
|
96
123
|
let text = new TextDecoder("utf-8", { fatal: false }).decode(slice);
|
|
@@ -187,6 +214,21 @@ function asCosyteFormat(value) {
|
|
|
187
214
|
return KNOWN_FORMATS.includes(value) ? value : null;
|
|
188
215
|
}
|
|
189
216
|
|
|
217
|
+
// src/core/limits.ts
|
|
218
|
+
var BYTES_PER_MIB = 1024 * 1024;
|
|
219
|
+
var MAX_INPUT_BYTES = 64 * BYTES_PER_MIB;
|
|
220
|
+
function describeByteLimit(limit = MAX_INPUT_BYTES) {
|
|
221
|
+
const mib = limit / BYTES_PER_MIB;
|
|
222
|
+
return Number.isInteger(mib) ? `${String(limit)} bytes (${String(mib)} MiB)` : `${String(limit)} bytes`;
|
|
223
|
+
}
|
|
224
|
+
function inputTooLargeError(limit = MAX_INPUT_BYTES) {
|
|
225
|
+
return new CliError(
|
|
226
|
+
CLI_CODES.CLI_INPUT_TOO_LARGE,
|
|
227
|
+
EXIT.DATAERR,
|
|
228
|
+
`input is larger than the ${describeByteLimit(limit)} this command reads in one invocation; split the input and re-run`
|
|
229
|
+
);
|
|
230
|
+
}
|
|
231
|
+
|
|
190
232
|
// src/core/findings.ts
|
|
191
233
|
function formatHl7Position(pos) {
|
|
192
234
|
let out = `seg[${String(pos.segmentIndex)}]`;
|
|
@@ -493,11 +535,7 @@ async function validateFormat(format, bytes) {
|
|
|
493
535
|
}
|
|
494
536
|
async function deframeMllp(bytes) {
|
|
495
537
|
if (bytes.lastIndexOf(11) > bytes.lastIndexOf(28)) {
|
|
496
|
-
throw
|
|
497
|
-
CLI_CODES.CLI_PARSE_FAILED,
|
|
498
|
-
EXIT.DATAERR,
|
|
499
|
-
"truncated MLLP stream: an unterminated frame at the end of input (no closing FS/CR)"
|
|
500
|
-
);
|
|
538
|
+
throw truncatedMllpError();
|
|
501
539
|
}
|
|
502
540
|
const { FrameReader } = await loadOptional("mllp", () => import('@cosyte/mllp'));
|
|
503
541
|
const payloads = [];
|
|
@@ -509,6 +547,13 @@ async function deframeMllp(bytes) {
|
|
|
509
547
|
reader.push(Buffer.from(bytes));
|
|
510
548
|
return { payloads, warningCount };
|
|
511
549
|
}
|
|
550
|
+
function truncatedMllpError() {
|
|
551
|
+
return new CliError(
|
|
552
|
+
CLI_CODES.CLI_PARSE_FAILED,
|
|
553
|
+
EXIT.DATAERR,
|
|
554
|
+
"truncated MLLP stream: an unterminated frame at the end of input (no closing FS/CR)"
|
|
555
|
+
);
|
|
556
|
+
}
|
|
512
557
|
function decode(bytes) {
|
|
513
558
|
return new TextDecoder("utf-8", { fatal: false }).decode(bytes);
|
|
514
559
|
}
|
|
@@ -524,6 +569,84 @@ function unsupportedInternal(format, op) {
|
|
|
524
569
|
);
|
|
525
570
|
}
|
|
526
571
|
|
|
572
|
+
// src/core/records.ts
|
|
573
|
+
var LINE_FEED = 10;
|
|
574
|
+
var CARRIAGE_RETURN = 13;
|
|
575
|
+
var VERTICAL_TAB = 11;
|
|
576
|
+
var FILE_SEPARATOR = 28;
|
|
577
|
+
function asBuffer(chunk) {
|
|
578
|
+
return Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk.buffer, chunk.byteOffset, chunk.length);
|
|
579
|
+
}
|
|
580
|
+
async function* oneChunk(bytes) {
|
|
581
|
+
await Promise.resolve();
|
|
582
|
+
if (bytes.length > 0) yield bytes;
|
|
583
|
+
}
|
|
584
|
+
async function* withinLimit(chunks, limit = MAX_INPUT_BYTES) {
|
|
585
|
+
let total = 0;
|
|
586
|
+
for await (const chunk of chunks) {
|
|
587
|
+
total += chunk.length;
|
|
588
|
+
if (total > limit) throw inputTooLargeError(limit);
|
|
589
|
+
yield chunk;
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
async function collectChunks(chunks) {
|
|
593
|
+
const parts = [];
|
|
594
|
+
for await (const chunk of chunks) parts.push(asBuffer(chunk));
|
|
595
|
+
return Buffer.concat(parts);
|
|
596
|
+
}
|
|
597
|
+
function isBlank(line) {
|
|
598
|
+
return new TextDecoder("utf-8", { fatal: false }).decode(line).trim().length === 0;
|
|
599
|
+
}
|
|
600
|
+
function stripCarriageReturn(line) {
|
|
601
|
+
return line.length > 0 && line[line.length - 1] === CARRIAGE_RETURN ? line.subarray(0, line.length - 1) : line;
|
|
602
|
+
}
|
|
603
|
+
async function* ndjsonRecords(chunks) {
|
|
604
|
+
let carry = Buffer.alloc(0);
|
|
605
|
+
for await (const chunk of chunks) {
|
|
606
|
+
const buf = carry.length > 0 ? Buffer.concat([carry, asBuffer(chunk)]) : asBuffer(chunk);
|
|
607
|
+
let start = 0;
|
|
608
|
+
for (; ; ) {
|
|
609
|
+
const end = buf.indexOf(LINE_FEED, start);
|
|
610
|
+
if (end < 0) break;
|
|
611
|
+
const line = stripCarriageReturn(buf.subarray(start, end));
|
|
612
|
+
if (!isBlank(line)) yield line;
|
|
613
|
+
start = end + 1;
|
|
614
|
+
}
|
|
615
|
+
carry = start === 0 ? asBuffer(buf) : Buffer.from(buf.subarray(start));
|
|
616
|
+
}
|
|
617
|
+
const last = stripCarriageReturn(carry);
|
|
618
|
+
if (!isBlank(last)) yield last;
|
|
619
|
+
}
|
|
620
|
+
async function* mllpFrames(chunks) {
|
|
621
|
+
const { FrameReader } = await loadOptional("mllp", () => import('@cosyte/mllp'));
|
|
622
|
+
const ready = [];
|
|
623
|
+
const reader = new FrameReader({
|
|
624
|
+
onFrame: (payload) => ready.push(Buffer.from(payload)),
|
|
625
|
+
onWarning: () => void 0,
|
|
626
|
+
// The CLI's own documented input limit is the binding one, so the reader's smaller default frame
|
|
627
|
+
// ceiling is raised to it: an over-limit MLLP stream is refused by the limit the help output and
|
|
628
|
+
// the command reference state, not by an undocumented one underneath it.
|
|
629
|
+
maxFrameSizeBytes: MAX_INPUT_BYTES
|
|
630
|
+
});
|
|
631
|
+
let lastStart = -1;
|
|
632
|
+
let lastEnd = -1;
|
|
633
|
+
let offset = 0;
|
|
634
|
+
for await (const chunk of chunks) {
|
|
635
|
+
const buf = asBuffer(chunk);
|
|
636
|
+
const start = buf.lastIndexOf(VERTICAL_TAB);
|
|
637
|
+
if (start >= 0) lastStart = offset + start;
|
|
638
|
+
const end = buf.lastIndexOf(FILE_SEPARATOR);
|
|
639
|
+
if (end >= 0) lastEnd = offset + end;
|
|
640
|
+
offset += buf.length;
|
|
641
|
+
reader.push(buf);
|
|
642
|
+
while (ready.length > 0) {
|
|
643
|
+
const frame = ready.shift();
|
|
644
|
+
if (frame !== void 0) yield frame;
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
if (lastStart > lastEnd) throw truncatedMllpError();
|
|
648
|
+
}
|
|
649
|
+
|
|
527
650
|
// src/core/input.ts
|
|
528
651
|
async function resolveInput(source, formatOverride, deps, op) {
|
|
529
652
|
if (source === void 0) {
|
|
@@ -545,34 +668,91 @@ async function resolveInput(source, formatOverride, deps, op) {
|
|
|
545
668
|
if (bytes.length === 0) {
|
|
546
669
|
return fail(new CliError(CLI_CODES.CLI_EMPTY_INPUT, EXIT.DATAERR, "input is empty"));
|
|
547
670
|
}
|
|
671
|
+
const format = resolveFormat(bytes, formatOverride, op);
|
|
672
|
+
if (format instanceof CliError) return fail(format);
|
|
673
|
+
return { ok: true, input: { format, bytes } };
|
|
674
|
+
}
|
|
675
|
+
async function resolveInputStream(source, formatOverride, deps, op, limit = MAX_INPUT_BYTES) {
|
|
676
|
+
if (source === void 0) {
|
|
677
|
+
return fail(
|
|
678
|
+
new CliError(
|
|
679
|
+
CLI_CODES.CLI_USAGE,
|
|
680
|
+
EXIT.USAGE,
|
|
681
|
+
"missing <file> argument; pass a path or `-` to read stdin"
|
|
682
|
+
)
|
|
683
|
+
);
|
|
684
|
+
}
|
|
685
|
+
const iterator = withinLimit(openChunks(source, deps), limit)[Symbol.asyncIterator]();
|
|
686
|
+
const need = formatOverride === void 0 ? DETECT_PREFIX_BYTES : 1;
|
|
687
|
+
const head = [];
|
|
688
|
+
let headBytes = 0;
|
|
689
|
+
try {
|
|
690
|
+
while (headBytes < need) {
|
|
691
|
+
const step = await iterator.next();
|
|
692
|
+
if (step.done === true) break;
|
|
693
|
+
head.push(step.value);
|
|
694
|
+
headBytes += step.value.length;
|
|
695
|
+
}
|
|
696
|
+
} catch (e) {
|
|
697
|
+
if (e instanceof CliError) return fail(e);
|
|
698
|
+
throw e;
|
|
699
|
+
}
|
|
700
|
+
if (headBytes === 0) {
|
|
701
|
+
return fail(new CliError(CLI_CODES.CLI_EMPTY_INPUT, EXIT.DATAERR, "input is empty"));
|
|
702
|
+
}
|
|
703
|
+
const prefix = Buffer.concat(
|
|
704
|
+
head.map((c) => Buffer.from(c.buffer, c.byteOffset, c.length)),
|
|
705
|
+
Math.min(headBytes, DETECT_PREFIX_BYTES)
|
|
706
|
+
);
|
|
707
|
+
const format = resolveFormat(prefix, formatOverride, op);
|
|
708
|
+
if (format instanceof CliError) {
|
|
709
|
+
await iterator.return(void 0);
|
|
710
|
+
return fail(format);
|
|
711
|
+
}
|
|
712
|
+
return { ok: true, input: { format, chunks: rejoin(head, iterator) } };
|
|
713
|
+
}
|
|
714
|
+
function openChunks(source, deps) {
|
|
715
|
+
if (source === "-") {
|
|
716
|
+
return deps.openStdin === void 0 ? readerAsChunks(() => deps.readStdin()) : deps.openStdin();
|
|
717
|
+
}
|
|
718
|
+
return deps.openFile === void 0 ? readerAsChunks(() => deps.readFile(source)) : deps.openFile(source);
|
|
719
|
+
}
|
|
720
|
+
async function* readerAsChunks(read) {
|
|
721
|
+
yield* oneChunk(await read());
|
|
722
|
+
}
|
|
723
|
+
async function* rejoin(head, rest) {
|
|
724
|
+
for (const chunk of head) yield chunk;
|
|
725
|
+
for (; ; ) {
|
|
726
|
+
const step = await rest.next();
|
|
727
|
+
if (step.done === true) return;
|
|
728
|
+
yield step.value;
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
function resolveFormat(prefix, formatOverride, op) {
|
|
548
732
|
let format;
|
|
549
733
|
if (formatOverride !== void 0) {
|
|
550
734
|
const narrowed = asCosyteFormat(formatOverride);
|
|
551
735
|
if (narrowed === null) {
|
|
552
|
-
return
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
"unknown --format value; expected one of hl7, fhir, dicom, x12, ccda, ncpdp, astm, mllp"
|
|
557
|
-
)
|
|
736
|
+
return new CliError(
|
|
737
|
+
CLI_CODES.CLI_USAGE,
|
|
738
|
+
EXIT.USAGE,
|
|
739
|
+
"unknown --format value; expected one of hl7, fhir, dicom, x12, ccda, ncpdp, astm, mllp"
|
|
558
740
|
);
|
|
559
741
|
}
|
|
560
742
|
format = narrowed;
|
|
561
743
|
} else {
|
|
562
|
-
const detected = detectFormat(
|
|
563
|
-
if (detected.format === null) return
|
|
744
|
+
const detected = detectFormat(prefix);
|
|
745
|
+
if (detected.format === null) return detectionError(detected);
|
|
564
746
|
format = detected.format;
|
|
565
747
|
}
|
|
566
|
-
if (!supportsOp(format, op)) {
|
|
567
|
-
return
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
`format '${format}' does not support \`${op}\` in this CLI build (${op} supports: ${formatsSupporting(op).join(", ")})`
|
|
572
|
-
)
|
|
748
|
+
if (op !== null && !supportsOp(format, op)) {
|
|
749
|
+
return new CliError(
|
|
750
|
+
CLI_CODES.CLI_FORMAT_UNSUPPORTED,
|
|
751
|
+
EXIT.DATAERR,
|
|
752
|
+
`format '${format}' does not support \`${op}\` in this CLI build (${op} supports: ${formatsSupporting(op).join(", ")})`
|
|
573
753
|
);
|
|
574
754
|
}
|
|
575
|
-
return
|
|
755
|
+
return format;
|
|
576
756
|
}
|
|
577
757
|
function fail(e) {
|
|
578
758
|
return { ok: false, result: errorResult(e) };
|
|
@@ -844,11 +1024,24 @@ async function parseCommand(args, deps, posture = VALUE_FREE) {
|
|
|
844
1024
|
)
|
|
845
1025
|
);
|
|
846
1026
|
}
|
|
847
|
-
const resolved = await
|
|
1027
|
+
const resolved = await resolveInputStream(positionals[0], values.format, deps, "parse");
|
|
848
1028
|
if (!resolved.ok) return resolved.result;
|
|
849
|
-
const { format,
|
|
1029
|
+
const { format, chunks } = resolved.input;
|
|
850
1030
|
if (format === "mllp" || values.ndjson === true) {
|
|
851
|
-
return await parseMulti(
|
|
1031
|
+
return await parseMulti(
|
|
1032
|
+
format,
|
|
1033
|
+
chunks,
|
|
1034
|
+
values.ndjson === true,
|
|
1035
|
+
values.quiet === true,
|
|
1036
|
+
deps.writeStdout
|
|
1037
|
+
);
|
|
1038
|
+
}
|
|
1039
|
+
let bytes;
|
|
1040
|
+
try {
|
|
1041
|
+
bytes = await collectChunks(chunks);
|
|
1042
|
+
} catch (e) {
|
|
1043
|
+
if (e instanceof CliError) return errorResult(e);
|
|
1044
|
+
throw e;
|
|
852
1045
|
}
|
|
853
1046
|
return await parseSingle(format, bytes, values.json === true, values.quiet === true, posture);
|
|
854
1047
|
}
|
|
@@ -867,23 +1060,57 @@ async function parseSingle(format, bytes, json, quiet, posture) {
|
|
|
867
1060
|
` : "";
|
|
868
1061
|
return { stdout, stderr, exit: EXIT.OK };
|
|
869
1062
|
}
|
|
870
|
-
async function parseMulti(format,
|
|
871
|
-
|
|
872
|
-
|
|
1063
|
+
async function parseMulti(format, chunks, ndjson, quiet, writeStdout) {
|
|
1064
|
+
const recordFormat = format === "mllp" ? "hl7" : format;
|
|
1065
|
+
const records = format === "mllp" ? mllpFrames(chunks) : ndjsonRecords(chunks);
|
|
1066
|
+
const held = [];
|
|
1067
|
+
const emit = (line) => {
|
|
1068
|
+
if (writeStdout === void 0) {
|
|
1069
|
+
held.push(line);
|
|
1070
|
+
return;
|
|
1071
|
+
}
|
|
1072
|
+
try {
|
|
1073
|
+
writeStdout(line);
|
|
1074
|
+
} catch {
|
|
1075
|
+
throw new CliError(
|
|
1076
|
+
CLI_CODES.CLI_OUTPUT_WRITE_FAILED,
|
|
1077
|
+
EXIT.IOERR,
|
|
1078
|
+
"could not write to the output stream; it closed before the record stream finished"
|
|
1079
|
+
);
|
|
1080
|
+
}
|
|
1081
|
+
};
|
|
1082
|
+
const written = () => held.join("");
|
|
1083
|
+
let total = 0;
|
|
1084
|
+
let failed = 0;
|
|
1085
|
+
let warnings = 0;
|
|
873
1086
|
try {
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
1087
|
+
for await (const record of records) {
|
|
1088
|
+
let line;
|
|
1089
|
+
try {
|
|
1090
|
+
const { model, warnings: ws } = await parseFormat(recordFormat, record);
|
|
1091
|
+
warnings += ws.length;
|
|
1092
|
+
line = { record: total, format: recordFormat, model, warnings: ws };
|
|
1093
|
+
} catch (e) {
|
|
1094
|
+
if (e instanceof CliError) throw e;
|
|
1095
|
+
failed += 1;
|
|
1096
|
+
line = {
|
|
1097
|
+
record: total,
|
|
1098
|
+
format: recordFormat,
|
|
1099
|
+
error: extractStableCode(e) ?? "CLI_PARSE_FAILED"
|
|
1100
|
+
};
|
|
1101
|
+
}
|
|
1102
|
+
total += 1;
|
|
1103
|
+
emit(JSON.stringify(line) + "\n");
|
|
881
1104
|
}
|
|
882
1105
|
} catch (e) {
|
|
883
|
-
if (e instanceof CliError)
|
|
884
|
-
|
|
1106
|
+
if (e instanceof CliError) {
|
|
1107
|
+
return { stdout: written(), stderr: `${formatDiagnostic(e)}
|
|
1108
|
+
`, exit: e.exit };
|
|
1109
|
+
}
|
|
1110
|
+
const rejected = parseFailureResult(format, new Uint8Array(), VALUE_FREE, e);
|
|
1111
|
+
return { stdout: written(), stderr: rejected.stderr, exit: rejected.exit };
|
|
885
1112
|
}
|
|
886
|
-
if (
|
|
1113
|
+
if (total === 0) {
|
|
887
1114
|
return errorResult(
|
|
888
1115
|
new CliError(
|
|
889
1116
|
CLI_CODES.CLI_PARSE_FAILED,
|
|
@@ -892,34 +1119,9 @@ async function parseMulti(format, bytes, ndjson, quiet) {
|
|
|
892
1119
|
)
|
|
893
1120
|
);
|
|
894
1121
|
}
|
|
895
|
-
const lines = [];
|
|
896
|
-
let failed = 0;
|
|
897
|
-
let warnings = 0;
|
|
898
|
-
for (let i = 0; i < records.length; i += 1) {
|
|
899
|
-
const rec = records[i];
|
|
900
|
-
try {
|
|
901
|
-
const { model, warnings: ws } = await parseFormat(recordFormat, rec);
|
|
902
|
-
warnings += ws.length;
|
|
903
|
-
lines.push({ record: i, format: recordFormat, model, warnings: ws });
|
|
904
|
-
} catch (e) {
|
|
905
|
-
if (e instanceof CliError) return errorResult(e);
|
|
906
|
-
failed += 1;
|
|
907
|
-
lines.push({
|
|
908
|
-
record: i,
|
|
909
|
-
format: recordFormat,
|
|
910
|
-
error: extractStableCode(e) ?? "CLI_PARSE_FAILED"
|
|
911
|
-
});
|
|
912
|
-
}
|
|
913
|
-
}
|
|
914
|
-
const stdout = lines.map((l) => JSON.stringify(l)).join("\n") + "\n";
|
|
915
1122
|
const exit = failed > 0 ? EXIT.DATAERR : EXIT.OK;
|
|
916
|
-
const stderr = quiet ? "" : `cosyte: parsed ${String(
|
|
917
|
-
return { stdout, stderr, exit };
|
|
918
|
-
}
|
|
919
|
-
function splitLines(bytes) {
|
|
920
|
-
const text = new TextDecoder("utf-8", { fatal: false }).decode(bytes);
|
|
921
|
-
const enc = new TextEncoder();
|
|
922
|
-
return text.split(/\r?\n/).filter((line) => line.trim().length > 0).map((line) => enc.encode(line));
|
|
1123
|
+
const stderr = quiet ? "" : `cosyte: parsed ${String(total)} ${recordFormat} record(s) (${String(warnings)} warning(s), ${String(failed)} failed)` + (ndjson ? " [ndjson]" : format === "mllp" ? " [mllp]" : "") + "\n";
|
|
1124
|
+
return { stdout: written(), stderr, exit };
|
|
923
1125
|
}
|
|
924
1126
|
var VALIDATE_OPTIONS = {
|
|
925
1127
|
format: { type: "string" },
|
|
@@ -1002,39 +1204,116 @@ var FORMAT_PROP = {
|
|
|
1002
1204
|
description: "Optional format override; omit to autodetect by content. A format whose parser does not support the requested operation returns a value-free CLI_FORMAT_UNSUPPORTED (never a fake)."
|
|
1003
1205
|
}
|
|
1004
1206
|
};
|
|
1207
|
+
var OUTCOME_PROPS = {
|
|
1208
|
+
ok: {
|
|
1209
|
+
type: "boolean",
|
|
1210
|
+
description: "True iff the tool call produced data. A negative verdict about the message is still true (the tool worked); only a call that produced no data at all is false."
|
|
1211
|
+
},
|
|
1212
|
+
status: {
|
|
1213
|
+
type: "string",
|
|
1214
|
+
enum: ["success", "verdict", "failed"],
|
|
1215
|
+
description: "The outcome to branch on without parsing text: 'success' the operation completed cleanly, 'verdict' the tool ran and reports a negative finding about the message, 'failed' the call produced no data (a usage mistake, unparseable input, an unavailable parser, an internal error)."
|
|
1216
|
+
},
|
|
1217
|
+
exit: {
|
|
1218
|
+
type: "integer",
|
|
1219
|
+
enum: Object.values(EXIT),
|
|
1220
|
+
description: "The exit code the underlying command resolved to, from the documented exit-code contract."
|
|
1221
|
+
},
|
|
1222
|
+
code: {
|
|
1223
|
+
type: "string",
|
|
1224
|
+
enum: Object.values(CLI_CODES),
|
|
1225
|
+
description: "The stable diagnostic code on a failed call, drawn from a fixed registry so it never carries an input value. Absent on a call that produced data."
|
|
1226
|
+
}
|
|
1227
|
+
};
|
|
1228
|
+
var OUTCOME_REQUIRED = ["ok", "status", "exit"];
|
|
1229
|
+
function outputSchema(data) {
|
|
1230
|
+
return {
|
|
1231
|
+
type: "object",
|
|
1232
|
+
properties: { ...OUTCOME_PROPS, data },
|
|
1233
|
+
required: [...OUTCOME_REQUIRED],
|
|
1234
|
+
additionalProperties: false
|
|
1235
|
+
};
|
|
1236
|
+
}
|
|
1005
1237
|
var TOOL_DEFS = [
|
|
1006
1238
|
{
|
|
1007
1239
|
name: "parse",
|
|
1240
|
+
title: "Parse a healthcare message",
|
|
1008
1241
|
description: "Parse a healthcare message (HL7 v2 or FHIR R4) to typed JSON. Format is autodetected by content. Returns the parsed model plus value-free warnings.",
|
|
1009
1242
|
inputSchema: {
|
|
1010
1243
|
type: "object",
|
|
1011
1244
|
properties: { ...CONTENT_PROP, ...FORMAT_PROP },
|
|
1012
1245
|
required: ["content"],
|
|
1013
1246
|
additionalProperties: false
|
|
1014
|
-
}
|
|
1247
|
+
},
|
|
1248
|
+
outputSchema: outputSchema({
|
|
1249
|
+
type: "object",
|
|
1250
|
+
description: "The parse payload, present on a call that produced data. A single message parses to format + model + warnings. A multi-record input (an MLLP stream) parses to `records`, one entry per record: a parsed record, or a value-free per-record error code.",
|
|
1251
|
+
properties: {
|
|
1252
|
+
format: { type: "string", description: "The format the input was parsed as." },
|
|
1253
|
+
model: { description: "The wrapped library's parsed model, verbatim: the data channel." },
|
|
1254
|
+
warnings: {
|
|
1255
|
+
type: "array",
|
|
1256
|
+
description: "Value-free parse warnings: a stable code plus positional context."
|
|
1257
|
+
},
|
|
1258
|
+
records: {
|
|
1259
|
+
type: "array",
|
|
1260
|
+
description: "One entry per record of a multi-record input, in stream order."
|
|
1261
|
+
}
|
|
1262
|
+
},
|
|
1263
|
+
additionalProperties: false
|
|
1264
|
+
})
|
|
1015
1265
|
},
|
|
1016
1266
|
{
|
|
1017
1267
|
name: "validate",
|
|
1268
|
+
title: "Validate a healthcare message",
|
|
1018
1269
|
description: "Validate a message and carry the verdict: ok=true with a valid result, or a result reporting value-free findings. The parsed-but-invalid verdict is a successful call (not a tool error).",
|
|
1019
1270
|
inputSchema: {
|
|
1020
1271
|
type: "object",
|
|
1021
1272
|
properties: { ...CONTENT_PROP, ...FORMAT_PROP },
|
|
1022
1273
|
required: ["content"],
|
|
1023
1274
|
additionalProperties: false
|
|
1024
|
-
}
|
|
1275
|
+
},
|
|
1276
|
+
outputSchema: outputSchema({
|
|
1277
|
+
type: "object",
|
|
1278
|
+
description: "The validation payload, present on a call that produced data (a valid result and a negative verdict alike). Value-free throughout: findings are codes, severities and positional locators, never a field value.",
|
|
1279
|
+
properties: {
|
|
1280
|
+
format: { type: "string", description: "The format the input was validated as." },
|
|
1281
|
+
valid: {
|
|
1282
|
+
type: "boolean",
|
|
1283
|
+
description: "The verdict: false means parsed-but-non-conformant, not a failed call."
|
|
1284
|
+
},
|
|
1285
|
+
findings: {
|
|
1286
|
+
type: "array",
|
|
1287
|
+
description: "Value-free findings: a stable code, a severity, and a positional locator."
|
|
1288
|
+
}
|
|
1289
|
+
},
|
|
1290
|
+
required: ["format", "valid", "findings"],
|
|
1291
|
+
additionalProperties: false
|
|
1292
|
+
})
|
|
1025
1293
|
},
|
|
1026
1294
|
{
|
|
1027
1295
|
name: "inspect",
|
|
1296
|
+
title: "Inspect a healthcare message's structure",
|
|
1028
1297
|
description: "Return a value-free structural summary of a message: its type, segment/entry counts, and a warning/issue count. Never includes a field value.",
|
|
1029
1298
|
inputSchema: {
|
|
1030
1299
|
type: "object",
|
|
1031
1300
|
properties: { ...CONTENT_PROP, ...FORMAT_PROP },
|
|
1032
1301
|
required: ["content"],
|
|
1033
1302
|
additionalProperties: false
|
|
1034
|
-
}
|
|
1303
|
+
},
|
|
1304
|
+
outputSchema: outputSchema({
|
|
1305
|
+
type: "object",
|
|
1306
|
+
description: "The value-free structural summary, present on a call that produced data. `format` names the shape of the rest, which is that format's own counts and structural type codes (a message type, a resource type, a transaction-set id): classification, never a value.",
|
|
1307
|
+
properties: {
|
|
1308
|
+
format: { type: "string", description: "The format the summary describes." }
|
|
1309
|
+
},
|
|
1310
|
+
required: ["format"],
|
|
1311
|
+
additionalProperties: true
|
|
1312
|
+
})
|
|
1035
1313
|
},
|
|
1036
1314
|
{
|
|
1037
1315
|
name: "convert",
|
|
1316
|
+
title: "Convert HL7 v2 to a FHIR R4 Bundle",
|
|
1038
1317
|
description: "Convert an HL7 v2 message to a FHIR R4 Bundle via @cosyte/transform. Returns the converted Bundle; an error-severity conversion issue is reported with ok=false.",
|
|
1039
1318
|
inputSchema: {
|
|
1040
1319
|
type: "object",
|
|
@@ -1048,7 +1327,21 @@ var TOOL_DEFS = [
|
|
|
1048
1327
|
},
|
|
1049
1328
|
required: ["content"],
|
|
1050
1329
|
additionalProperties: false
|
|
1051
|
-
}
|
|
1330
|
+
},
|
|
1331
|
+
outputSchema: outputSchema({
|
|
1332
|
+
type: "object",
|
|
1333
|
+
description: "The conversion payload, present on a call that produced data. An error-severity finding is a negative verdict (the Bundle is still returned), not a failed call.",
|
|
1334
|
+
properties: {
|
|
1335
|
+
format: { type: "string", description: "The conversion target the Bundle is in." },
|
|
1336
|
+
bundle: { type: "object", description: "The converted FHIR R4 Bundle: the data channel." },
|
|
1337
|
+
findings: {
|
|
1338
|
+
type: "array",
|
|
1339
|
+
description: "Value-free conversion findings: a code, a severity, and a positional locator."
|
|
1340
|
+
}
|
|
1341
|
+
},
|
|
1342
|
+
required: ["format", "bundle", "findings"],
|
|
1343
|
+
additionalProperties: false
|
|
1344
|
+
})
|
|
1052
1345
|
}
|
|
1053
1346
|
];
|
|
1054
1347
|
function inlineDeps(content) {
|
|
@@ -1069,37 +1362,65 @@ function stringArg(args, key) {
|
|
|
1069
1362
|
const v = args[key];
|
|
1070
1363
|
return typeof v === "string" ? v : null;
|
|
1071
1364
|
}
|
|
1072
|
-
function
|
|
1073
|
-
const hardError = result.stdout === "";
|
|
1074
|
-
const text = hardError ? result.stderr.trim() : result.stdout.trim();
|
|
1365
|
+
function structuredResult(structuredContent) {
|
|
1075
1366
|
return {
|
|
1076
|
-
content: [
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
isError: hardError,
|
|
1080
|
-
structuredContent: { exit: result.exit, ok: !hardError }
|
|
1367
|
+
content: [{ type: "text", text: JSON.stringify(structuredContent) }],
|
|
1368
|
+
isError: structuredContent.status === "failed",
|
|
1369
|
+
structuredContent
|
|
1081
1370
|
};
|
|
1082
1371
|
}
|
|
1083
|
-
function
|
|
1084
|
-
return
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1372
|
+
function isRecordLine(value) {
|
|
1373
|
+
return typeof value === "object" && value !== null && "record" in value;
|
|
1374
|
+
}
|
|
1375
|
+
function parsePayload(stdout) {
|
|
1376
|
+
const values = [];
|
|
1377
|
+
for (const line of stdout.split("\n")) {
|
|
1378
|
+
if (line.trim().length === 0) continue;
|
|
1379
|
+
try {
|
|
1380
|
+
values.push(JSON.parse(line));
|
|
1381
|
+
} catch {
|
|
1382
|
+
return void 0;
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
const only = values.length === 1 ? values[0] : void 0;
|
|
1386
|
+
return only !== void 0 && !isRecordLine(only) ? only : { records: values };
|
|
1387
|
+
}
|
|
1388
|
+
function diagnosticCode(stderr) {
|
|
1389
|
+
return Object.values(CLI_CODES).find((code) => stderr.includes(`cosyte: ${code}: `));
|
|
1390
|
+
}
|
|
1391
|
+
function toToolResult(result) {
|
|
1392
|
+
if (result.stdout === "") {
|
|
1393
|
+
const code = diagnosticCode(result.stderr);
|
|
1394
|
+
return structuredResult({
|
|
1395
|
+
ok: false,
|
|
1396
|
+
status: "failed",
|
|
1397
|
+
exit: result.exit,
|
|
1398
|
+
...code !== void 0 ? { code } : {}
|
|
1399
|
+
});
|
|
1400
|
+
}
|
|
1401
|
+
const data = parsePayload(result.stdout);
|
|
1402
|
+
return structuredResult({
|
|
1403
|
+
ok: true,
|
|
1404
|
+
status: result.exit === EXIT.OK ? "success" : "verdict",
|
|
1405
|
+
exit: result.exit,
|
|
1406
|
+
...data !== void 0 ? { data } : {}
|
|
1407
|
+
});
|
|
1408
|
+
}
|
|
1409
|
+
function usageError() {
|
|
1410
|
+
return structuredResult({
|
|
1411
|
+
ok: false,
|
|
1412
|
+
status: "failed",
|
|
1413
|
+
exit: EXIT.USAGE,
|
|
1414
|
+
code: CLI_CODES.CLI_USAGE
|
|
1415
|
+
});
|
|
1089
1416
|
}
|
|
1090
1417
|
function internalError(e) {
|
|
1091
1418
|
const err = toCliError(e);
|
|
1092
|
-
return {
|
|
1093
|
-
content: [{ type: "text", text: `cosyte: ${err.code}: ${err.message}` }],
|
|
1094
|
-
isError: true,
|
|
1095
|
-
structuredContent: { exit: err.exit, ok: false }
|
|
1096
|
-
};
|
|
1419
|
+
return structuredResult({ ok: false, status: "failed", exit: err.exit, code: err.code });
|
|
1097
1420
|
}
|
|
1098
1421
|
async function dispatchTool(name, args, deps) {
|
|
1099
1422
|
const content = stringArg(args, "content");
|
|
1100
|
-
if (content === null)
|
|
1101
|
-
return usageError("missing required 'content' argument (the message text to operate on)");
|
|
1102
|
-
}
|
|
1423
|
+
if (content === null) return usageError();
|
|
1103
1424
|
const runDeps = deps ?? inlineDeps(content);
|
|
1104
1425
|
const format = stringArg(args, "format");
|
|
1105
1426
|
const fmtFlag = format !== null ? ["--format", format] : [];
|
|
@@ -1118,7 +1439,7 @@ async function dispatchTool(name, args, deps) {
|
|
|
1118
1439
|
return toToolResult(await convertCommand(["-", "--to", to, "--json"], runDeps, VALUE_FREE));
|
|
1119
1440
|
}
|
|
1120
1441
|
default:
|
|
1121
|
-
return usageError(
|
|
1442
|
+
return usageError();
|
|
1122
1443
|
}
|
|
1123
1444
|
} catch (e) {
|
|
1124
1445
|
return internalError(e);
|
|
@@ -1132,12 +1453,21 @@ function createMcpServer() {
|
|
|
1132
1453
|
server.setRequestHandler(ListToolsRequestSchema, () => ({
|
|
1133
1454
|
tools: TOOL_DEFS.map((t) => ({
|
|
1134
1455
|
name: t.name,
|
|
1456
|
+
title: t.title,
|
|
1135
1457
|
description: t.description,
|
|
1136
1458
|
inputSchema: {
|
|
1137
1459
|
type: t.inputSchema.type,
|
|
1138
1460
|
properties: { ...t.inputSchema.properties },
|
|
1139
1461
|
...t.inputSchema.required !== void 0 ? { required: [...t.inputSchema.required] } : {},
|
|
1140
1462
|
...t.inputSchema.additionalProperties !== void 0 ? { additionalProperties: t.inputSchema.additionalProperties } : {}
|
|
1463
|
+
},
|
|
1464
|
+
// Every advertised tool publishes its result schema; a client validates a reply against it
|
|
1465
|
+
// instead of pattern-matching the text block. Declared, so it is copied unconditionally.
|
|
1466
|
+
outputSchema: {
|
|
1467
|
+
type: t.outputSchema.type,
|
|
1468
|
+
properties: { ...t.outputSchema.properties },
|
|
1469
|
+
required: [...t.outputSchema.required],
|
|
1470
|
+
additionalProperties: t.outputSchema.additionalProperties
|
|
1141
1471
|
}
|
|
1142
1472
|
}))
|
|
1143
1473
|
}));
|
|
@@ -1147,7 +1477,9 @@ function createMcpServer() {
|
|
|
1147
1477
|
return {
|
|
1148
1478
|
content: result.content.map((c) => ({ type: c.type, text: c.text })),
|
|
1149
1479
|
isError: result.isError,
|
|
1150
|
-
|
|
1480
|
+
// The whole structured value reaches the wire. A field-by-field copy here would silently
|
|
1481
|
+
// truncate the payload the called tool's own schema promises.
|
|
1482
|
+
structuredContent: { ...result.structuredContent }
|
|
1151
1483
|
};
|
|
1152
1484
|
});
|
|
1153
1485
|
return server;
|