Skip to main content
Glama

compute_ndvi

Calculate vegetation health by computing NDVI from red and near-infrared bands in raster data, then save results as a GeoTIFF file.

Instructions

Compute NDVI (Normalized Difference Vegetation Index) and save to GeoTIFF.

Parameters:

  • source: input raster path.

  • red_band_index: index of red band (1-based).

  • nir_band_index: index of near-infrared band (1-based).

  • destination: output NDVI raster path.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sourceYes
red_band_indexYes
nir_band_indexYes
destinationYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The core handler function for the compute_ndvi MCP tool. It reads specified red and NIR bands from the input raster, computes NDVI using the formula (NIR - Red) / (NIR + Red), handles division by zero, copies metadata, and writes the result to a new GeoTIFF file.
    @gis_mcp.tool()
    def compute_ndvi(
        source: str,
        red_band_index: int,
        nir_band_index: int,
        destination: str
    ) -> Dict[str, Any]:
        """
        Compute NDVI (Normalized Difference Vegetation Index) and save to GeoTIFF.
    
        Parameters:
        - source:            input raster path.
        - red_band_index:    index of red band (1-based).
        - nir_band_index:    index of near-infrared band (1-based).
        - destination:       output NDVI raster path.
        """
        try:
            import rasterio
            import numpy as np
    
            src_path = os.path.expanduser(source.replace("`", ""))
            dst_path = os.path.expanduser(destination.replace("`", ""))
    
            with rasterio.open(src_path) as src:
                red = src.read(red_band_index).astype("float32")
                nir = src.read(nir_band_index).astype("float32")
                ndvi = (nir - red) / (nir + red + 1e-6)  # avoid division by zero
    
                profile = src.profile.copy()
                profile.update(dtype="float32", count=1)
    
            os.makedirs(os.path.dirname(dst_path) or ".", exist_ok=True)
    
            with rasterio.open(dst_path, "w", **profile) as dst:
                dst.write(ndvi, 1)
    
            return {
                "status": "success",
                "destination": str(dst_path),
                "message": f"NDVI calculated and saved to '{dst_path}'."
            }
    
        except Exception as e:
            raise ValueError(f"Failed to compute NDVI: {e}")
  • MCP resource that lists 'compute_ndvi' among available rasterio operations, effectively advertising the tool's availability.
    @gis_mcp.resource("gis://operation/rasterio")
    def get_rasterio_operations() -> Dict[str, List[str]]:
        """List available rasterio operations."""
        return {
            "operations": [
                "metadata_raster",
                "get_raster_crs",
                "clip_raster_with_shapefile",
                "resample_raster",
                "reproject_raster",
                "weighted_band_sum",
                "concat_bands",
                "raster_algebra",
                "compute_ndvi",
                "raster_histogram",
                "tile_raster",
                "raster_band_statistics",
                "extract_band",
                "zonal_statistics",
                "reclassify_raster",
                "focal_statistics",
                "hillshade",
                "write_raster"
            ]
        }
  • Import statements in the main entry point that trigger the execution of decorators in rasterio_functions.py, registering the compute_ndvi tool with the FastMCP instance.
    from . import (
        geopandas_functions,
        shapely_functions,
        rasterio_functions,
        pyproj_functions,
        pysal_functions,
    )
  • Definition of the gis_mcp FastMCP instance used by the @gis_mcp.tool() decorator to register tools including compute_ndvi.
    # MCP imports using the new SDK patterns
    from fastmcp import FastMCP
    
    
    gis_mcp = FastMCP("GIS MCP")
Behavior2/5

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

No annotations are provided, so the description carries full burden. It mentions the action ('compute and save') but lacks critical behavioral details: whether it overwrites existing files at the destination, what permissions are needed, error handling for invalid band indices, computational intensity, or output specifics beyond 'GeoTIFF'. The description is minimal beyond stating the core operation.

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

Conciseness4/5

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

The description is appropriately sized and front-loaded: the first sentence states the purpose and output, followed by a structured parameter list. Every sentence earns its place, though the parameter formatting could be slightly more concise. No redundant information is present.

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

Completeness3/5

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

Given 4 parameters with 0% schema coverage and no annotations, the description does well on parameters but lacks behavioral context for a mutation tool (writes files). An output schema exists, so return values needn't be explained. However, for a tool that performs computation and file I/O, more guidance on errors, overwrites, or input requirements would improve completeness.

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

Parameters5/5

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

Schema description coverage is 0%, so the description must fully compensate. It explicitly lists all 4 parameters with clear semantics: 'input raster path', 'index of red band (1-based)', 'index of near-infrared band (1-based)', and 'output NDVI raster path'. This adds essential meaning beyond the bare schema types, clarifying band indexing and file paths.

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

Purpose5/5

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

The description clearly states the specific action ('Compute NDVI'), defines the acronym, specifies the resource ('input raster'), and indicates the output format ('save to GeoTIFF'). It distinguishes itself from sibling tools by focusing on NDVI calculation rather than other raster/vector operations like 'clip_raster_with_shapefile' or 'reproject_raster'.

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., input raster must have specific bands), when NDVI is appropriate versus other vegetation indices, or refer to sibling tools like 'extract_band' or 'raster_algebra' that might be related. Usage is implied only through parameter descriptions.

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/mahdin75/gis-mcp'

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