Skip to main content
Glama

knn_weights

Generate spatial weights for k-nearest neighbors analysis from point data to identify spatial relationships and patterns in geographic datasets.

Instructions

Create a k-nearest neighbors spatial weights (W) object from point data.

  • data_path: path to point shapefile or GeoPackage

  • k: number of nearest neighbors

  • id_field: optional attribute name to use as observation IDs

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
data_pathYes
kYes
id_fieldNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The knn_weights tool handler: creates k-nearest neighbors spatial weights matrix (W) from geospatial point data using libpysal.weights.KNN, handles ID fields, converts numpy types for JSON serialization, and returns structured summary with previews and stats.
    @gis_mcp.tool()
    def knn_weights(
        data_path: str,
        k: int,
        id_field: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        Create a k-nearest neighbors spatial weights (W) object from point data.
    
        - data_path: path to point shapefile or GeoPackage
        - k: number of nearest neighbors
        - id_field: optional attribute name to use as observation IDs
        """
        try:
            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"}
    
            # Extract coordinates
            coords = [(geom.x, geom.y) for geom in gdf.geometry]
    
            # Create KNN weights
            import libpysal
            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)
    
            ids = w.id_order
            # Convert ids to native Python types immediately
            ids = [int(i) if isinstance(i, (np.integer, np.int32, np.int64)) else i for i in ids]
            neighbor_counts = [int(w.cardinalities[i]) if isinstance(w.cardinalities[i], (np.integer, np.int32, np.int64)) else w.cardinalities[i] for i in ids]
            islands = [int(i) if isinstance(i, (np.integer, np.int32, np.int64)) else i for i in list(w.islands)] if hasattr(w, "islands") else []
    
            # Previews - convert to native Python types immediately
            preview_ids = ids[:5]
            neighbors_preview = {}
            weights_preview = {}
            for i in preview_ids:
                # Convert neighbor IDs and weights to native Python types
                neighbors = w.neighbors.get(i, [])
                weights_list = w.weights.get(i, [])
                neighbors_preview[int(i) if isinstance(i, (np.integer, np.int32, np.int64)) else i] = [
                    int(n) if isinstance(n, (np.integer, np.int32, np.int64, np.int8, np.int16)) else n for n in neighbors
                ]
                weights_preview[int(i) if isinstance(i, (np.integer, np.int32, np.int64)) else i] = [
                    float(w_val) if isinstance(w_val, (np.floating, np.float32, np.float64, np.float16)) 
                    else (int(w_val) if isinstance(w_val, (np.integer, np.int32, np.int64, np.int8, np.int16)) else w_val) 
                    for w_val in weights_list
                ]
    
            result = {
                "n": int(w.n),
                "id_count": int(len(ids)),
                "k": int(k),
                "id_field": id_field,
                "neighbors_stats": {
                    "min": int(min(neighbor_counts)) if neighbor_counts else 0,
                    "max": int(max(neighbor_counts)) if neighbor_counts else 0,
                    "mean": float(np.mean(neighbor_counts)) if neighbor_counts else 0.0,
                },
                "islands": islands,
                "neighbors_preview": neighbors_preview,
                "weights_preview": weights_preview,
            }
    
            # Convert numpy types to native Python types for serialization (recursive, final pass)
            def convert_numpy_types(obj):
                """Recursively convert numpy types to native Python types."""
                if obj is None:
                    return None
                if isinstance(obj, dict):
                    return {convert_numpy_types(k) if isinstance(k, (np.integer, np.int32, np.int64)) else k: convert_numpy_types(v) for k, v in obj.items()}
                elif isinstance(obj, (list, tuple)):
                    return [convert_numpy_types(item) for item in obj]
                elif isinstance(obj, (np.integer, np.int32, np.int64, np.int8, np.int16)):
                    return int(obj)
                elif isinstance(obj, (np.floating, np.float32, np.float64, np.float16)):
                    return float(obj)
                elif isinstance(obj, np.ndarray):
                    return obj.tolist()
                elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes)):
                    # Handle other iterable types
                    return [convert_numpy_types(item) for item in obj]
                else:
                    return obj
            
            result = convert_numpy_types(result)
            
            return {
                "status": "success",
                "message": "KNN spatial weights constructed successfully",
                "result": result,
                "weights_info": result,  # Also include as weights_info for test compatibility
            }
    
        except Exception as e:
            logger.error(f"Error creating KNN weights: {str(e)}")
            return {"status": "error", "message": f"Failed to create KNN weights: {str(e)}"}
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It states the tool creates a spatial weights object but doesn't describe what that object contains, how it's structured, whether it modifies input data, what permissions are required, or any performance characteristics. For a tool that presumably generates computational geometry results, this leaves significant behavioral gaps.

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 opening sentence followed by bullet points for parameters. Every element serves a purpose with zero wasted words, making it easy to scan and understand quickly despite the technical nature of the tool.

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

Completeness3/5

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

Given the tool has an output schema (which presumably describes the weights object), the description doesn't need to explain return values. However, for a spatial analysis tool with no annotations and complex sibling relationships, the description should provide more context about when to use this specific weights method and what the resulting object represents in practical terms.

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 three parameters: 'data_path' as path to point shapefile/GeoPackage, 'k' as number of nearest neighbors, and 'id_field' as optional attribute name for observation IDs. This adds meaningful context beyond the bare schema types, though it doesn't specify format details or constraints for the data_path parameter.

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 creates a k-nearest neighbors spatial weights object from point data, specifying both the action ('create') and resource ('spatial weights object'). It distinguishes from many siblings by focusing on spatial weights generation rather than general geometry operations, though it doesn't explicitly differentiate from similar weights tools like 'distance_band_weights' or 'weights_from_shapefile'.

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. With siblings like 'distance_band_weights' and 'weights_from_shapefile' that also create spatial weights, there's no indication of when k-nearest neighbors is preferred over other weighting methods or what specific use cases this tool addresses.

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