Skip to main content
Glama

load-dicom-seg

Load a DICOM SEG file and associate it with a reference image to enable medical image segmentation analysis within the DICOM-MCP server.

Instructions

Load a DICOM SEG file and associate it with a reference image

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
seg_fileYesPath to a DICOM SEG file
reference_series_uidNoSeries UID of the reference image

Implementation Reference

  • MCP tool handler for 'load-dicom-seg' that validates arguments, loads reference image if provided, calls the core load_dicom_seg function, caches the result, and returns summary information.
    elif name == "load-dicom-seg":
        seg_file = arguments.get("seg_file")
        reference_series_uid = arguments.get("reference_series_uid")
        
        if not seg_file or not os.path.isfile(seg_file):
            raise ValueError(f"Invalid DICOM SEG file: {seg_file}")
            
        # Get reference image if provided
        reference_image = None
        if reference_series_uid:
            if reference_series_uid not in dicom_cache:
                raise ValueError(f"Reference series {reference_series_uid} not loaded. Use load-dicom-series first.")
            reference_image = dicom_cache[reference_series_uid]["image"]
            
        # Load the DICOM SEG
        seg_array, seg_metadata = load_dicom_seg(seg_file, reference_image)
        
        # Generate a unique ID for this segmentation
        seg_uid = f"seg_{Path(seg_file).stem}"
        
        # Cache the loaded data
        dicom_cache[seg_uid] = {
            "image": seg_array,
            "metadata": seg_metadata,
            "reference": reference_series_uid
        }
        
        # Return summary information
        shape = seg_array.shape
        segment_count = len(seg_metadata.get("segment_info", []))
        
        return [
            types.TextContent(
                type="text",
                text=f"Loaded DICOM SEG {seg_uid}\n" +
                     f"Shape: {shape}\n" +
                     f"Segments: {segment_count}\n" +
                     f"Metadata: {json.dumps(seg_metadata, indent=2, default=str)}"
            )
        ]
  • Core helper function implementing the DICOM SEG loading logic using pydicom_seg and ITK for image handling and metadata extraction.
    def load_dicom_seg(seg_file_path: str, reference_image=None) -> Tuple[np.ndarray, Dict[str, Any]]:
        """Load a DICOM SEG file into a 3D numpy array and metadata dictionary"""
        try:
            # Read the DICOM SEG object
            seg_dicom = pydicom.dcmread(seg_file_path)
            seg_reader = pydicom_seg.MultiClassReader()
            seg_obj = seg_reader.read(seg_dicom)
            
            # Convert to numpy array
            np_array = seg_obj.data.astype(np.float32)
            
            # Extract metadata including segment information
            metadata = {
                "segment_info": []
            }
            
            # Add segment information if available
            if hasattr(seg_obj, "segment_infos"):
                for idx, segment in enumerate(seg_obj.segment_infos):
                    segment_data = {
                        "label": idx + 1,
                        "name": getattr(segment, "SegmentDescription", f"Segment {idx+1}"),
                        "algorithm_type": getattr(segment, "SegmentAlgorithmType", "UNKNOWN")
                    }
                    metadata["segment_info"].append(segment_data)
            
            # If reference image is provided, copy its metadata
            if reference_image is not None:
                itk_seg_image = itk.GetImageFromArray(np_array)
                itk_seg_image.CopyInformation(reference_image)
                
                # Update numpy array with potentially transformed data
                np_array = itk.GetArrayFromImage(itk_seg_image)
                
                # Extract updated metadata
                size = itk_seg_image.GetLargestPossibleRegion().GetSize()
                spacing = itk_seg_image.GetSpacing()
                origin = itk_seg_image.GetOrigin()
                direction = itk_seg_image.GetDirection().GetVnlMatrix().as_matrix().flatten().tolist()
                
                metadata.update({
                    "size": (int(size[0]), int(size[1]), int(size[2])),
                    "spacing": (float(spacing[0]), float(spacing[1]), float(spacing[2])),
                    "origin": (float(origin[0]), float(origin[1]), float(origin[2])),
                    "direction": direction
                })
            
            return np_array, metadata
        except Exception as e:
            raise RuntimeError(f"Failed to load DICOM SEG: {e}")
  • Registration of the 'load-dicom-seg' tool in the MCP server, including name, description, and input schema.
    types.Tool(
        name="load-dicom-seg",
        description="Load a DICOM SEG file and associate it with a reference image",
        inputSchema={
            "type": "object",
            "properties": {
                "seg_file": {"type": "string", "description": "Path to a DICOM SEG file"},
                "reference_series_uid": {"type": "string", "description": "Series UID of the reference image"},
            },
            "required": ["seg_file"],
        },
    ),
  • JSON Schema for input validation of the 'load-dicom-seg' tool.
    inputSchema={
        "type": "object",
        "properties": {
            "seg_file": {"type": "string", "description": "Path to a DICOM SEG file"},
            "reference_series_uid": {"type": "string", "description": "Series UID of the reference image"},
        },
        "required": ["seg_file"],
    },

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/shaunporwal/DICOM-MCP'

If you have feedback or need assistance with the MCP directory API, please join our Discord server