Skip to main content
Glama
USGS Spatial Data Catalog MCP Server

USGS Spatial Data Catalog MCP Server

by GSA-TTS

GSA MCP Hackathon — Server Template

USGS Spatial Data Catalog tools

This repository now exposes ten read-only tools, prefixed usgs_spatcat_: search_layers, get_layer, list_spatial_layers, get_sublayers, get_native_resolution, intersect_layers, distance_to_layers, query_attributes, list_analysis_modules, and analyze_point.

Set SPATCAT_CATALOG_URL and SPATCAT_ANALYSIS_URL in your local .env to approved HTTPS API bases including /spatcat-api and /spatcat-analysis. Optional SPATCAT_CATALOG_TOKEN and SPATCAT_ANALYSIS_TOKEN are independently scoped bearer credentials. No live API hostname is assumed.

On Linux, keep the environment separate from a macOS environment:

UV_PROJECT_ENVIRONMENT=.venv-linux uv sync --frozen --group dev
.venv-linux/bin/python -m spatcat_mcp.app
.venv-linux/bin/pytest tests/ -q
.venv-linux/bin/ruff check .

app.py and its transport precedence are unchanged: a platform-injected port selects HTTP, explicit MCP_TRANSPORT=streamable-http selects HTTP, otherwise the server uses stdio. The template server display name is also unchanged. The original example tool is no longer registered; example resources/prompts remain template placeholders, not USGS data.

Data preparation skill over MCP

The Python package is spatcat_mcp; the distribution and command remain example-server. FastMCP is pinned to 4.2.5 for its documented skills API. The server serves one AI-authored documentation skill from skills/spatcat-data-preparation/SKILL.md: format selection, GeoParquet/PMTiles/COG preparation and validation, permission-gated S3 delivery planning, and registration preparation. All commands in it are suggestions, not completed actions. No conversion, upload, or write tools were added.

Read it using MCP resources at skill://spatcat-data-preparation/SKILL.md, or use FastMCP's Skills extension for discovery and verified whole-skill retrieval:

from fastmcp import Client
from fastmcp.skills import SkillsClientExtension

# An in-process example; use your approved server connection in a real client.
from spatcat_mcp.app import mcp

async def read_preparation_skill():
    async with Client(mcp, extensions=[SkillsClientExtension()]) as client:
        entries = await client.list_skills()
        skill = await client.read_skill("skill://spatcat-data-preparation/SKILL.md")
        return entries, skill

Clients without the extension can list/read resources, or use FastMCP list_skill_resources() and read_skill() through the manifest fallback. Tool-only clients will not discover this skill: no resource-to-tools transform is enabled, so the ten domain tools remain unchanged. Only this named skill and its SKILL.md are allowed; .agents/skills/ is never scanned. The file is included in wheels and source distributions. Restart the server after editing it. AI-generated code and documentation require human review before production use.

Verification: .venv-linux/bin/pytest tests/ -q, .venv-linux/bin/ruff check src tests, .venv-linux/bin/ruff format --check src tests, and uv build --python .venv-linux/bin/python (build dependency downloads require approval).

Query workflow and limitations

Search for layers, inspect metadata/capabilities and Esri sublayers, then run spatial or attribute queries. Discover module IDs before point analysis. GeoJSON is validated as two-dimensional WGS84 (longitude, latitude), with a 10,000-position budget; reprojection and topology repair are not performed. Confirm this CRS assumption with the upstream operator before live use.

Results have source, retrieved_at, data, and warnings. data preserves the upstream object/array, including per-layer errors and pagination metadata. No undocumented response schemas, total counts, or dataset freshness dates are invented. Catalog limit defaults to 20 and is capped at 100. Only the catalog endpoint has documented pagination; other tools do not fabricate pagination. Responses exceeding 5 MB fail explicitly rather than silently truncate.

Raster distance is not implemented by the API. S3 polygon distance uses the centroid and ignores the buffer; Esri/WFS distance uses closest approach. WMS and OGC support must be checked per layer. Capability metadata is returned without guessing undocumented boolean field names or inferring support solely from service type. Upstream unsupported-operation/partial-failure responses remain visible; no-result queries are not determinations of site safety.

Attribute filters support field-to-literal comparisons, IN, LIKE, IS [NOT] NULL, AND/OR, and bounded parentheses. Functions, comments, subqueries, and SQL statements are rejected. out_fields accepts * or a comma-separated identifier list. This is validation of an upstream Esri filter, not permission to execute SQL against a database.

Security and deployment boundary

Tool callers cannot choose HTTP origins. Origins are operator configuration; HTTPS/443, disabled redirects/proxy inheritance, response limits, request deadlines, and connection-time public-IP validation apply to every USGS API request. DNS answers are validated and the TCP connection uses the validated IP while TLS verifies the original hostname. The network adapter touches httpx/httpcore internals and is tested against uv.lock; re-test on upgrades. No request/response bodies, coordinates, or credentials are logged by these tools. The API may perform costly backend analysis despite read-only intent.

Before remote deployment, configure MCP authentication, per-tool authorization, rate limiting at the gateway, exact-origin egress allowlisting, and log access controls. Existing template HTTP transport is not an authorization boundary. These deployment changes are intentionally not part of this tool-only change. Do not expose the template HTTP server publicly without those controls. Live validation requires approved API URLs, credentials if needed, and explicit network permission. AI-generated changes require human review before production.


A ready-to-run starter for building a Model Context Protocol (MCP) server in Python, plus deployment kits for IBM Cloud (watsonx Orchestrate) and Databricks.

Built with FastMCP and uv. If you have never built an MCP server before, start with QUICKSTART.md.


Related MCP server: capalith

What is an MCP server?

An MCP server exposes tools (functions the model can call), prompts (reusable conversation starters), and resources (data the model can read) to an AI client such as Claude Desktop, Claude Code, or an agent platform like watsonx Orchestrate. You write the tools; the client's model decides when to call them.

This template gives you a working server with one example of each, so you can replace the examples with your own service and deploy.


Repo structure

mcp-hackathon-template/
├── README.md                  # This file
├── QUICKSTART.md              # 5-minute clone → run → connect walkthrough
├── main.py                    # Local entry point (uv run python main.py)
├── pyproject.toml             # Package + dependencies (uv)
├── requirements.txt           # Mirror of runtime deps (for buildpack hosts)
├── Dockerfile                 # Container image (streamable-HTTP, port 8080)
├── manifest.yaml              # cloud.gov (Cloud Foundry) deploy
├── server.json                # MCP registry metadata
├── .env.example               # Copy to .env for local dev
├── .github/workflows/ci.yml   # Lint + test on push/PR
├── docs/                      # Vendor-contributed reference materials
├── src/
│   └── example_server/        # ← rename to your service
│       ├── app.py             # Thin entry point: builds FastMCP, picks transport
│       ├── config.py          # Settings from env vars / .env
│       ├── models.py          # Pydantic models & enums for tool params
│       ├── utils.py           # Shared helpers (HTTP client, pagination)
│       ├── routes.py          # HTTP-only routes (/health, /version)
│       ├── tools/             # ONE FILE PER TOOL
│       │   ├── __init__.py    #   register_tools(mcp) aggregator
│       │   └── example_tool.py
│       ├── prompts/
│       │   ├── __init__.py    #   register_prompts(mcp) aggregator
│       │   └── example.py
│       └── resources/
│           ├── __init__.py    #   register_resources(mcp) aggregator
│           └── example.py
├── tests/                     # Import + registration smoke tests
├── eval/                      # Stub → build a Phoenix eval harness (see mcp-eval skill)
└── deploy/
    ├── README.md              # Which deployment kit to use
    ├── ibm/                   # watsonx Orchestrate: 3 kits (see below)
    └── databricks/            # Databricks Apps kit

Getting started

Prerequisites

  • uv — pip install uv or brew install uv

Install and run

cp .env.example .env
uv sync
uv run python main.py

The server starts in stdio mode — it talks JSON-RPC over stdin/stdout, which is how local clients (Claude Desktop, Claude Code) launch it. See QUICKSTART.md to connect a client.

Verify

uv sync --group dev
uv run pytest tests/ -v      # tests
uv run ruff check .          # lint

The one-tool-per-file pattern

Each tool lives in its own file under src/example_server/tools/ and exposes a register(mcp) function. tools/__init__.py calls each one from a single register_tools(mcp). This keeps the tool list scannable and lets you add or remove an integration by touching two files.

Step 1 — create src/example_server/tools/my_tool.py:

from typing import Annotated
from urllib.parse import quote
from fastmcp import FastMCP

from example_server.utils import fetch_json


def register(mcp: FastMCP) -> None:
    @mcp.tool(
        name="example_get_thing",
        annotations={
            "title": "Get a thing",
            "readOnlyHint": True,
            "destructiveHint": False,
            "idempotentHint": True,
            "openWorldHint": True,
        },
    )
    async def get_thing(thing_id: Annotated[str, "The ID to fetch."]) -> dict:
        """One-line summary. Document the data source, its update cadence,
        and the return shape here — the model reads this docstring."""
        safe_id = quote(thing_id, safe="")
        return await fetch_json(f"things/{safe_id}")

Step 2 — wire it up in tools/__init__.py:

from example_server.tools import example_tool, my_tool

def register_tools(mcp) -> None:
    example_tool.register(mcp)
    my_tool.register(mcp)  # ← add this line

Step 3 — add any API key as a typed field in config.py and document the env var in .env.example.

Prompts (prompts/) and resources (resources/) follow the exact same register(mcp) + aggregator pattern.


Rename the package

Before publishing your server, rename example_server to your service (e.g. census_mcp):

  1. Rename the folder src/example_server/ → src/<your_name>/.

  2. Update pyproject.toml: the [project].name, [project.scripts], and [tool.hatch.build.targets.wheel].packages.

  3. Find-and-replace example_server across src/, tests/, main.py, Dockerfile, and manifest.yaml.


Tool design tips (federal data)

  • Return structured data, not prose. Return dicts/lists with consistent keys and let the model narrate.

  • Document freshness. Federal datasets lag; state the update frequency and "as-of" date in the docstring.

  • Expose pagination. Use PaginationParams / paginate() from utils.py, and return has_more / next_offset.

  • Use explicit timeouts. utils.fetch_json defaults to 30s.

  • Actionable errors. Return an error dict with a hint, not a raw stack trace.

  • Constrain outbound requests. Keep API origins in operator-controlled code or configuration, pass only validated relative paths to fetch_json, and encode path segments. Never pass a tool-supplied URL directly to an HTTP client.

  • Treat redirects and DNS as security boundaries. Redirects are disabled by default. A server that must fetch caller-supplied URLs needs connection-time IP validation on every hop plus network egress controls; a one-time DNS check is not sufficient.

  • Keep sensitive data out of errors and logs. Do not expose or log upstream bodies, headers, full URLs, query strings, credentials, stack traces, SSNs, dates of birth, or addresses.


Deploying

Local development uses stdio. To share your server with an agent platform, deploy it and register it. See deploy/README.md for a chooser, then:

  • IBM watsonx Orchestrate — deploy/ibm/ (three kits: local stdio toolkit, Code Engine build-from-Git, and prebuilt image).

  • Databricks Apps — deploy/databricks/.

Both read the same server code; app.py automatically serves HTTP when the platform injects a port.


Partner reference materials

The docs/ directory contains educational reference materials that IBM and Databricks may contribute for hackathon participants. Vendor-contributed materials do not represent the views, positions, or policies of GSA or the United States Government.

GSA does not endorse any commercial product, service, or enterprise referenced in these materials. Reference to a commercial product, service, or enterprise does not constitute or imply endorsement, recommendation, or favoring by GSA or the United States Government. These materials are provided for educational purposes only. See docs/README.md for the complete notice and contribution guidance.


Evaluations

Measuring how well an LLM can use your tools is the real test of server quality. This template intentionally does not ship an eval harness — see eval/README.md for how to build one with the mcp-eval skill.


License

MIT. See SECURITY.md for the vulnerability disclosure policy and hackathon security notes.

Available Tools

10 tools
usgs_spatcat_analyze_pointUsgs Spatcat Analyze PointA
Read-onlyIdempotent

Analyze a WGS84 longitude/latitude using selected modules or all modules.

Discover module IDs with list_analysis_modules. Omit module_ids to run all modules; specify a subset to reduce latency. Returns point metadata and module-specific results without inventing missing values.

Inputs: latitude (required), longitude (required), module_ids. Returns: Preserves upstream fields and per-layer failures without invented metadata.

usgs_spatcat_distance_to_layersUsgs Spatcat Distance To LayersA
Read-onlyIdempotent

Find nearest vector features to a WGS84 Point, Polygon, or MultiPolygon.

Esri/WFS distance is closest approach in meters, zero for overlap, searching outward up to buffer_meters. S3 vectors use polygon centroids and ignore buffer_meters. Raster distance (COG/WCS/WMS raster) is NOT implemented. Discover supported layers first. No match does not prove absence beyond the search radius; preserve per-layer errors.

Inputs: geometry (required), layer_ids (required), buffer_meters. Returns: Preserves upstream fields and per-layer failures without invented metadata.

usgs_spatcat_get_layerUsgs Spatcat Get LayerA
Read-onlyIdempotent

Get full layer metadata, service endpoints, and capabilities by ID.

Discover IDs with search_layers. Endpoints are returned as untrusted metadata, not fetched. Check capabilities before choosing an operation; service type alone does not establish query support.

Inputs: layer_id (required). Returns: Preserves upstream fields and per-layer failures without invented metadata.

usgs_spatcat_get_native_resolutionUsgs Spatcat Get Native ResolutionA
Read-onlyIdempotent

Probe a WCS raster layer's native resolution in meters.

Use before selecting raster intersection resolution. This endpoint is not a general resolution probe for all service types.

Inputs: layer_id (required). Returns: Preserves upstream fields and per-layer failures without invented metadata.

usgs_spatcat_get_sublayersUsgs Spatcat Get SublayersA
Read-onlyIdempotent

List Esri MapServer sublayer IDs, names, scales, and geometry types.

Set include_fields for field definitions and available pagination info. Inspect fields before attribute queries and sublayers before intersects.

Inputs: layer_id (required), include_fields. Returns: Preserves upstream fields and per-layer failures without invented metadata.

usgs_spatcat_intersect_layersUsgs Spatcat Intersect LayersA
Read-onlyIdempotent

Intersect layers with a WGS84 Point, Polygon, or MultiPolygon.

Vector results contain features; raster results contain summaries. Optional sublayers are Esri MapServer IDs; resolution is raster-only ('auto', 'native', or meters). WMS polygon queries require a sibling WFS/WCS endpoint. Preserve per-layer failures; absence is not a safe-site determination. Inspect layer capabilities first.

Inputs: geometry (required), layer_ids (required), sublayers, resolution. Returns: Preserves upstream fields and per-layer failures without invented metadata.

usgs_spatcat_list_analysis_modulesUsgs Spatcat List Analysis ModulesA
Read-onlyIdempotent

List available analysis module IDs and API-supplied descriptions.

Use returned module IDs with analyze_point. Availability is upstream controlled; examples such as soils/watershed are not an exhaustive enum.

Inputs: no named parameters. Returns: Preserves upstream fields and per-layer failures without invented metadata.

usgs_spatcat_list_spatial_layersUsgs Spatcat List Spatial LayersA
Read-onlyIdempotent

List layers supporting spatial queries with their API capabilities.

No undocumented filtering or pagination parameters are forwarded. Raster distance is not implemented, even if metadata suggests support. WMS support depends on sibling endpoints and geometry type.

Inputs: no named parameters. Returns: Preserves upstream fields and per-layer failures without invented metadata.

usgs_spatcat_query_attributesUsgs Spatcat Query AttributesA
Read-onlyIdempotent

Query Esri MapServer/FeatureServer layers by a read-only WHERE filter.

Example: ADMIN_ST = 'NM'. Supports comparisons, IN, LIKE, IS NULL, AND/OR, and parentheses, not arbitrary SQL/functions. out_fields is '*' or comma-separated field names. max_results applies per layer, not globally. Discover field names before filtering; results may be capped.

Inputs: where (required), layer_ids (required), out_fields, max_results. Returns: Preserves upstream fields and per-layer failures without invented metadata.

usgs_spatcat_search_layersUsgs Spatcat Search LayersA
Read-onlyIdempotent

Search layer names, descriptions, and tags, or browse with no query.

Use returned IDs with get_layer. Filters use API codes (e.g. WFS, FLOOD_HAZARD). Returns the upstream page, retaining pagination metadata when supplied; dataset freshness and total counts may be unknown.

Inputs: limit, query, offset, category, +1 more. Returns: Preserves upstream fields and per-layer failures without invented metadata.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.1/5.0

    Scored across 10 tools

    Disambiguation4/5

    Most tools map cleanly to a single action on a distinct resource, and descriptions actively clarify boundaries (e.g. search_layers for name/tag discovery vs. get_layer for metadata by ID vs. list_spatial_layers for spatial-capable layers). The layer-discovery trio (search_layers / list_spatial_layers / get_sublayers) still overlaps enough that an agent may hesitate, and get_native_resolution's narrow raster-only scope is easy to over-apply.

    Naming Consistency5/5

    Every tool uses the same usgs_spatcat_ prefix followed by a verb_noun snake_case name (search_layers, get_layer, intersect_layers, analyze_point). No camelCase mixing or vague single-word verbs.

    Tool Count5/5

    Ten tools is well within the ideal range and each corresponds to a distinct capability: discovery, metadata, attribute query, spatial intersection/distance, module listing, and point analysis. No tool feels redundant padding.

    Completeness4/5

    The surface covers the full workflow for a spatial catalog: discover (search/list) → inspect (get_layer/get_sublayers) → query (attributes/intersect/distance) → analyze. Gaps are minor: no pagination-continuation or result-export/retrieval-by-ID tool, but agents can work around these via the existing query endpoints.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      B
      maintenance
      Read-only access to a self-hosted GeoLens geospatial catalog: dataset search, schemas, GeoJSON features, saved maps, and sandboxed read-only SQL over PostGIS.
      14
      306
      Apache 2.0
    • A
      license
      B
      quality
      C
      maintenance
      Enables read-only access to a local-first catalog of portable agent skills, exposing tools to discover ranked matches, inspect stored artifacts, traverse declared relationships, and view configuration.
      5
      MIT
    • A
      license
      A
      quality
      B
      maintenance
      Enables read-only search and spatial analysis across all six Overture Maps themes, with tools for catalog/schema inspection, feature retrieval, spatial joins, summaries, nearest queries, ID resolution, and release comparisons.
      9
      1
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables AI clients to explore and query a governed lakehouse Gold layer through read-only tools for listing tables, describing schemas, searching catalog documentation, and running validated SELECT queries with SQL guard protections.
      MIT