Skip to main content
Glama

resample_raster

Resample raster datasets by scaling resolution with specified methods to adjust spatial detail for analysis or display needs.

Instructions

Resample a raster dataset by a scale factor and save the result.

Parameters:

  • source: local path or HTTPS URL of the source raster.

  • scale_factor: multiplicative factor for width/height (e.g., 0.5 to halve resolution, 2.0 to double).

  • resampling: resampling method name: "nearest", "bilinear", "cubic", etc.

  • destination: local filesystem path for the resampled raster.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sourceYes
scale_factorYes
resamplingYes
destinationYes

Implementation Reference

  • The core handler function for the 'resample_raster' tool. It opens a source raster (local or URL), resamples it by a given scale_factor using the specified resampling method (e.g., nearest, bilinear), computes new dimensions and transform, and writes the result to a destination file using rasterio.
    @gis_mcp.tool()
    def resample_raster(
        source: str,
        scale_factor: float,
        resampling: str,
        destination: str
    ) -> Dict[str, Any]:
        """
        Resample a raster dataset by a scale factor and save the result.
        
        Parameters:
        - source:       local path or HTTPS URL of the source raster.
        - scale_factor: multiplicative factor for width/height 
                        (e.g., 0.5 to halve resolution, 2.0 to double).
        - resampling:   resampling method name: "nearest", "bilinear", "cubic", etc.
        - destination:  local filesystem path for the resampled raster.
        """
        try:
            import numpy as np
            import rasterio
            from rasterio.enums import Resampling
            from rasterio.transform import Affine
    
            # Strip backticks if present
            src_clean = source.replace("`", "")
            dst_clean = destination.replace("`", "")
    
            # Open source (remote or local)
            if src_clean.lower().startswith("https://"):
                src = rasterio.open(src_clean)
            else:
                src_path = os.path.expanduser(src_clean)
                if not os.path.isfile(src_path):
                    raise FileNotFoundError(f"Source raster not found at '{src_path}'.")
                src = rasterio.open(src_path)
    
            # Validate scale factor
            if scale_factor <= 0:
                raise ValueError("Scale factor must be positive.")
    
            # Compute new dimensions
            new_width  = int(src.width  * scale_factor)
            new_height = int(src.height * scale_factor)
    
            if new_width == 0 or new_height == 0:
                raise ValueError("Resulting raster dimensions are zero. Check scale_factor.")
    
            # Map resampling method string to Resampling enum
            resampling_enum = getattr(Resampling, resampling.lower(), Resampling.nearest)
    
            # Read and resample all bands
            data = src.read(
                out_shape=(src.count, new_height, new_width),
                resampling=resampling_enum
            )
    
            # Validate resampled data
            if data is None or data.size == 0:
                raise ValueError("No data was resampled.")
    
            # Calculate the new transform to reflect the resampling
            new_transform = src.transform * Affine.scale(
                (src.width  / new_width),
                (src.height / new_height)
            )
    
            # Update profile
            profile = src.profile.copy()
            profile.update({
                "height":    new_height,
                "width":     new_width,
                "transform": new_transform
            })
            src.close()
    
            # Ensure destination directory exists
            dst_path = os.path.expanduser(dst_clean)
            os.makedirs(os.path.dirname(dst_path) or ".", exist_ok=True)
    
            # Write the resampled raster
            with rasterio.open(dst_path, "w", **profile) as dst:
                dst.write(data)
    
            return {
                "status":      "success",
                "destination": str(dst_path),
                "message":     f"Raster resampled by factor {scale_factor} using '{resampling}' and saved to '{dst_path}'."
            }
    
        except Exception as e:
            # Log error and raise for MCP to report
            logger.error(f"Error resampling raster '{source}': {e}")
            raise ValueError(f"Failed to resample raster: {e}")
  • MCP resource that lists available rasterio operations, including 'resample_raster', serving as a discovery/registration 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"
            ]
        }
  • Definition of the gis_mcp FastMCP instance used for tool and resource registration via decorators (@gis_mcp.tool(), @gis_mcp.resource()). All tools in rasterio_functions.py are registered to this instance.
    # MCP imports using the new SDK patterns
    from fastmcp import FastMCP
    
    
    gis_mcp = FastMCP("GIS MCP")

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