Skip to main content
Glama

load-dicom-seg

Load a DICOM SEG file and associate it with a reference image by specifying the file path and reference Series UID. Supports medical image workflows in the DICOM-MCP environment.

Instructions

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

Input Schema

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

Implementation Reference

  • Core implementation of the load_dicom_seg tool: reads DICOM SEG file using pydicom_seg, converts to numpy array, extracts segment metadata, and aligns with reference image if provided.
    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}")
  • MCP server handler dispatch for 'load-dicom-seg' tool: validates arguments, retrieves reference image from cache if provided, calls the core load_dicom_seg function, caches the result, and returns a text summary.
    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)}" ) ]
  • Input schema definition for the 'load-dicom-seg' tool as returned by list_tools().
    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"], }, ),
  • Registration of all tools including 'load-dicom-seg' in the handle_list_tools() function.
    return [ types.Tool( name="add-note", description="Add a new note", inputSchema={ "type": "object", "properties": { "name": {"type": "string"}, "content": {"type": "string"}, }, "required": ["name", "content"], }, ), types.Tool( name="scan-dicom-directory", description="Scan a directory for DICOM files and organize them into series", inputSchema={ "type": "object", "properties": { "directory": {"type": "string", "description": "Path to directory containing DICOM files"}, }, "required": ["directory"], }, ), types.Tool( name="extract-dicom-metadata", description="Extract detailed metadata from a DICOM file", inputSchema={ "type": "object", "properties": { "dicom_file": {"type": "string", "description": "Path to a DICOM file"}, }, "required": ["dicom_file"], }, ), types.Tool( name="load-dicom-series", description="Load a DICOM series into memory for processing", inputSchema={ "type": "object", "properties": { "series_uid": {"type": "string", "description": "Series UID of the DICOM series to load"}, }, "required": ["series_uid"], }, ), 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"], }, ), types.Tool( name="crop-dicom-image", description="Crop a loaded DICOM image by removing boundary percentage", inputSchema={ "type": "object", "properties": { "series_uid": {"type": "string", "description": "Series UID of the loaded DICOM image"}, "boundary_percentage": {"type": "number", "description": "Percentage of image to crop from each boundary (0.0-0.5)"}, }, "required": ["series_uid"], }, ) ]

Other Tools

Related Tools

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