Skip to main content
Glama

join_counts

Calculate spatial autocorrelation for binary variables in shapefiles to identify clustering patterns using join count statistics.

Instructions

Global Binary Join Counts.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
shapefile_pathYes
dependent_varNoLAND_USE
target_crsNoEPSG:4326
distance_thresholdNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • Main handler for the 'join_counts' MCP tool. Loads shapefile, creates spatial weights, computes global binary join counts using esda.Join_Counts, and returns statistics including join counts, expected, variance, z-score, p-value, and data preview.
    @gis_mcp.tool()
    def join_counts(shapefile_path: str, dependent_var: str = "LAND_USE", target_crs: str = "EPSG:4326",
                    distance_threshold: float = 100000) -> Dict[str, Any]:
        """Global Binary Join Counts."""
        gdf, y, w, (threshold, unit), err = pysal_load_data(shapefile_path, dependent_var, target_crs, distance_threshold)
        if err:
            return {"status": "error", "message": err}
    
        # Join counts requires binary/categorical data - user must ensure y is binary (0/1 or True/False)
        import esda
        stat = esda.Join_Counts(y, w)
        preview = gdf[['geometry', dependent_var]].head(5).copy()
        preview['geometry'] = preview['geometry'].apply(lambda g: g.wkt)
    
        # Join_Counts attributes: J (total joins), bb, ww, bw, etc.
        join_count_val = None
        if hasattr(stat, "J"):
            join_count_val = float(stat.J)
        elif hasattr(stat, "jc"):
            join_count_val = float(stat.jc)
        elif hasattr(stat, "join_count"):
            join_count_val = float(stat.join_count)
        
        # Handle expected, variance, z_score - these might be DataFrames or scalars
        def safe_float(val):
            """Convert value to float, handling DataFrames and numpy types."""
            if val is None:
                return None
            if isinstance(val, pd.DataFrame):
                # If it's a DataFrame, extract the first value
                return float(val.iloc[0, 0]) if not val.empty else None
            if isinstance(val, (np.ndarray, list, tuple)):
                return float(val[0]) if len(val) > 0 else None
            try:
                return float(val)
            except (ValueError, TypeError):
                return None
        
        expected_val = getattr(stat, "expected", None)
        variance_val = getattr(stat, "variance", None)
        z_score_val = getattr(stat, "z_score", None)
        p_val = None
        if hasattr(stat, "p_value"):
            p_val = safe_float(stat.p_value)
        elif hasattr(stat, "p_sim"):
            p_val = safe_float(stat.p_sim)
        
        return {
            "status": "success",
            "message": f"Join Counts completed successfully (threshold: {threshold} {unit})",
            "result": {
                "join_counts": join_count_val,
                "expected": safe_float(expected_val),
                "variance": safe_float(variance_val),
                "z_score": safe_float(z_score_val),
                "p_value": p_val,
                "data_preview": preview.to_dict(orient="records")
            }
        }
  • Shared helper function called by 'join_counts' (and other ESDA tools) to load GeoDataFrame, validate inputs, reproject, compute effective distance threshold, create row-standardized DistanceBand weights, and handle islands by zeroing their weights.
    def pysal_load_data(shapefile_path: str, dependent_var: str, target_crs: str, distance_threshold: float):
        """Common loader and weight creation for esda statistics."""
        if not os.path.exists(shapefile_path):
            return None, None, None, None, f"Shapefile not found: {shapefile_path}"
    
        gdf = gpd.read_file(shapefile_path)
        if dependent_var not in gdf.columns:
            return None, None, None, None, f"Dependent variable '{dependent_var}' not found in shapefile columns"
    
        gdf = gdf.to_crs(target_crs)
    
        effective_threshold = distance_threshold
        unit = "meters"
        if target_crs.upper() == "EPSG:4326":
            effective_threshold = distance_threshold / 111000
            unit = "degrees"
    
        y = gdf[dependent_var].values.astype(np.float64)
        import libpysal
        w = libpysal.weights.DistanceBand.from_dataframe(gdf, threshold=effective_threshold, binary=False)
        w.transform = 'r'
    
        for island in w.islands:
            w.weights[island] = [0] * len(w.weights[island])
            w.cardinalities[island] = 0
    
        return gdf, y, w, (effective_threshold, unit), None
  • MCP resource that lists available ESDA spatial analysis tools, including 'join_counts', discoverable via gis://operations/esda.
    @gis_mcp.resource("gis://operations/esda")
    def get_spatial_operations() -> Dict[str, List[str]]:
        """List available spatial analysis operations. This is for esda library. They are using pysal library."""
        return {
            "operations": [
                "getis_ord_g",
                "morans_i",
                "gearys_c",
                "gamma_statistic",
                "moran_local",
                "getis_ord_g_local",
                "join_counts",
                "join_counts_local",
                "adbscan"
            ]
        }
Behavior1/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 but fails to do so. It does not explain what the tool outputs, its computational behavior, error conditions, or any side effects, leaving the agent with insufficient information to use it correctly.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness3/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is extremely concise with a single phrase, but this brevity results in under-specification rather than efficient communication. It is front-loaded but lacks necessary detail, making it inadequate despite its short length.

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

Completeness2/5

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

Given the tool's complexity (4 parameters, 1 required, no annotations) and the presence of an output schema, the description is incomplete. It does not clarify the tool's purpose, usage, or parameters, leaving significant gaps even though output details might be covered elsewhere.

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

Parameters1/5

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

Schema description coverage is 0%, meaning parameters are undocumented in the schema. The description adds no semantic information about parameters like 'shapefile_path', 'dependent_var', 'target_crs', or 'distance_threshold', failing to compensate for the lack of schema documentation.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose2/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description 'Global Binary Join Counts' restates the tool name 'join_counts' with minimal elaboration, making it tautological. It lacks a specific verb and resource specification, failing to distinguish what the tool actually does beyond its name.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines1/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance is provided on when to use this tool versus alternatives like 'join_counts_local' or other spatial analysis tools in the sibling list. The description offers no context, prerequisites, or exclusions for usage.

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