All skills
mapbox avatar

/mapbox-mcp-runtime-patterns

@7cac917 official
by mapboxmapbox/mapbox-agent-skills80 stars
17

Integration patterns for Mapbox MCP Server in AI applications and agent frameworks. Covers runtime integration with pydantic-ai, mastra, LangChain, and custom agents. Use when building AI-powered applications that need geospatial capabilities.

Use this Skill: https://skilld.dev/gh/mapbox/mapbox-agent-skills/mapbox-mcp-runtime-patterns

This session only. Nothing lands on disk.

referencessmolagents.md

≈1.5k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Smolagents Integration

Use case: Lightweight agents with geospatial capabilities (Hugging Face)

Smolagents is Hugging Face's simple, efficient agent framework. Perfect for deploying geospatial agents with minimal overhead.

from smolagents import CodeAgent, Tool, HfApiModel
import requests
import os

class MapboxMCP:
    """Mapbox MCP connector."""

    def __init__(self, token: str = None):
        self.url = 'https://mcp.mapbox.com/mcp'
        token = token or os.getenv('MAPBOX_ACCESS_TOKEN')
        self.headers = {
            'Content-Type': 'application/json',
            'Authorization': f'Bearer {token}'
        }

    def call_tool(self, tool_name: str, params: dict) -> str:
        request = {
            'jsonrpc': '2.0',
            'id': 1,
            'method': 'tools/call',
            'params': {'name': tool_name, 'arguments': params}
        }
        response = requests.post(self.url, headers=self.headers, json=request)
        result = response.json()['result']
        return result['content'][0]['text']

# Create Mapbox tools for Smolagents
class DirectionsTool(Tool):
    name = "directions_tool"
    description = """
    Get driving directions between two locations.

    Args:
        origin: Origin coordinates as [longitude, latitude]
        destination: Destination coordinates as [longitude, latitude]

    Returns:
        Directions with distance and travel time
    """

    def __init__(self):
        super().__init__()
        self.mcp = MapboxMCP()

    def forward(self, origin: list, destination: list) -> str:
        return self.mcp.call_tool('directions_tool', {
            'coordinates': [
                {'longitude': origin[0], 'latitude': origin[1]},
                {'longitude': destination[0], 'latitude': destination[1]}
            ],
            'routing_profile': 'mapbox/driving-traffic'
        })

class CalculateDistanceTool(Tool):
    name = "distance_tool"
    description = """
    Calculate distance between two points (offline, instant).

    Args:
        from_coords: Start coordinates [longitude, latitude]
        to_coords: End coordinates [longitude, latitude]
        units: 'miles' or 'kilometers'

    Returns:
        Distance as a number
    """

    def __init__(self):
        super().__init__()
        self.mcp = MapboxMCP()

    def forward(self, from_coords: list, to_coords: list, units: str = 'miles') -> str:
        return self.mcp.call_tool('distance_tool', {
            'from': {'longitude': from_coords[0], 'latitude': from_coords[1]},
            'to': {'longitude': to_coords[0], 'latitude': to_coords[1]},
            'units': units
        })

class SearchPOITool(Tool):
    name = "search_poi"
    description = """
    Search for points of interest by category.

    Args:
        category: POI category (restaurant, hotel, gas_station, etc.)
        location: Search center [longitude, latitude]

    Returns:
        List of nearby POIs with names and coordinates
    """

    def __init__(self):
        super().__init__()
        self.mcp = MapboxMCP()

    def forward(self, category: str, location: list) -> str:
        return self.mcp.call_tool('category_search_tool', {
            'category': category,
            'proximity': {'longitude': location[0], 'latitude': location[1]}
        })

class IsochroneTool(Tool):
    name = "isochrone_tool"
    description = """
    Calculate reachable area within time limit (isochrone).

    Args:
        location: Center point [longitude, latitude]
        minutes: Time limit in minutes
        profile: 'mapbox/driving', 'mapbox/walking', or 'mapbox/cycling'

    Returns:
        GeoJSON polygon of reachable area
    """

    def __init__(self):
        super().__init__()
        self.mcp = MapboxMCP()

    def forward(self, location: list, minutes: int, profile: str = 'mapbox/driving') -> str:
        return self.mcp.call_tool('isochrone_tool', {
            'coordinates': {'longitude': location[0], 'latitude': location[1]},
            'contours_minutes': [minutes],
            'profile': profile
        })

# Create agent with Mapbox tools
model = HfApiModel()

agent = CodeAgent(
    tools=[
        DirectionsTool(),
        CalculateDistanceTool(),
        SearchPOITool(),
        IsochroneTool()
    ],
    model=model
)

# Use agent
result = agent.run(
    "Find restaurants within 10 minutes walking from Times Square NYC "
    "(coordinates: -73.9857, 40.7484). Calculate distances to each."
)

print(result)

Real-world example - Property search agent:

class PropertySearchAgent:
    def __init__(self):
        self.mcp = MapboxMCP()

        # Create specialized tools
        tools = [
            IsochroneTool(),
            SearchPOITool(),
            CalculateDistanceTool()
        ]

        self.agent = CodeAgent(
            tools=tools,
            model=HfApiModel()
        )

    def find_properties_near_work(
        self,
        work_location: list,
        max_commute_minutes: int,
        property_locations: list[dict]
    ):
        """Find properties within commute time of work."""

        prompt = f"""
        I need to find properties within {max_commute_minutes} minutes
        driving of my work at {work_location}.

        Property locations to check:
        {property_locations}

        For each property:
        1. Calculate if it's within the commute time
        2. Find nearby amenities (grocery stores, restaurants)
        3. Calculate distances to key locations

        Return a ranked list of properties with commute time and nearby amenities.
        """

        return self.agent.run(prompt)

# Usage
property_agent = PropertySearchAgent()

properties = [
    {'id': 1, 'address': '123 Main St', 'coords': [-122.4194, 37.7749]},
    {'id': 2, 'address': '456 Oak Ave', 'coords': [-122.4094, 37.7849]},
]

results = property_agent.find_properties_near_work(
    work_location=[-122.4, 37.79],  # Downtown SF
    max_commute_minutes=30,
    property_locations=properties
)

Benefits:

  • Lightweight and efficient
  • Simple tool definition
  • Code-based agent execution
  • Great for production deployment

Source: SKILL.md on GitHub

1 warning17d5 checks · Risk SAFE
  • Gen Agent Trust Hub17d

    The skill provides legitimate integration patterns and code examples for using Mapbox geospatial tools with various AI agent frameworks. It uses standard developer practices for package management, environment configuration, and API interaction with official vendor services.

  • Socket17d

    No alerts

  • Snyk17d

    Risk: LOW · No issues

  • Runlayer6mo

    2/12 files flagged

  • ZeroLeaks5mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at 7cac917. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 9 hours ago.

Activeupdated 6 months ago
  • MCP
  • TypeScript
  • mapbox
  • geospatial
  • routing
  • geocoding
  • pydantic-ai
  • langchain
  • mastra
  • agents

README badge

README badge for mapbox/mapbox-agent-skills/mapbox-mcp-runtime-patterns

Demonstrates runtime integration patterns for the Mapbox MCP Server across pydantic-ai, mastra, LangChain, and custom agents, covering offline tools (Turf.js), API-backed geospatial features (routing, geocoding, isochrones), and production considerations. Use this when building AI applications that need to query maps, calculate distances, search POIs, or optimize routes without manual API integration.

Generated from the current SKILL.md.

What's the difference between offline tools like distance_tool and API tools like directions_tool?
Offline tools (distance, bearing, point-in-polygon) use Turf.js, return instant results, and have no API cost. API tools (directions, geocoding, isochrones) call Mapbox APIs, return real-time data like traffic-aware routing, and count against your token usage.
Can I use the hosted Mapbox MCP server or do I need to self-host?
The hosted server at https://mcp.mapbox.com/mcp is recommended for production — no server management, always up-to-date, and lower latency. Self-hosting via npm is available for custom deployments or development.
Which frameworks does this skill cover?
Integration patterns for Pydantic AI, Mastra, LangChain, CrewAI, Smolagents, and custom agent architectures. Real-estate, food-delivery, and travel-planning use cases are included.
When should I use category_search_tool vs search_and_geocode_tool?
Use category_search_tool to browse by type (e.g. 'find coffee shops nearby'). Use search_and_geocode_tool for specific places or street addresses (e.g. '123 Main Street').
Does this skill include production guidance like caching, rate limiting, and error handling?
Yes. The skill references a production-patterns file covering caching, batch operations, tool descriptions, error handling, security, rate limiting, and testing.

Generated from the current SKILL.md. These answers refresh after source changes.