Skip to main content
Glama

weighted_band_sum

Calculate a weighted sum of multi-band raster data using specified weights to produce a single-band output for geospatial analysis.

Instructions

Compute a weighted sum of all bands in a raster using specified weights.

Parameters:

  • source: Path to the input multi-band raster file.

  • weights: List of weights (must match number of bands and sum to 1).

  • destination: Path to save the output single-band raster.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sourceYes
weightsYes
destinationYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The handler function that implements the core logic of weighted_band_sum: reads a multi-band raster, applies weights to each band, computes the sum, and writes the result to a new single-band raster file.
    def weighted_band_sum(
        source: str,
        weights: List[float],
        destination: str
    ) -> Dict[str, Any]:
        """
        Compute a weighted sum of all bands in a raster using specified weights.
    
        Parameters:
        - source:      Path to the input multi-band raster file.
        - weights:     List of weights (must match number of bands and sum to 1).
        - destination: Path to save the output single-band raster.
        """
        try:
            import os
            import numpy as np
            import rasterio
    
            src_path = os.path.expanduser(source.replace("`", ""))
            dst_path = os.path.expanduser(destination.replace("`", ""))
    
            with rasterio.open(src_path) as src:
                count = src.count
                if len(weights) != count:
                    raise ValueError(f"Number of weights ({len(weights)}) does not match number of bands ({count}).")
    
                if not np.isclose(sum(weights), 1.0, atol=1e-6):
                    raise ValueError("Sum of weights must be 1.0.")
    
                weighted = np.zeros((src.height, src.width), dtype="float32")
    
                for i in range(1, count + 1):
                    band = src.read(i).astype("float32")
                    weighted += weights[i - 1] * band
    
                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(weighted, 1)
    
            return {
                "status": "success",
                "destination": str(dst_path),
                "message": f"Weighted band sum computed and saved to '{dst_path}'."
            }
    
        except Exception as e:
            raise ValueError(f"Failed to compute weighted sum: {e}")
  • Resource function that lists 'weighted_band_sum' among available rasterio operations, indicating its registration in the MCP toolset.
    @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"
            ]
        }
  • src/gis_mcp/mcp.py:1-6 (registration)
    Creates the FastMCP instance 'gis_mcp' to which tools like weighted_band_sum are registered via decorators.
    # MCP imports using the new SDK patterns
    from fastmcp import FastMCP
    
    
    gis_mcp = FastMCP("GIS MCP")
Behavior3/5

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

With no annotations provided, the description carries the full burden. It discloses key behavioral traits: the tool performs a computation (not just reading), creates a new output file at 'destination', and has constraints on weights. However, it doesn't mention file format requirements, error handling, performance characteristics, or whether it modifies the source file.

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 efficiently structured with a clear purpose statement followed by a bulleted parameter list. Every sentence earns its place by defining the operation and explaining parameter constraints without redundancy. It's appropriately sized for a tool with three parameters.

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's moderate complexity (mathematical raster operation), no annotations, and the presence of an output schema (which handles return values), the description is reasonably complete. It covers the core operation and parameters but could better address behavioral aspects like file I/O behavior or weight validation errors.

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

Parameters4/5

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

The schema description coverage is 0%, so the description must compensate. It provides clear semantic meaning for all three parameters: 'source' as input raster path, 'weights' as a normalized list matching band count, and 'destination' as output path. This adds substantial value beyond the bare schema, though it could specify weight ranges or path format examples.

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 tool's purpose with specific verb ('Compute') and resource ('weighted sum of all bands in a raster'), distinguishing it from sibling tools like 'extract_band', 'concat_bands', or 'raster_algebra' which perform different raster operations. It precisely defines the mathematical operation and output format.

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 through the parameter descriptions (e.g., weights 'must match number of bands and sum to 1'), suggesting when to use this tool for band aggregation. However, it lacks explicit guidance on when to choose this over alternatives like 'raster_band_statistics' or 'raster_algebra', and doesn't mention prerequisites or exclusions.

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