Skip to main content
Glama

extract-dicom-metadata

Extract detailed metadata from DICOM medical image files to access structured information about patient data, imaging parameters, and study details.

Instructions

Extract detailed metadata from a DICOM file

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
dicom_fileYesPath to a DICOM file

Implementation Reference

  • Core handler function that implements the logic to extract structured metadata from a single DICOM file using pydicom.
    def extract_dicom_metadata(dicom_file: str) -> Dict[str, Any]:
        """Extract comprehensive metadata from a DICOM file"""
        try:
            ds = pydicom.dcmread(dicom_file, stop_before_pixels=True)
            
            # Create a clean dictionary of metadata
            metadata = {}
            
            # Patient information
            metadata["patient"] = {
                "id": getattr(ds, "PatientID", None),
                "name": str(getattr(ds, "PatientName", "")),
                "birth_date": getattr(ds, "PatientBirthDate", None),
                "sex": getattr(ds, "PatientSex", None)
            }
            
            # Study information
            metadata["study"] = {
                "instance_uid": getattr(ds, "StudyInstanceUID", None),
                "id": getattr(ds, "StudyID", None),
                "date": getattr(ds, "StudyDate", None),
                "time": getattr(ds, "StudyTime", None),
                "description": getattr(ds, "StudyDescription", None)
            }
            
            # Series information
            metadata["series"] = {
                "instance_uid": getattr(ds, "SeriesInstanceUID", None),
                "number": getattr(ds, "SeriesNumber", None),
                "date": getattr(ds, "SeriesDate", None),
                "time": getattr(ds, "SeriesTime", None),
                "description": getattr(ds, "SeriesDescription", None),
                "modality": getattr(ds, "Modality", None)
            }
            
            # Image information
            metadata["image"] = {
                "sop_instance_uid": getattr(ds, "SOPInstanceUID", None),
                "sop_class_uid": getattr(ds, "SOPClassUID", None),
                "instance_number": getattr(ds, "InstanceNumber", None),
                "rows": getattr(ds, "Rows", None),
                "columns": getattr(ds, "Columns", None),
                "pixel_spacing": getattr(ds, "PixelSpacing", None),
                "slice_thickness": getattr(ds, "SliceThickness", None),
                "slice_location": getattr(ds, "SliceLocation", None),
                "window_center": getattr(ds, "WindowCenter", None),
                "window_width": getattr(ds, "WindowWidth", None)
            }
            
            # Equipment information
            metadata["equipment"] = {
                "manufacturer": getattr(ds, "Manufacturer", None),
                "model": getattr(ds, "ManufacturerModelName", None),
                "software_versions": getattr(ds, "SoftwareVersions", None)
            }
            
            return metadata
        except Exception as e:
            raise RuntimeError(f"Failed to extract DICOM metadata: {e}")
  • Tool registration in list_tools(), including name, description, and input schema for 'dicom_file' path.
    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"],
        },
    ),
  • MCP call_tool handler dispatch for the tool: validates input file, calls extract_dicom_metadata, and returns JSON-formatted metadata as text content.
    elif name == "extract-dicom-metadata":
        dicom_file = arguments.get("dicom_file")
        if not dicom_file or not os.path.isfile(dicom_file):
            raise ValueError(f"Invalid DICOM file: {dicom_file}")
            
        # Extract metadata
        metadata = extract_dicom_metadata(dicom_file)
        
        return [
            types.TextContent(
                type="text",
                text=json.dumps(metadata, indent=2, default=str)
            )
        ]
  • JSON schema defining the input: object with required 'dicom_file' string path.
    inputSchema={
        "type": "object",
        "properties": {
            "dicom_file": {"type": "string", "description": "Path to a DICOM file"},
        },
        "required": ["dicom_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 states the tool extracts metadata but doesn't describe what 'detailed metadata' includes (e.g., patient info, study details, image parameters), potential errors (e.g., invalid file paths, corrupted DICOM data), or performance aspects (e.g., speed, memory usage). This leaves significant gaps for a tool that likely returns complex data.

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, efficient sentence that directly states the tool's purpose without unnecessary words. It's front-loaded with the core action and resource, making it easy to parse. Every part of the sentence contributes essential information, achieving optimal conciseness.

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 DICOM metadata extraction and the lack of annotations and output schema, the description is incomplete. It doesn't explain what 'detailed metadata' entails, the format of the output (e.g., JSON, structured data), or error handling. For a tool with no structured output documentation, this leaves the agent with insufficient context to understand the full behavior and results.

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%, with the single parameter 'dicom_file' documented as 'Path to a DICOM file' in the schema. The description doesn't add any additional meaning beyond this (e.g., file format requirements, path resolution rules). Given the high schema coverage, the baseline score of 3 is appropriate as the schema handles the parameter documentation adequately.

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 ('extract') and target resource ('detailed metadata from a DICOM file'), making the purpose immediately understandable. It doesn't explicitly differentiate from sibling tools like 'scan-dicom-directory' or 'load-dicom-series', but the focus on metadata extraction is specific enough to avoid confusion with those operations.

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. It doesn't mention prerequisites (e.g., needing a valid DICOM file), exclusions (e.g., not for non-DICOM files), or comparisons to siblings like 'scan-dicom-directory' for batch processing or 'load-dicom-seg' for segmentation data. Usage is implied but not explicitly defined.

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