Skip to content

Conversation

@mattpodwysocki
Copy link
Contributor

@mattpodwysocki mattpodwysocki commented Jan 6, 2026

Summary

Implements two new Mapbox Navigation API tools and their companion prompts to expand API coverage:

Map Matching Tool (map_matching_tool)

  • Purpose: Snaps noisy GPS traces to actual road networks
  • Use cases: Fleet tracking data cleanup, recorded trip analysis, fitness activity processing
  • Features:
    • Supports 2-100 coordinates with {longitude, latitude} format
    • Optional timestamps and radiuses for improved accuracy
    • Multiple routing profiles: driving, driving-traffic, walking, cycling
    • Returns confidence scores, matched geometry, and optional annotations (speed, distance, duration, congestion)

Optimization Tool (optimization_tool)

  • Purpose: Solves vehicle routing problems (VRP)
  • Use cases: Delivery route optimization, multi-vehicle scheduling, pickup/dropoff coordination
  • Features:
    • Supports up to 1000 coordinates
    • Simplified mode: Automatically creates vehicle and services from coordinates
    • Advanced mode: Full control over vehicles, services, shipments, time windows, capacities, breaks
    • Internal polling mechanism (may take 5-10 seconds for complex routes)
    • Returns optimized routes with stops, ETAs, distances, and dropped items

New Prompts

optimize-deliveries

Guides agents through route optimization workflow:

  • Example: "Optimize my delivery route for these 10 addresses"
  • Automatically geocodes addresses to coordinates
  • Uses optimization_tool to find optimal routes
  • Shows optimized sequence, ETAs, and route visualization

clean-gps-trace

Guides agents through GPS trace cleaning:

  • Example: "Clean up this noisy GPS trace"
  • Snaps GPS points to roads using map matching
  • Shows before/after visualization
  • Displays quality metrics and statistics

Implementation Details

Tools

  • ✅ Complete input/output Zod schemas with validation
  • ✅ Proper error handling and validation
  • ✅ Comprehensive unit tests (19 tests total)
  • ✅ Proper annotations (readOnlyHint, openWorldHint, idempotentHint)
  • ✅ Registered in toolRegistry.ts
  • ✅ Synchronous implementation works in all MCP clients

Prompts

  • ✅ Clear step-by-step workflows
  • ✅ Integration with tools
  • ✅ Example use cases and formatting guidance
  • ✅ Registered in promptRegistry.ts

Test Coverage

✓ MapMatchingTool (9 tests)
  ✓ sends custom header
  ✓ returns structured content for valid coordinates
  ✓ includes timestamps when provided
  ✓ includes radiuses when provided
  ✓ includes annotations when provided
  ✓ returns error when timestamps length does not match coordinates
  ✓ returns error when radiuses length does not match coordinates
  ✓ supports different routing profiles
  ✓ uses geojson geometries by default

✓ OptimizationTool (10 tests)
  ✓ sends custom header
  ✓ works in simplified mode with default vehicle
  ✓ works in advanced mode with custom vehicles and services
  ✓ works with shipments instead of services
  ✓ returns error when vehicles provided without services or shipments
  ✓ handles polling timeout
  ✓ handles API error on POST
  ✓ handles 404 on polling GET
  ✓ uses correct routing profile
  ✓ includes structured content in successful response

All 422 tests passing

Why These Tools?

These were the last two major Mapbox Navigation APIs not yet implemented in the public MCP server:

The prompts make these tools more discoverable and provide clear usage patterns for AI agents.

Note on Task-based Implementation

An async task-based version of the optimization tool was explored but reverted because no MCP clients currently support the experimental Tasks API (Inspector, Claude Desktop/CLI, Goose all fail with task augmentation errors). The current synchronous version works in all clients. A separate PR will track the task-based implementation for when client support becomes available.

Test plan

  • Unit tests pass (422/422)
  • Build succeeds
  • Tools registered correctly
  • Works in Claude Desktop, CLI, Inspector, and Goose
  • Prompts registered correctly
  • Annotations present and correct
  • Input/output schemas validate properly

🤖 Generated with Claude Code

@mattpodwysocki mattpodwysocki requested a review from a team as a code owner January 6, 2026 03:29
mattpodwysocki added a commit that referenced this pull request Jan 6, 2026
Add two new prompts to guide users through using the Map Matching
and Optimization tools added in PR #89.

New Prompts:
- clean-gps-trace: Clean and snap noisy GPS traces to roads
  * Guides through parsing GPS coordinates
  * Uses map_matching_tool with proper parameters
  * Shows before/after visualization with confidence scores
  * Example: "Clean up this GPS trace from my bike ride"

- optimize-deliveries: Optimize multi-stop routes
  * Handles address geocoding automatically
  * Configures optimization with shipments format
  * Shows optimized route with efficiency metrics
  * Example: "Optimize my delivery route for these addresses"

Changes:
- Added CleanGpsTracePrompt.ts with map matching workflow
- Added OptimizeDeliveriesPrompt.ts with route optimization workflow
- Updated promptRegistry.ts with new prompts
- Added comprehensive tests in promptRegistry.test.ts
- Updated README.md with example prompts

Testing:
- All 424 tests passing ✓
- New prompt metadata tests verify correct structure
- Prompts follow kebab-case naming convention

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
mattpodwysocki and others added 4 commits January 6, 2026 10:18
Implements two new Mapbox Navigation API tools:

- Map Matching Tool (map_matching_tool): Snaps GPS traces to roads
  - Supports 2-100 coordinates with optional timestamps and radiuses
  - Returns confidence scores, matched geometry, and annotations
  - Handles driving, cycling, walking, and driving-traffic profiles

- Optimization Tool (optimization_tool): Solves vehicle routing problems
  - Supports up to 1000 coordinates
  - Simplified mode: auto-generates vehicle and services
  - Advanced mode: custom vehicles, services, shipments, time windows
  - Async polling mechanism (POST + GET)

Both tools include:
- Complete input/output schemas with Zod validation
- Comprehensive unit tests (19 tests total)
- Proper annotations (readOnlyHint, openWorldHint, etc.)

All 422 tests passing.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
This commit converts the OptimizationTool from a synchronous blocking tool
to an async task-based tool using the experimental MCP Tasks API.

**Problem:** The Optimization API v2 is long-running (up to 10 seconds with
polling), blocking the agent from doing other work while waiting for results.

**Solution:** Implemented task-based execution using MCP SDK 1.25.1's
experimental tasks API:

- **src/tools/optimization-tool/OptimizationTask.ts** (NEW): Task-based
  implementation with three handlers:
  - createTask: Submits optimization job to Mapbox API, returns immediately
    without blocking
  - getTask: Returns current task status (pending, working, completed, failed)
  - getTaskResult: Returns final optimization results when complete
  - Background polling runs asynchronously with proper error handling

- **src/index.ts**: Added task support to server
  - Created InMemoryTaskStore and InMemoryTaskMessageQueue
  - Updated server capabilities to include tasks: { requests: { tools: { call: {} } } }
  - Registered OptimizationTask instead of synchronous OptimizationTool
  - Fixed "Type instantiation is excessively deep" error in GetPromptRequestSchema
    handler with type assertions (workaround for MCP SDK 1.25.1 issue #985)

- **src/tools/BaseTool.ts**: Fixed TypeScript compilation error
  - Added type assertions to break complex type inference chains
  - Workaround for "Type instantiation is excessively deep" errors with
    MCP SDK 1.25.1 generic types

**Benefits:**
- Non-blocking execution - returns task ID immediately
- Agent can do other work while optimization runs in background
- Progress updates via task status messages
- Proper error handling and timeout management
- All existing tests pass (422 tests)
- Zero TypeScript compilation errors

**Testing:**
- Server starts successfully with task support
- All 422 existing tests pass
- Build completes without errors

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
- Add OptimizeDeliveriesPrompt for the task-based optimization tool
  - Guides agent through route optimization workflow
  - References async task-based execution
  - Provides clear instructions for displaying results

- Add CleanGpsTracePrompt for the map matching tool
  - Guides agent through GPS trace cleaning/snapping
  - Shows before/after visualization approach
  - Includes quality metrics and statistics

- Register both new prompts in promptRegistry.ts

All tests passing (422 tests) and build successful.
No MCP clients currently support the experimental Tasks API:
- MCP Inspector: task support not available
- Claude Desktop/CLI: returns error -32601 (task augmentation required)
- Goose: falls back to other tools

Changes:
- Remove task-based OptimizationTask.ts implementation
- Re-enable synchronous OptimizationTool.ts (with polling)
- Remove task capabilities from server (taskStore, InMemoryTaskStore, etc.)
- Update OptimizeDeliveriesPrompt to remove task-based language
- Tool now blocks for 5-10 seconds during optimization (necessary trade-off)

The synchronous version:
- Works in all current MCP clients
- Still does async polling internally (POST job, GET results)
- Returns results when optimization completes
- All 422 tests passing

We can convert back to task-based when clients add support.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
@mattpodwysocki mattpodwysocki force-pushed the add-map-matching-optimization-tools branch from 9611892 to 08a6ca3 Compare January 6, 2026 15:19
The Mapbox Optimization API v2 is currently in beta and not accessible
to all users. This commit migrates to the publicly available V1 API.

Key changes:
- Changed from async job submission (POST + polling) to synchronous GET
- Updated coordinate limit from 1000 to 12 (V1 constraint)
- Simplified input schema: removed vehicles/services/shipments complexity
- Updated output schema: changed from routes/stops to waypoints/trips
- Updated prompt to reflect V1 limitations and synchronous behavior
- Rewrote all tests (11 tests) to match V1 API format

All tests passing (11/11).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
@mattpodwysocki
Copy link
Contributor Author

✅ Updated: Optimization API V1 Migration Complete

The OptimizationTool has been migrated from the beta V2 API to the publicly available V1 API.

Changes Made

API Migration:

  • Switched from async job submission (POST + polling) to synchronous GET requests
  • Updated from optimized-trips/v2 to optimized-trips/v1 endpoint

Schema Updates:

  • Input: Simplified from complex V2 schema (vehicles, services, shipments) to straightforward V1 parameters (coordinates, profile, routing options)
  • Output: Changed from V2 format (routes, stops, dropped items) to V1 format (waypoints with optimized order, trips with legs)
  • Coordinate limit: Changed from 1000 to 12 (V1 API constraint)

Code Changes:

  • OptimizationTool.ts: Complete rewrite from async polling to synchronous request (354 lines simplified)
  • OptimizationTool.input.schema.ts: Replaced complex V2 schema with V1 parameters
  • OptimizationTool.output.schema.ts: Updated to match V1 response structure
  • OptimizeDeliveriesPrompt.ts: Updated guidance to reflect V1 limitations and synchronous behavior

Testing:

  • Completely rewrote test suite with 11 comprehensive tests
  • All tests passing ✓
  • Tests cover: basic optimization, routing profiles, optional parameters, error handling, input validation

Why This Change?

The Mapbox Optimization API v2 is currently in beta and not accessible to all Mapbox users. Migrating to V1 ensures the tool works for everyone with a public Mapbox account.

Impact

  • Breaking change: Coordinate limit reduced from 1000 to 12 per request
  • Benefit: No longer requires async task polling - results return immediately
  • Benefit: Simpler API surface area, easier to use
  • Benefit: Works with all public Mapbox accounts (V2 requires beta access)

Commit: f489d33

@mattpodwysocki
Copy link
Contributor Author

Closing this PR

This PR is superseded by #94 (offline_tools branch).

What's in #94 now:

  1. Map Matching Tool - Already included ✅
  2. Optimization V1 Tool - New implementation using V1 API (simpler, synchronous) ✅
  3. Optimization V2 Tool - Code present but not registered (for when V2 goes public)

Why switch to V1?

The V2 optimization API (/optimized-trips/v2) requires beta access and currently returns 403 errors. The V1 API (/optimized-trips/v1/{profile}/{coordinates}) is:

  • Publicly available
  • Synchronous (no polling needed)
  • Supports 2-12 coordinates
  • Perfect for simple TSP problems
  • Works in all MCP clients now ✅

What about V2 features?

The V2 implementation from this PR has been preserved as OptimizationV2Tool.ts with all the advanced features (time windows, capacity, breaks, shipments). It's ready to be enabled when the V2 API becomes publicly available.

Closing this PR as all functionality is now in #94.

🤖 Generated with Claude Code

@mattpodwysocki
Copy link
Contributor Author

Superseded by #94

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant