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