Skip to main content
Glama
tharlestsa

OpenLandMap MCP Server

by tharlestsa

build_python_snippet

Generate Python code to access and process OpenLandMap raster data for operations like opening, plotting, clipping, or analyzing geospatial datasets.

Instructions

Generate a ready-to-use Python code snippet for accessing a raster asset.

Supports multiple operations: open, info, plot, clip_bbox, stats, export_csv.

Args: collection_id: Collection identifier. item_id: Item identifier. asset_key: Asset key within the item. operation: Code operation to generate: 'open' — open the raster with rasterio 'info' — print raster metadata 'plot' — plot with matplotlib 'clip_bbox' — clip to a bounding box 'stats' — compute zonal statistics 'export_csv' — export values to CSV

Returns: Python code snippet as a string.

Example: build_python_snippet("organic.carbon_usda.6a1c", "organic.carbon_usda.6a1c_20180101_20181231", "organic.carbon_usda.6a1c_m_1km_b30cm_s", "plot")

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
collection_idYes
item_idYes
asset_keyYes
operationNoopen

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The 'build_python_snippet' function, decorated with @mcp.tool(), implements the logic to generate Python code snippets for various raster operations.
    async def build_python_snippet(
        collection_id: str,
        item_id: str,
        asset_key: str,
        operation: str = "open",
    ) -> str:
        """Generate a ready-to-use Python code snippet for accessing a raster asset.
    
        Supports multiple operations: open, info, plot, clip_bbox, stats, export_csv.
    
        Args:
            collection_id: Collection identifier.
            item_id: Item identifier.
            asset_key: Asset key within the item.
            operation: Code operation to generate:
                'open' — open the raster with rasterio
                'info' — print raster metadata
                'plot' — plot with matplotlib
                'clip_bbox' — clip to a bounding box
                'stats' — compute zonal statistics
                'export_csv' — export values to CSV
    
        Returns:
            Python code snippet as a string.
    
        Example:
            build_python_snippet("organic.carbon_usda.6a1c",
                                 "organic.carbon_usda.6a1c_20180101_20181231",
                                 "organic.carbon_usda.6a1c_m_1km_b30cm_s",
                                 "plot")
        """
        data = await client.get_item_raw(collection_id, item_id)
        assets = data.get("assets", {})
    
        if asset_key not in assets:
            return f"# Error: asset '{asset_key}' not found. Available: {list(assets.keys())}"
    
        url = assets[asset_key].get("href", "")
    
        snippets = {
            "open": (
                f'import rasterio\n\n'
                f'url = "{url}"\n\n'
                f'with rasterio.open(url) as src:\n'
                f'    data = src.read(1)\n'
                f'    print(f"Shape: {{data.shape}}")\n'
                f'    print(f"CRS: {{src.crs}}")\n'
                f'    print(f"Bounds: {{src.bounds}}")\n'
                f'    print(f"Resolution: {{src.res}}")\n'
                f'    print(f"NoData: {{src.nodata}}")'
            ),
            "info": (
                f'import rasterio\n\n'
                f'url = "{url}"\n\n'
                f'with rasterio.open(url) as src:\n'
                f'    print(f"Driver: {{src.driver}}")\n'
                f'    print(f"Width x Height: {{src.width}} x {{src.height}}")\n'
                f'    print(f"Bands: {{src.count}}")\n'
                f'    print(f"CRS: {{src.crs}}")\n'
                f'    print(f"Transform: {{src.transform}}")\n'
                f'    print(f"Bounds: {{src.bounds}}")\n'
                f'    print(f"Resolution: {{src.res}}")\n'
                f'    print(f"Data type: {{src.dtypes}}")\n'
                f'    print(f"NoData: {{src.nodata}}")\n'
                f'    tags = src.tags()\n'
                f'    for k, v in tags.items():\n'
                f'        print(f"  {{k}}: {{v}}")'
            ),
            "plot": (
                f'import rasterio\n'
                f'import matplotlib.pyplot as plt\n'
                f'import numpy as np\n\n'
                f'url = "{url}"\n\n'
                f'with rasterio.open(url) as src:\n'
                f'    data = src.read(1)\n'
                f'    nodata = src.nodata\n'
                f'    if nodata is not None:\n'
                f'        data = np.where(data == nodata, np.nan, data)\n\n'
                f'    fig, ax = plt.subplots(1, 1, figsize=(12, 8))\n'
                f'    im = ax.imshow(data, cmap="viridis")\n'
                f'    plt.colorbar(im, ax=ax, label="{collection_id}")\n'
                f'    ax.set_title("{collection_id} — {item_id}")\n'
                f'    plt.tight_layout()\n'
                f'    plt.show()'
            ),
            "clip_bbox": (
                f'import rasterio\n'
                f'from rasterio.windows import from_bounds\n\n'
                f'url = "{url}"\n\n'
                f'# Define your bounding box [west, south, east, north]\n'
                f'bbox = [-54.0, -18.0, -45.0, -12.0]  # Example: part of Cerrado\n\n'
                f'with rasterio.open(url) as src:\n'
                f'    window = from_bounds(*bbox, transform=src.transform)\n'
                f'    data = src.read(1, window=window)\n'
                f'    print(f"Clipped shape: {{data.shape}}")\n'
  • Registration of 'build_python_snippet' as an MCP tool using the @mcp.tool() decorator.
    @mcp.tool()
Behavior2/5

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

No annotations are provided, so the description carries the full burden. It states the tool returns a Python code snippet as a string, which is useful. However, it doesn't disclose behavioral traits such as whether the tool requires authentication, has rate limits, or if the generated code includes dependencies (e.g., rasterio, matplotlib). For a code-generation tool with no annotations, this leaves significant gaps in understanding its operation and constraints.

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 well-structured and front-loaded: the first sentence states the purpose, followed by a bullet-point list of operations, a clear Args section, and an example. Every sentence adds value without redundancy, making it efficient and easy to scan.

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 (generating code for multiple operations) and the presence of an output schema (which covers return values), the description is largely complete. It explains parameters thoroughly and includes an example. However, it lacks context on dependencies or execution environment for the generated code, which could be important for users.

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?

Schema description coverage is 0%, so the description must compensate. It provides clear semantics for all four parameters: collection_id, item_id, and asset_key are explained as identifiers, and operation is detailed with a list of possible values and their purposes (e.g., 'open' for opening with rasterio). This adds substantial meaning beyond the bare schema, though it doesn't specify formats or constraints for the identifiers.

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: 'Generate a ready-to-use Python code snippet for accessing a raster asset.' It specifies the exact action (generate), target (Python code snippet), and resource (raster asset). This distinguishes it from sibling tools like build_r_snippet (for R) or get_asset_url (for URLs).

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 list of supported operations (e.g., open, info, plot), suggesting it's for generating code to perform these specific tasks on raster assets. However, it lacks explicit guidance on when to use this tool versus alternatives like get_asset_download_info or get_visualization_assets, and doesn't mention prerequisites or exclusions.

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/tharlestsa/openlandmap_mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server