Skip to main content
Glama

build_transform_and_save_weights

Create spatial weights matrices from geographic data files for spatial analysis, with options to apply transformations and save in standard formats.

Instructions

Pipeline: Read shapefile, build spatial weights, optionally transform, and save to file.

Parameters:

  • data_path: Path to point shapefile or GeoPackage

  • method: 'queen', 'rook', 'distance_band', 'knn'

  • id_field: Optional field name for IDs

  • threshold: Distance threshold (required if method='distance_band')

  • k: Number of neighbors (required if method='knn')

  • binary: True for binary weights, False for inverse distance (DistanceBand only)

  • transform_type: 'r', 'v', 'b', 'o', or 'd' (optional)

  • output_path: File path to save weights

  • format: 'gal' or 'gwt'

  • overwrite: Allow overwriting if file exists

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
data_pathYes
methodNoqueen
id_fieldNo
thresholdNo
kNo
binaryNo
transform_typeNo
output_pathNoweights.gal
formatNogal
overwriteNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The core handler function for the 'build_transform_and_save_weights' tool. It reads a shapefile or GeoPackage, constructs spatial weights using libpysal based on the specified method (queen, rook, distance_band, or knn), optionally applies a transformation (row-standardized, etc.), and saves the weights matrix to a GAL or GWT file. The @gis_mcp.tool() decorator registers it as an MCP tool.
    @gis_mcp.tool()
    def build_transform_and_save_weights(
        data_path: str,
        method: str = "queen",
        id_field: Optional[str] = None,
        threshold: Optional[float] = None,
        k: Optional[int] = None,
        binary: bool = True,
        transform_type: Optional[str] = None,
        output_path: str = "weights.gal",
        format: str = "gal",
        overwrite: bool = False
    ) -> Dict[str, Any]:
        """
        Pipeline: Read shapefile, build spatial weights, optionally transform, and save to file.
    
        Parameters:
        - data_path: Path to point shapefile or GeoPackage
        - method: 'queen', 'rook', 'distance_band', 'knn'
        - id_field: Optional field name for IDs
        - threshold: Distance threshold (required if method='distance_band')
        - k: Number of neighbors (required if method='knn')
        - binary: True for binary weights, False for inverse distance (DistanceBand only)
        - transform_type: 'r', 'v', 'b', 'o', or 'd' (optional)
        - output_path: File path to save weights
        - format: 'gal' or 'gwt'
        - overwrite: Allow overwriting if file exists
        """
        try:
            # --- Step 1: Check input file ---
            if not os.path.exists(data_path):
                return {"status": "error", "message": f"Data file not found: {data_path}"}
    
            gdf = gpd.read_file(data_path)
            if gdf.empty:
                return {"status": "error", "message": "Input file contains no features"}
    
            coords = [(geom.x, geom.y) for geom in gdf.geometry]
    
            # --- Step 2: Build weights ---
            import libpysal
            method = (method or "").lower()
            if method == "queen":
                w = libpysal.weights.Queen.from_dataframe(gdf, idVariable=id_field)
            elif method == "rook":
                w = libpysal.weights.Rook.from_dataframe(gdf, idVariable=id_field)
            elif method == "distance_band":
                if threshold is None:
                    return {"status": "error", "message": "Threshold is required for distance_band method"}
                if id_field and id_field in gdf.columns:
                    ids = gdf[id_field].tolist()
                    w = libpysal.weights.DistanceBand(coords, threshold=threshold, binary=binary, ids=ids)
                else:
                    w = libpysal.weights.DistanceBand(coords, threshold=threshold, binary=binary)
            elif method == "knn":
                if k is None:
                    return {"status": "error", "message": "k is required for knn method"}
                if id_field and id_field in gdf.columns:
                    ids = gdf[id_field].tolist()
                    w = libpysal.weights.KNN(coords, k=k, ids=ids)
                else:
                    w = libpysal.weights.KNN(coords, k=k)
            else:
                return {"status": "error", "message": f"Unsupported method: {method}"}
    
            # --- Step 3: Apply transformation if given ---
            if transform_type:
                transform_type = (transform_type or "").lower()
                if transform_type not in {"r", "v", "b", "o", "d"}:
                    return {"status": "error", "message": f"Invalid transform type: {transform_type}"}
                w.transform = transform_type
    
            # --- Step 4: Save weights to file ---
            format = (format or "").lower()
            if format not in {"gal", "gwt"}:
                return {"status": "error", "message": f"Invalid format: {format}"}
    
            if not output_path.lower().endswith(f".{format}"):
                output_path += f".{format}"
    
            if os.path.exists(output_path) and not overwrite:
                return {"status": "error", "message": f"File already exists: {output_path}. Set overwrite=True to replace it."}
    
            w.to_file(output_path, format=format)
    
            # --- Step 5: Build result ---
            return {
                "status": "success",
                "message": f"{method} weights built and saved successfully",
                "result": {
                    "path": output_path,
                    "format": format,
                    "n": int(w.n),
                    "transform": getattr(w, "transform", None),
                    "islands": list(w.islands) if hasattr(w, "islands") else [],
                },
            }
    
        except Exception as e:
            logger.error(f"Error in build_transform_and_save_weights: {str(e)}")
            return {"status": "error", "message": f"Failed to build and save weights: {str(e)}"}
  • Import of pysal_functions.py in main.py triggers automatic registration of all @gis_mcp.tool() decorated functions, including build_transform_and_save_weights, via Python import side effects.
    from . import (
        geopandas_functions,
        shapely_functions,
        rasterio_functions,
        pyproj_functions,
        pysal_functions,
    )
  • src/gis_mcp/mcp.py:1-6 (registration)
    Creation of the FastMCP server instance 'gis_mcp' used for tool registration 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 of behavioral disclosure. It describes the pipeline flow and file operations, but doesn't mention permission requirements, error conditions, rate limits, or what happens when files are overwritten. The description covers the basic operation but lacks detailed behavioral context for a complex 10-parameter 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 pipeline summary followed by parameter details. Every sentence earns its place, though the parameter list is lengthy (necessary given the complexity). It's appropriately sized for a 10-parameter tool with no schema descriptions.

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 complexity (10 parameters, spatial operations) and the presence of an output schema, the description provides good coverage. It explains the multi-step pipeline, parameter dependencies, and file operations. The output schema handles return values, so the description appropriately focuses on the transformation process and parameter semantics.

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 detailed parameter explanations. It clarifies when parameters are required based on method choice, explains what each parameter controls (e.g., 'binary: True for binary weights, False for inverse distance'), and provides format options. This adds significant value 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 tool's purpose as a pipeline that reads shapefiles, builds spatial weights, optionally transforms them, and saves to file. It uses specific verbs (read, build, transform, save) and distinguishes from siblings like 'distance_band_weights' or 'knn_weights' by combining multiple steps into one workflow.

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 explanations (e.g., 'required if method='distance_band''), but doesn't explicitly state when to use this tool versus alternatives like 'build_and_transform_weights' or simpler weight-building tools. It provides context about parameter dependencies but lacks explicit guidance on tool selection.

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