rt-imaging-mcp 0.1.0__py3-none-any.whl
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.
- rt_imaging_mcp/__init__.py +3 -0
- rt_imaging_mcp/__main__.py +3 -0
- rt_imaging_mcp/config.py +54 -0
- rt_imaging_mcp/dvh.py +136 -0
- rt_imaging_mcp/geometry.py +158 -0
- rt_imaging_mcp/security/__init__.py +1 -0
- rt_imaging_mcp/security/allowlist.py +174 -0
- rt_imaging_mcp/security/errors.py +89 -0
- rt_imaging_mcp/security/paths.py +116 -0
- rt_imaging_mcp/security/roi_names.py +156 -0
- rt_imaging_mcp/server.py +247 -0
- rt_imaging_mcp/tools/__init__.py +5 -0
- rt_imaging_mcp/tools/dicom.py +171 -0
- rt_imaging_mcp/tools/nifti.py +59 -0
- rt_imaging_mcp/tools/rt.py +169 -0
- rt_imaging_mcp/tools/rt_common.py +81 -0
- rt_imaging_mcp/tools/rt_dose.py +109 -0
- rt_imaging_mcp/tools/rt_dvh.py +313 -0
- rt_imaging_mcp/tools/rt_plan.py +146 -0
- rt_imaging_mcp-0.1.0.dist-info/METADATA +167 -0
- rt_imaging_mcp-0.1.0.dist-info/RECORD +25 -0
- rt_imaging_mcp-0.1.0.dist-info/WHEEL +4 -0
- rt_imaging_mcp-0.1.0.dist-info/entry_points.txt +2 -0
- rt_imaging_mcp-0.1.0.dist-info/licenses/LICENSE +201 -0
- rt_imaging_mcp-0.1.0.dist-info/licenses/NOTICE +4 -0
rt_imaging_mcp/config.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Server configuration.
|
|
2
|
+
|
|
3
|
+
There is no default root directory (rule R3): the server refuses to start
|
|
4
|
+
without one. Limits are conservative by default (rule R8).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from rt_imaging_mcp.security.allowlist import OPT_IN_KEYWORDS
|
|
14
|
+
from rt_imaging_mcp.security.errors import ConfigError
|
|
15
|
+
from rt_imaging_mcp.security.roi_names import MAX_NAME_LENGTH, normalize
|
|
16
|
+
|
|
17
|
+
ENV_ROOT = "RT_IMAGING_MCP_ROOT"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class Config:
|
|
22
|
+
root: Path
|
|
23
|
+
max_files: int = 5_000
|
|
24
|
+
max_depth: int = 8
|
|
25
|
+
max_file_bytes: int = 1024**3
|
|
26
|
+
enabled_opt_in_tags: frozenset[str] = field(default_factory=frozenset)
|
|
27
|
+
extra_roi_names: frozenset[str] = field(default_factory=frozenset)
|
|
28
|
+
|
|
29
|
+
def __post_init__(self) -> None:
|
|
30
|
+
if self.max_files < 1 or self.max_depth < 0 or self.max_file_bytes < 1:
|
|
31
|
+
raise ConfigError()
|
|
32
|
+
if not self.enabled_opt_in_tags <= OPT_IN_KEYWORDS:
|
|
33
|
+
raise ConfigError()
|
|
34
|
+
for name in self.extra_roi_names:
|
|
35
|
+
normalized = normalize(name)
|
|
36
|
+
if not normalized or len(normalized) > MAX_NAME_LENGTH:
|
|
37
|
+
raise ConfigError()
|
|
38
|
+
|
|
39
|
+
@classmethod
|
|
40
|
+
def from_root(cls, root: str | Path, **overrides: object) -> Config:
|
|
41
|
+
try:
|
|
42
|
+
resolved = Path(root).expanduser().resolve(strict=True)
|
|
43
|
+
except (OSError, RuntimeError):
|
|
44
|
+
raise ConfigError() from None
|
|
45
|
+
if not resolved.is_dir():
|
|
46
|
+
raise ConfigError()
|
|
47
|
+
return cls(root=resolved, **overrides) # type: ignore[arg-type]
|
|
48
|
+
|
|
49
|
+
@classmethod
|
|
50
|
+
def from_env(cls) -> Config:
|
|
51
|
+
value = os.environ.get(ENV_ROOT)
|
|
52
|
+
if not value:
|
|
53
|
+
raise ConfigError()
|
|
54
|
+
return cls.from_root(value)
|
rt_imaging_mcp/dvh.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""Dose-volume metrics from per-voxel doses (pure numpy, no file access).
|
|
2
|
+
|
|
3
|
+
Definitions (voxels carry a weight; the weight is 1 unless a dose slice is only partly inside the
|
|
4
|
+
structure or is shared between two contour slabs, see ``slice_contributions``):
|
|
5
|
+
|
|
6
|
+
* ``D(p)``: the highest dose ``d`` such that at least ``p`` percent of the structure volume
|
|
7
|
+
receives a dose of ``d`` or more. ``D(100)`` is the minimum dose, ``D(2)`` is a near-maximum dose.
|
|
8
|
+
* ``V(t)``: the percentage and volume of the structure that receives at least ``t`` Gy.
|
|
9
|
+
A small tolerance (1e-9 Gy) absorbs floating point error from the dose grid scaling.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import math
|
|
15
|
+
from collections.abc import Sequence
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
from numpy.typing import NDArray
|
|
20
|
+
|
|
21
|
+
DOSE_TOLERANCE_GY = 1e-9
|
|
22
|
+
SLICE_TOLERANCE_MM = 1e-6
|
|
23
|
+
WEIGHT_TOLERANCE = 1e-9
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def slice_contributions(
|
|
27
|
+
dose_z: Sequence[float],
|
|
28
|
+
dose_thickness: float,
|
|
29
|
+
contour_z: Sequence[float],
|
|
30
|
+
contour_thickness: float,
|
|
31
|
+
) -> list[list[tuple[int, float]]]:
|
|
32
|
+
"""For each dose slice, the contour slices it overlaps and the weight of each.
|
|
33
|
+
|
|
34
|
+
Each contour slice stands for a slab of ``contour_thickness`` mm centred on its z, and each
|
|
35
|
+
dose slice for a slab of ``dose_thickness`` mm centred on its z. The weight of a contour
|
|
36
|
+
slice for a dose slice is the fraction of the dose slab that overlaps the contour slab.
|
|
37
|
+
A dose plane inside one slab gets ``[(index, 1.0)]``; a plane on the boundary between two
|
|
38
|
+
slabs gets half of each; a plane on the outer boundary of the structure gets half of the
|
|
39
|
+
outermost slab only; a plane outside gets ``[]``. Summed over all dose slices, every contour
|
|
40
|
+
slab receives exactly its own thickness, so the structure volume equals the sum of the slabs
|
|
41
|
+
however the planes fall. If slabs overlap (irregular contour spacing) the weights of one dose
|
|
42
|
+
slice are scaled to add up to at most 1. ``contour_z`` must be ascending.
|
|
43
|
+
"""
|
|
44
|
+
contour = np.asarray(contour_z, dtype=float)
|
|
45
|
+
half_contour = contour_thickness / 2.0
|
|
46
|
+
slab_low = contour - half_contour
|
|
47
|
+
slab_high = contour + half_contour
|
|
48
|
+
half_dose = dose_thickness / 2.0
|
|
49
|
+
|
|
50
|
+
result: list[list[tuple[int, float]]] = []
|
|
51
|
+
for z in dose_z:
|
|
52
|
+
overlap = np.minimum(slab_high, z + half_dose) - np.maximum(slab_low, z - half_dose)
|
|
53
|
+
weights = np.clip(overlap, 0.0, None) / dose_thickness
|
|
54
|
+
total = float(weights.sum())
|
|
55
|
+
if total > 1.0:
|
|
56
|
+
weights = weights / total
|
|
57
|
+
result.append(
|
|
58
|
+
[
|
|
59
|
+
(int(index), float(weights[index]))
|
|
60
|
+
for index in np.flatnonzero(weights > SLICE_TOLERANCE_MM)
|
|
61
|
+
]
|
|
62
|
+
)
|
|
63
|
+
return result
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def dose_at_volume(
|
|
67
|
+
sorted_doses: NDArray[np.float64],
|
|
68
|
+
percent: float,
|
|
69
|
+
sorted_weights: NDArray[np.float64] | None = None,
|
|
70
|
+
) -> float:
|
|
71
|
+
"""``D(percent)`` for ascending ``sorted_doses`` (with the matching ``sorted_weights``)."""
|
|
72
|
+
if sorted_weights is None:
|
|
73
|
+
count = len(sorted_doses)
|
|
74
|
+
needed = min(max(math.ceil(round(percent * count / 100.0, 9)), 1), count)
|
|
75
|
+
return float(sorted_doses[count - needed])
|
|
76
|
+
target = percent * float(sorted_weights.sum()) / 100.0
|
|
77
|
+
from_the_top = np.cumsum(sorted_weights[::-1])
|
|
78
|
+
index = int(np.searchsorted(from_the_top, target - WEIGHT_TOLERANCE, side="left"))
|
|
79
|
+
index = min(index, len(sorted_doses) - 1)
|
|
80
|
+
return float(sorted_doses[::-1][index])
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def volume_at_dose(
|
|
84
|
+
doses: NDArray[np.float64],
|
|
85
|
+
threshold_gy: float,
|
|
86
|
+
weights: NDArray[np.float64] | None = None,
|
|
87
|
+
) -> float:
|
|
88
|
+
"""Number of voxels (weighted when ``weights`` is given) receiving at least ``threshold_gy``."""
|
|
89
|
+
above = doses >= threshold_gy - DOSE_TOLERANCE_GY
|
|
90
|
+
if weights is None:
|
|
91
|
+
return float(np.count_nonzero(above))
|
|
92
|
+
return float(weights[above].sum())
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def format_number(value: float) -> str:
|
|
96
|
+
"""Compact key text: 95.0 -> '95', 2.5 -> '2.5'."""
|
|
97
|
+
return f"{value:g}"
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def dvh_metrics(
|
|
101
|
+
doses: NDArray[np.float64],
|
|
102
|
+
voxel_volume_mm3: float,
|
|
103
|
+
percentages: Sequence[float],
|
|
104
|
+
thresholds_gy: Sequence[float],
|
|
105
|
+
weights: NDArray[np.float64] | None = None,
|
|
106
|
+
) -> dict[str, Any]:
|
|
107
|
+
"""Statistics, D(p) and V(t) for the voxel doses of one structure."""
|
|
108
|
+
order = np.argsort(doses, kind="stable")
|
|
109
|
+
ordered = doses[order]
|
|
110
|
+
ordered_weights = None if weights is None else weights[order]
|
|
111
|
+
total = float(len(ordered)) if ordered_weights is None else float(ordered_weights.sum())
|
|
112
|
+
d_metrics = {
|
|
113
|
+
f"D{format_number(p)}": round(dose_at_volume(ordered, p, ordered_weights), 6)
|
|
114
|
+
for p in percentages
|
|
115
|
+
}
|
|
116
|
+
v_metrics: dict[str, dict[str, float]] = {}
|
|
117
|
+
for threshold in thresholds_gy:
|
|
118
|
+
voxels = volume_at_dose(ordered, threshold, ordered_weights)
|
|
119
|
+
v_metrics[f"V{format_number(threshold)}Gy"] = {
|
|
120
|
+
"percent": round(100.0 * voxels / total, 4),
|
|
121
|
+
"volume_cm3": round(voxels * voxel_volume_mm3 / 1000.0, 6),
|
|
122
|
+
}
|
|
123
|
+
mean = (
|
|
124
|
+
np.average(ordered, weights=ordered_weights)
|
|
125
|
+
if ordered_weights is not None
|
|
126
|
+
else ordered.mean(dtype=np.float64)
|
|
127
|
+
)
|
|
128
|
+
return {
|
|
129
|
+
"dose_gy": {
|
|
130
|
+
"min": round(float(ordered[0]), 6),
|
|
131
|
+
"max": round(float(ordered[-1]), 6),
|
|
132
|
+
"mean": round(float(mean), 6),
|
|
133
|
+
},
|
|
134
|
+
"d_metrics_gy": d_metrics,
|
|
135
|
+
"v_metrics": v_metrics,
|
|
136
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""Small planar geometry helpers for RT structure contours (pure numpy)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
from numpy.typing import NDArray
|
|
9
|
+
|
|
10
|
+
Polygon = NDArray[np.float64] # shape (N, 2): x, y in millimetres
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def polygon_area(polygon: Polygon) -> float:
|
|
14
|
+
"""Absolute area of a simple polygon (shoelace formula)."""
|
|
15
|
+
x = polygon[:, 0]
|
|
16
|
+
y = polygon[:, 1]
|
|
17
|
+
return float(abs(np.dot(x, np.roll(y, -1)) - np.dot(y, np.roll(x, -1))) / 2.0)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def point_in_polygon(point: tuple[float, float], polygon: Polygon) -> bool:
|
|
21
|
+
"""Even-odd ray casting test. Points exactly on an edge are not guaranteed either way."""
|
|
22
|
+
px, py = point
|
|
23
|
+
x = polygon[:, 0]
|
|
24
|
+
y = polygon[:, 1]
|
|
25
|
+
x_next = np.roll(x, -1)
|
|
26
|
+
y_next = np.roll(y, -1)
|
|
27
|
+
crosses = (y > py) != (y_next > py)
|
|
28
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
29
|
+
x_at_py = (x_next - x) * (py - y) / (y_next - y) + x
|
|
30
|
+
return bool(np.count_nonzero(crosses & (px < x_at_py)) % 2 == 1)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def net_slice_area(polygons: Sequence[Polygon]) -> float:
|
|
34
|
+
"""Area enclosed by the contours of one slice, treating nested contours as holes.
|
|
35
|
+
|
|
36
|
+
Containment depth decides the sign (even-odd rule): a contour inside one other contour
|
|
37
|
+
is a hole, a contour inside that hole is material again, and so on. Each contour is
|
|
38
|
+
probed with its first vertex, so contours that touch or share vertices are not handled.
|
|
39
|
+
"""
|
|
40
|
+
total = 0.0
|
|
41
|
+
for index, polygon in enumerate(polygons):
|
|
42
|
+
probe = (float(polygon[0, 0]), float(polygon[0, 1]))
|
|
43
|
+
depth = sum(
|
|
44
|
+
1
|
|
45
|
+
for other_index, other in enumerate(polygons)
|
|
46
|
+
if other_index != index and point_in_polygon(probe, other)
|
|
47
|
+
)
|
|
48
|
+
total += polygon_area(polygon) * (1.0 if depth % 2 == 0 else -1.0)
|
|
49
|
+
return max(total, 0.0)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _crossing_edges(polygon: Polygon) -> tuple[NDArray[np.float64], ...]:
|
|
53
|
+
"""Edge end points (x1, y1, x2, y2) of all non-horizontal edges."""
|
|
54
|
+
x1, y1 = polygon[:, 0], polygon[:, 1]
|
|
55
|
+
x2, y2 = np.roll(x1, -1), np.roll(y1, -1)
|
|
56
|
+
keep = y1 != y2
|
|
57
|
+
return x1[keep], y1[keep], x2[keep], y2[keep]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _bounds(polygon: Polygon) -> tuple[float, float, float, float]:
|
|
61
|
+
"""Bounding box (min_x, max_x, min_y, max_y)."""
|
|
62
|
+
low = polygon.min(axis=0)
|
|
63
|
+
high = polygon.max(axis=0)
|
|
64
|
+
return float(low[0]), float(high[0]), float(low[1]), float(high[1])
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _index_range(axis: NDArray[np.float64], low: float, high: float) -> tuple[int, int]:
|
|
68
|
+
"""Half-open index range of the ascending ``axis`` values inside [low, high]."""
|
|
69
|
+
start = int(np.searchsorted(axis, low, side="left"))
|
|
70
|
+
stop = int(np.searchsorted(axis, high, side="right"))
|
|
71
|
+
return start, max(start, stop)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _row_spans(
|
|
75
|
+
ys: NDArray[np.float64],
|
|
76
|
+
x1: NDArray[np.float64],
|
|
77
|
+
y1: NDArray[np.float64],
|
|
78
|
+
y2: NDArray[np.float64],
|
|
79
|
+
) -> tuple[NDArray[np.intp], NDArray[np.intp], NDArray[np.intp]]:
|
|
80
|
+
"""For every edge, the rows whose centre line it crosses.
|
|
81
|
+
|
|
82
|
+
An edge crosses a row line ``y`` when ``min(y1, y2) <= y < max(y1, y2)``, the half-open rule
|
|
83
|
+
of the ray casting test. Returns ``(first_row, row_count, edge_of_each_crossing)``.
|
|
84
|
+
"""
|
|
85
|
+
low = np.minimum(y1, y2)
|
|
86
|
+
high = np.maximum(y1, y2)
|
|
87
|
+
first = np.searchsorted(ys, low, side="left")
|
|
88
|
+
last = np.searchsorted(ys, high, side="left")
|
|
89
|
+
counts = np.maximum(last - first, 0)
|
|
90
|
+
edge_of_crossing = np.repeat(np.arange(len(x1)), counts)
|
|
91
|
+
return first, counts, edge_of_crossing
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def polygon_work(xs: NDArray[np.float64], ys: NDArray[np.float64], polygon: Polygon) -> int:
|
|
95
|
+
"""Work ``polygon_mask`` does: cells in the bounding box plus row crossings of the edges."""
|
|
96
|
+
min_x, max_x, min_y, max_y = _bounds(polygon)
|
|
97
|
+
c0, c1 = _index_range(xs, min_x, max_x)
|
|
98
|
+
r0, r1 = _index_range(ys, min_y, max_y)
|
|
99
|
+
x1, y1, _, y2 = _crossing_edges(polygon)
|
|
100
|
+
_, counts, _ = _row_spans(ys, x1, y1, y2)
|
|
101
|
+
return (c1 - c0) * (r1 - r0) + int(counts.sum())
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def polygon_mask(
|
|
105
|
+
xs: NDArray[np.float64], ys: NDArray[np.float64], polygon: Polygon
|
|
106
|
+
) -> NDArray[np.bool_]:
|
|
107
|
+
"""Mask of grid cell centres inside ``polygon``, shape (len(ys), len(xs)).
|
|
108
|
+
|
|
109
|
+
``xs`` (columns) and ``ys`` (rows) must be ascending. Uses the even-odd rule. A centre is inside
|
|
110
|
+
when an odd number of edge crossings of its row lie at or left of it, so a centre exactly on a
|
|
111
|
+
vertical edge counts as inside on the left side of the polygon only.
|
|
112
|
+
|
|
113
|
+
Scanline method: for each row the x positions where edges cross the row line are sorted and
|
|
114
|
+
the cells between pairs of crossings are filled, which costs about (cells + crossings) instead
|
|
115
|
+
of (cells x edges).
|
|
116
|
+
"""
|
|
117
|
+
mask = np.zeros((ys.size, xs.size), dtype=bool)
|
|
118
|
+
min_x, max_x, min_y, max_y = _bounds(polygon)
|
|
119
|
+
c0, c1 = _index_range(xs, min_x, max_x)
|
|
120
|
+
r0, r1 = _index_range(ys, min_y, max_y)
|
|
121
|
+
if c1 <= c0 or r1 <= r0:
|
|
122
|
+
return mask
|
|
123
|
+
|
|
124
|
+
x1, y1, x2, y2 = _crossing_edges(polygon)
|
|
125
|
+
first, counts, edge = _row_spans(ys, x1, y1, y2)
|
|
126
|
+
total = int(counts.sum())
|
|
127
|
+
if total == 0:
|
|
128
|
+
return mask
|
|
129
|
+
|
|
130
|
+
# Row and x position of every crossing of an edge with a row line.
|
|
131
|
+
within = np.arange(total) - np.repeat(np.cumsum(counts) - counts, counts)
|
|
132
|
+
rows = first[edge] + within
|
|
133
|
+
py = ys[rows]
|
|
134
|
+
ax, ay, bx, by = x1[edge], y1[edge], x2[edge], y2[edge]
|
|
135
|
+
x_at_row = (bx - ax) * (py - ay) / (by - ay) + ax
|
|
136
|
+
|
|
137
|
+
# Sort by row, then x, and pair crossings 1-2, 3-4, ... within each row.
|
|
138
|
+
order = np.lexsort((x_at_row, rows))
|
|
139
|
+
rows, x_at_row = rows[order], x_at_row[order]
|
|
140
|
+
same_row_next = np.zeros(total, dtype=bool)
|
|
141
|
+
same_row_next[:-1] = rows[1:] == rows[:-1]
|
|
142
|
+
row_start = np.flatnonzero(np.r_[True, rows[1:] != rows[:-1]])
|
|
143
|
+
row_length = np.diff(np.r_[row_start, total])
|
|
144
|
+
position = np.arange(total) - np.repeat(row_start, row_length)
|
|
145
|
+
opening = np.flatnonzero((position % 2 == 0) & same_row_next)
|
|
146
|
+
|
|
147
|
+
first_col = np.searchsorted(xs, x_at_row[opening], side="left") - c0
|
|
148
|
+
end_col = np.searchsorted(xs, x_at_row[opening + 1], side="left") - c0
|
|
149
|
+
row_index = rows[opening] - r0
|
|
150
|
+
|
|
151
|
+
width = c1 - c0
|
|
152
|
+
flat_open = row_index * (width + 1) + first_col
|
|
153
|
+
flat_close = row_index * (width + 1) + end_col
|
|
154
|
+
size = (r1 - r0) * (width + 1)
|
|
155
|
+
delta = np.bincount(flat_open, minlength=size) - np.bincount(flat_close, minlength=size)
|
|
156
|
+
filled = np.cumsum(delta.reshape(r1 - r0, width + 1), axis=1)[:, :width] > 0
|
|
157
|
+
mask[r0:r1, c0:c1] = filled
|
|
158
|
+
return mask
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Security layer. Every tool must go through these modules (see docs/threat-model.md)."""
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""DICOM tag allowlist (rule R1).
|
|
2
|
+
|
|
3
|
+
Only attributes listed here can ever be returned. There is no denylist logic:
|
|
4
|
+
a tag that is not on the allowlist is rejected, including private tags and
|
|
5
|
+
attributes added to DICOM in the future.
|
|
6
|
+
|
|
7
|
+
``ALWAYS_BLOCKED_KEYWORDS`` is documentation and a test invariant: it must never
|
|
8
|
+
overlap with the allowed sets. Nothing in this module reads from it at runtime
|
|
9
|
+
to decide what to return.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from collections.abc import Iterable, Sequence
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from rt_imaging_mcp.security.errors import TagNotAllowedError
|
|
18
|
+
|
|
19
|
+
# Technical attributes. Safe to return by default.
|
|
20
|
+
DEFAULT_KEYWORDS: frozenset[str] = frozenset(
|
|
21
|
+
{
|
|
22
|
+
"Modality",
|
|
23
|
+
"Rows",
|
|
24
|
+
"Columns",
|
|
25
|
+
"NumberOfFrames",
|
|
26
|
+
"SamplesPerPixel",
|
|
27
|
+
"BitsAllocated",
|
|
28
|
+
"BitsStored",
|
|
29
|
+
"HighBit",
|
|
30
|
+
"PixelRepresentation",
|
|
31
|
+
"PhotometricInterpretation",
|
|
32
|
+
"PixelSpacing",
|
|
33
|
+
"SliceThickness",
|
|
34
|
+
"SpacingBetweenSlices",
|
|
35
|
+
"ImageOrientationPatient",
|
|
36
|
+
"ImagePositionPatient",
|
|
37
|
+
"SOPClassUID",
|
|
38
|
+
"TransferSyntaxUID",
|
|
39
|
+
"RescaleSlope",
|
|
40
|
+
"RescaleIntercept",
|
|
41
|
+
}
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
# Can carry indirect identifiers or free text. Off unless the user enables them explicitly.
|
|
45
|
+
OPT_IN_KEYWORDS: frozenset[str] = frozenset(
|
|
46
|
+
{
|
|
47
|
+
"StudyDate",
|
|
48
|
+
"StudyTime",
|
|
49
|
+
"SeriesDate",
|
|
50
|
+
"SeriesTime",
|
|
51
|
+
"AcquisitionDate",
|
|
52
|
+
"AcquisitionTime",
|
|
53
|
+
"ContentDate",
|
|
54
|
+
"ContentTime",
|
|
55
|
+
"StudyDescription",
|
|
56
|
+
"SeriesDescription",
|
|
57
|
+
"ProtocolName",
|
|
58
|
+
"BodyPartExamined",
|
|
59
|
+
"Manufacturer",
|
|
60
|
+
"ManufacturerModelName",
|
|
61
|
+
"SoftwareVersions",
|
|
62
|
+
"StudyInstanceUID",
|
|
63
|
+
"SeriesInstanceUID",
|
|
64
|
+
"SOPInstanceUID",
|
|
65
|
+
"FrameOfReferenceUID",
|
|
66
|
+
}
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
# Direct identifiers and similar. Can never be enabled. Kept for tests and documentation.
|
|
70
|
+
ALWAYS_BLOCKED_KEYWORDS: frozenset[str] = frozenset(
|
|
71
|
+
{
|
|
72
|
+
"PatientName",
|
|
73
|
+
"PatientID",
|
|
74
|
+
"PatientBirthDate",
|
|
75
|
+
"PatientBirthTime",
|
|
76
|
+
"PatientSex",
|
|
77
|
+
"PatientAge",
|
|
78
|
+
"PatientSize",
|
|
79
|
+
"PatientWeight",
|
|
80
|
+
"PatientAddress",
|
|
81
|
+
"PatientTelephoneNumbers",
|
|
82
|
+
"PatientComments",
|
|
83
|
+
"OtherPatientIDs",
|
|
84
|
+
"OtherPatientNames",
|
|
85
|
+
"PatientMotherBirthName",
|
|
86
|
+
"MedicalRecordLocator",
|
|
87
|
+
"AdditionalPatientHistory",
|
|
88
|
+
"EthnicGroup",
|
|
89
|
+
"Occupation",
|
|
90
|
+
"InstitutionName",
|
|
91
|
+
"InstitutionAddress",
|
|
92
|
+
"InstitutionalDepartmentName",
|
|
93
|
+
"ReferringPhysicianName",
|
|
94
|
+
"PerformingPhysicianName",
|
|
95
|
+
"PhysiciansOfRecord",
|
|
96
|
+
"NameOfPhysiciansReadingStudy",
|
|
97
|
+
"RequestingPhysician",
|
|
98
|
+
"OperatorsName",
|
|
99
|
+
"AccessionNumber",
|
|
100
|
+
"StudyID",
|
|
101
|
+
"DeviceSerialNumber",
|
|
102
|
+
"StationName",
|
|
103
|
+
"ImageComments",
|
|
104
|
+
}
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
ALL_ALLOWABLE_KEYWORDS: frozenset[str] = DEFAULT_KEYWORDS | OPT_IN_KEYWORDS
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def resolve_keywords(
|
|
111
|
+
requested: Iterable[str] | None,
|
|
112
|
+
enabled_opt_in: frozenset[str] = frozenset(),
|
|
113
|
+
) -> tuple[str, ...]:
|
|
114
|
+
"""Return the keywords a tool may read.
|
|
115
|
+
|
|
116
|
+
``requested=None`` means "everything currently allowed". Any requested keyword
|
|
117
|
+
that is not currently allowed raises ``TagNotAllowedError``.
|
|
118
|
+
"""
|
|
119
|
+
allowed = DEFAULT_KEYWORDS | (enabled_opt_in & OPT_IN_KEYWORDS)
|
|
120
|
+
if requested is None:
|
|
121
|
+
return tuple(sorted(allowed))
|
|
122
|
+
|
|
123
|
+
resolved: list[str] = []
|
|
124
|
+
for keyword in requested:
|
|
125
|
+
if not isinstance(keyword, str) or keyword not in allowed:
|
|
126
|
+
raise TagNotAllowedError()
|
|
127
|
+
if keyword not in resolved:
|
|
128
|
+
resolved.append(keyword)
|
|
129
|
+
return tuple(resolved)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def to_jsonable(value: Any) -> Any:
|
|
133
|
+
"""Convert a pydicom value to plain JSON types. Unknown types become ``None``."""
|
|
134
|
+
if value is None or isinstance(value, bool):
|
|
135
|
+
return value
|
|
136
|
+
if isinstance(value, int):
|
|
137
|
+
return int(value)
|
|
138
|
+
if isinstance(value, float):
|
|
139
|
+
return float(value)
|
|
140
|
+
if isinstance(value, str):
|
|
141
|
+
return str(value)
|
|
142
|
+
if isinstance(value, Sequence) and not isinstance(value, bytes | bytearray):
|
|
143
|
+
return [to_jsonable(item) for item in value]
|
|
144
|
+
return None
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _lookup(dataset: Any, keyword: str) -> Any:
|
|
148
|
+
value = dataset.get(keyword)
|
|
149
|
+
if value is None:
|
|
150
|
+
file_meta = getattr(dataset, "file_meta", None)
|
|
151
|
+
if file_meta is not None:
|
|
152
|
+
value = file_meta.get(keyword)
|
|
153
|
+
return value
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def filter_dataset(dataset: Any, keywords: Iterable[str]) -> dict[str, Any]:
|
|
157
|
+
"""Read ``keywords`` from a pydicom dataset and return JSON-safe values.
|
|
158
|
+
|
|
159
|
+
Defense in depth: even when called with keywords that were not vetted by
|
|
160
|
+
``resolve_keywords``, anything outside the allowable universe is rejected.
|
|
161
|
+
Attributes are fetched by keyword only, so private tags are never touched.
|
|
162
|
+
"""
|
|
163
|
+
result: dict[str, Any] = {}
|
|
164
|
+
for keyword in keywords:
|
|
165
|
+
if keyword not in ALL_ALLOWABLE_KEYWORDS:
|
|
166
|
+
raise TagNotAllowedError()
|
|
167
|
+
value = _lookup(dataset, keyword)
|
|
168
|
+
if value is None:
|
|
169
|
+
continue
|
|
170
|
+
converted = to_jsonable(value)
|
|
171
|
+
if converted is None:
|
|
172
|
+
continue
|
|
173
|
+
result[keyword] = converted
|
|
174
|
+
return result
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Errors with fixed messages.
|
|
2
|
+
|
|
3
|
+
Rule R6: error messages never contain data read from files. To make that
|
|
4
|
+
impossible by construction, these exceptions take no arguments and always
|
|
5
|
+
carry the static ``message`` of their class.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class RtImagingMcpError(Exception):
|
|
12
|
+
"""Base class. The message is a fixed string, never built from file content."""
|
|
13
|
+
|
|
14
|
+
message = "internal error"
|
|
15
|
+
|
|
16
|
+
def __init__(self) -> None:
|
|
17
|
+
super().__init__(self.message)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ConfigError(RtImagingMcpError):
|
|
21
|
+
message = "invalid configuration"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class InvalidPathError(RtImagingMcpError):
|
|
25
|
+
message = "invalid path"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class PathOutsideRootError(RtImagingMcpError):
|
|
29
|
+
message = "path is outside the configured root"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class PathNotFoundError(RtImagingMcpError):
|
|
33
|
+
message = "path does not exist"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class WrongPathKindError(RtImagingMcpError):
|
|
37
|
+
message = "path is not of the expected kind"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class TagNotAllowedError(RtImagingMcpError):
|
|
41
|
+
message = "tag is not allowed"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class FileTooLargeError(RtImagingMcpError):
|
|
45
|
+
message = "file exceeds the configured size limit"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class NotDicomError(RtImagingMcpError):
|
|
49
|
+
message = "file is not a readable DICOM file"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class NotNiftiError(RtImagingMcpError):
|
|
53
|
+
message = "file is not a readable NIfTI file"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class NotRtStructError(RtImagingMcpError):
|
|
57
|
+
message = "file is not a readable RT structure set"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class NotRtDoseError(RtImagingMcpError):
|
|
61
|
+
message = "file is not a readable RT dose file"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class NotRtPlanError(RtImagingMcpError):
|
|
65
|
+
message = "file is not a readable RT plan file"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class InvalidParameterError(RtImagingMcpError):
|
|
69
|
+
message = "invalid parameter"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class StructureNotFoundError(RtImagingMcpError):
|
|
73
|
+
message = "structure not found or has no usable contours"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class FrameOfReferenceError(RtImagingMcpError):
|
|
77
|
+
message = "frame of reference is missing or does not match between structure set and dose"
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class UnsupportedGridError(RtImagingMcpError):
|
|
81
|
+
message = "dose grid orientation, spacing or units are not supported"
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class NoStructureVoxelsError(RtImagingMcpError):
|
|
85
|
+
message = "structure does not overlap the dose grid"
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class WorkLimitError(RtImagingMcpError):
|
|
89
|
+
message = "computation exceeds the work limit"
|