Skip to main content
Glama

focal_statistics

Calculate moving window statistics like mean, min, max, or standard deviation on raster data for spatial pattern analysis in GIS workflows.

Instructions

Compute focal (moving window) statistics on a raster. Args: raster_path: Path to the input raster. statistic: Statistic to compute ('mean', 'min', 'max', 'std'). size: Window size (odd integer). output_path: Optional path to save the result. Returns: Dictionary with status, message, and output path if saved.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
raster_pathYes
statisticYes
sizeNo
output_pathNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The primary handler function for the 'focal_statistics' MCP tool. It computes focal statistics (mean, min, max, std) on raster data using a moving window via scipy.ndimage.generic_filter. The function is registered via the @gis_mcp.tool() decorator, which handles schema generation from type hints and docstring.
    @gis_mcp.tool()
    def focal_statistics(raster_path: str, statistic: str, size: int = 3, output_path: str = None) -> Dict[str, Any]:
        """
        Compute focal (moving window) statistics on a raster.
        Args:
            raster_path: Path to the input raster.
            statistic: Statistic to compute ('mean', 'min', 'max', 'std').
            size: Window size (odd integer).
            output_path: Optional path to save the result.
        Returns:
            Dictionary with status, message, and output path if saved.
        """
        try:
            import rasterio
            import numpy as np
            from scipy.ndimage import generic_filter
            with rasterio.open(raster_path) as src:
                data = src.read(1)
                profile = src.profile.copy()
                func = None
                if statistic == "mean":
                    func = np.mean
                elif statistic == "min":
                    func = np.min
                elif statistic == "max":
                    func = np.max
                elif statistic == "std":
                    func = np.std
                else:
                    raise ValueError(f"Unsupported statistic: {statistic}")
                filtered = generic_filter(data, func, size=size, mode='nearest')
            if output_path:
                output_path_resolved = resolve_path(output_path, relative_to_storage=True)
                output_path_resolved.parent.mkdir(parents=True, exist_ok=True)
                with rasterio.open(str(output_path_resolved), "w", **profile) as dst:
                    dst.write(filtered, 1)
                output_path = str(output_path_resolved)
            return {
                "status": "success",
                "message": f"Focal {statistic} computed successfully.",
                "output_path": output_path
            }
        except Exception as e:
            logger.error(f"Error in focal_statistics: {str(e)}")
            return {"status": "error", "message": str(e)}
  • Imports the rasterio_functions module (among others), which triggers the execution of decorators like @gis_mcp.tool() on functions such as focal_statistics, thereby registering the tool with the FastMCP server instance.
    from . import (
        geopandas_functions,
        shapely_functions,
        rasterio_functions,
        pyproj_functions,
        pysal_functions,
    )
  • A resource endpoint that lists available rasterio operations, including 'focal_statistics', for tool discovery.
    @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"
            ]
        }
  • The function signature and docstring define the input schema (parameters with types and descriptions) and output schema for the tool, used by FastMCP for validation.
    def focal_statistics(raster_path: str, statistic: str, size: int = 3, output_path: str = None) -> Dict[str, Any]:
        """
        Compute focal (moving window) statistics on a raster.
        Args:
            raster_path: Path to the input raster.
            statistic: Statistic to compute ('mean', 'min', 'max', 'std').
            size: Window size (odd integer).
            output_path: Optional path to save the result.
        Returns:
            Dictionary with status, message, and output path if saved.
        """
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 of behavioral disclosure. It explains the core operation (moving window statistics) and output format (dictionary with status, message, and output path), but lacks details on permissions, side effects, error handling, or computational intensity. It adequately describes what the tool does but misses advanced behavioral context.

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 efficiently structured with a clear purpose sentence followed by organized Args and Returns sections. Every sentence adds value, though the Returns section could be slightly more detailed given the output schema exists. It's appropriately sized for a 4-parameter tool.

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 complexity (spatial statistics operation), no annotations, 0% schema coverage, but with an output schema present, the description provides good coverage. It explains parameters thoroughly and the operation's nature, though it could benefit from more behavioral context (e.g., performance implications) to be fully complete.

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?

With 0% schema description coverage, the description compensates well by explaining all 4 parameters in the Args section: 'raster_path' (input raster path), 'statistic' (specific statistics with enum values), 'size' (window size with odd integer constraint), and 'output_path' (optional save location). This adds significant meaning beyond the bare schema.

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 focal (moving window) statistics on a raster') with the exact resource type ('raster'), distinguishing it from sibling tools like 'raster_band_statistics' or 'zonal_statistics' which perform different raster analyses. The opening sentence provides a complete purpose statement.

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 like 'raster_band_statistics' or 'zonal_statistics' from the sibling list, nor does it mention prerequisites or context for applying moving window statistics. 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