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"],
    },
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions loading and association but fails to detail critical aspects like required permissions, whether the operation is read-only or modifies data, error handling, or output format. This leaves significant gaps in understanding the tool's behavior.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, clear sentence that efficiently conveys the core action without unnecessary details. It is front-loaded and wastes no words, making it highly concise and well-structured for quick understanding.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of handling DICOM files, no annotations, and no output schema, the description is insufficient. It does not cover behavioral traits, error cases, or what the tool returns, leaving the agent with incomplete information for proper invocation and handling.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the input schema already documents both parameters ('seg_file' and 'reference_series_uid') adequately. The description adds no additional meaning beyond what the schema provides, such as explaining the association process or parameter interactions, meeting the baseline for high schema coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('Load a DICOM SEG file') and the resource ('associate it with a reference image'), making the purpose specific and understandable. However, it does not explicitly differentiate from sibling tools like 'load-dicom-series' or 'extract-dicom-metadata', which could handle related DICOM operations, so it falls short of a perfect score.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives, such as 'load-dicom-series' for general loading or 'extract-dicom-metadata' for metadata extraction. It lacks context on prerequisites, exclusions, or specific scenarios, leaving usage unclear.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other 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