Skip to main content
Glama

raster_algebra

Perform addition or subtraction on raster bands to combine or compare geospatial data, with automatic alignment handling for accurate results.

Instructions

Perform algebraic operations (addition or subtraction) on two raster bands, handling alignment issues automatically.

Parameters:

  • raster1: Path to the first raster (.tif).

  • raster2: Path to the second raster (.tif).

  • band_index: Index of the band to process (1-based index).

  • operation: Either "add" or "subtract" to specify the calculation.

  • destination: Path to save the result as a new raster.

The function aligns rasters if needed, applies the selected operation, and saves the result.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
raster1Yes
raster2Yes
band_indexYes
operationYes
destinationYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The core handler function for the 'raster_algebra' tool. It takes two raster paths, a band index, an operation ('add' or 'subtract'), and a destination path. Automatically aligns the rasters if CRS, transform, or shape differ, performs the operation on the specified bands, and writes the result to the output file.
    def raster_algebra(
        raster1: str,
        raster2: str,
        band_index: int,
        operation: str,  # User selects "add" or "subtract"
        destination: str
    ) -> Dict[str, Any]:
        """
        Perform algebraic operations (addition or subtraction) on two raster bands, 
        handling alignment issues automatically.
    
        Parameters:
        - raster1:     Path to the first raster (.tif).
        - raster2:     Path to the second raster (.tif).
        - band_index:  Index of the band to process (1-based index).
        - operation:   Either "add" or "subtract" to specify the calculation.
        - destination: Path to save the result as a new raster.
    
        The function aligns rasters if needed, applies the selected operation, and saves the result.
        """
        try:
            import rasterio
            import numpy as np
            from rasterio.warp import reproject, calculate_default_transform, Resampling
    
            # Expand file paths
            r1 = os.path.expanduser(raster1.replace("`", ""))
            r2 = os.path.expanduser(raster2.replace("`", ""))
            dst = os.path.expanduser(destination.replace("`", ""))
    
            # Open the raster files
            with rasterio.open(r1) as src1, rasterio.open(r2) as src2:
                # Ensure alignment of rasters
                if src1.crs != src2.crs or src1.transform != src2.transform or src1.shape != src2.shape:
                    transform, width, height = calculate_default_transform(
                        src2.crs, src1.crs, src2.width, src2.height, *src2.bounds
                    )
                    aligned_data = np.zeros((height, width), dtype="float32")
                    reproject(
                        source=src2.read(band_index),
                        destination=aligned_data,
                        src_transform=src2.transform,
                        src_crs=src2.crs,
                        dst_transform=transform,
                        dst_crs=src1.crs,
                        resampling=Resampling.bilinear
                    )
                    band2 = aligned_data
                else:
                    band2 = src2.read(band_index).astype("float32")
    
                band1 = src1.read(band_index).astype("float32")
    
                # Perform the selected operation
                if operation.lower() == "add":
                    result = band1 + band2
                elif operation.lower() == "subtract":
                    result = band1 - band2
                else:
                    raise ValueError("Invalid operation. Use 'add' or 'subtract'.")
    
                # Prepare output raster metadata
                profile = src1.profile.copy()
                profile.update(dtype="float32", count=1)
    
            # Ensure the output directory exists
            os.makedirs(os.path.dirname(dst) or ".", exist_ok=True)
    
            # Save the result to a new raster file
            with rasterio.open(dst, "w", **profile) as dstfile:
                dstfile.write(result, 1)
    
            return {
                "status": "success",
                "destination": dst,
                "message": f"Raster operation '{operation}' completed and saved."
            }
    
        except Exception as e:
            raise ValueError(f"Failed to perform raster operation: {e}")
  • Resource endpoint listing 'raster_algebra' as an available rasterio operation, which serves as a discovery mechanism for the tool.
    @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"
            ]
        }
  • Imports the rasterio_functions module in the main entry point, which executes the decorators to register the 'raster_algebra' tool with the MCP server.
    from . import (
        geopandas_functions,
        shapely_functions,
        rasterio_functions,
        pyproj_functions,
        pysal_functions,
    )
Behavior3/5

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

With no annotations provided, the description carries full burden. It discloses key behaviors: automatic alignment handling, that it creates a new raster file, and the specific operations supported. However, it doesn't mention performance characteristics, memory requirements, error handling, or what happens with invalid inputs. The description adds value but lacks comprehensive behavioral context for a mutation tool.

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 well-structured with a clear purpose statement followed by parameter documentation and behavioral details. Every sentence adds value, though the two-sentence structure could be slightly more front-loaded. No redundant information or wasted words are present.

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

Completeness4/5

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

Given the tool has 5 parameters, no annotations, but does have an output schema, the description provides good coverage of inputs and core behavior. The output schema likely handles return values, so the description appropriately focuses on parameter semantics and operational context. For a raster processing tool with mutation effects, it could benefit from more error/edge-case information.

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?

With 0% schema description coverage, the description fully compensates by providing clear semantics for all 5 parameters: file paths for inputs/output, band index interpretation (1-based), operation options, and destination purpose. Each parameter's meaning and format is explicitly documented beyond what the bare schema provides.

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 tool performs algebraic operations (addition/subtraction) on two raster bands, which is a specific verb+resource combination. It distinguishes from siblings by focusing on band-level arithmetic rather than other raster operations like clipping or reprojecting. However, it doesn't explicitly contrast with 'weighted_band_sum' which might be a similar sibling tool.

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

Usage Guidelines3/5

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

The description implies usage when needing to add or subtract raster bands with automatic alignment handling, but doesn't explicitly state when to use this versus alternatives like 'concat_bands' or 'weighted_band_sum'. No guidance on prerequisites, error conditions, or when not to use this tool is provided.

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