Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
## Unreleased

### Bug Fixes

- **`matrix_tool` and `map_matching_tool`: fewer failed calls (#340).** The Claude directory showed 6.8% of `matrix_tool` calls and 15.1% of `map_matching_tool` calls failing. The hosted server's logs for the last 30 days had 1,181 errors in 21,716 `matrix_tool` calls and 16 in 320 `map_matching_tool` calls. Each cause below was reproduced against the live APIs.
- **A single pair failed `matrix_tool` (944 of the 1,181 errors):** asking for one source and one destination is a single matrix element, which the API refuses with a 422. The tool now asks for a 1×2 matrix (the source to itself and to the destination), the API's minimum, and returns only the requested pair.
- **Rate limits (215 errors):** the Matrix API allows 60 requests per minute (30 for `driving-traffic`), and the pipeline's retries only cover a few seconds. The description and the 429 error now tell the model to put all the points in one call instead of one call per pair.
- **`matrix_tool` refused valid requests (9 errors):** with both `sources` and `destinations` set, it required every coordinate to be used. The API has no such rule (4 coordinates with `sources=0&destinations=1;2` returns a 1×2 matrix), so the check is gone.
- **Unroutable points broke `matrix_tool`:** when a coordinate can't be snapped to the road network (in the water, or with latitude and longitude swapped), the Matrix API returns 200 with `null` in `sources` and `destinations`. The output schema didn't allow `null`, and the tool returned the response anyway, so the MCP SDK rejected it with an output validation error. `null` waypoints are now allowed, and the result says which coordinates couldn't be snapped. A response that still fails the schema now comes back as a tool error, as `map_matching_tool` does since #230.
- **`overview=false` broke `map_matching_tool` (10 of the 16 errors):** the API leaves out each matching's `geometry` then, and the output schema required it. It's optional now.
- **`map_matching_tool` was used for routing:** models call it with a few points kilometers apart, which gets `NoMatch` or `All coordinates are too far away from each other`. The description now says it's for dense GPS traces and to use `directions_tool` between places, and those errors say the same.
- **`map_matching_tool` inputs:** the radius description said the default is unlimited. It's 5 meters, and the API refuses values outside 0 to 50, so the schema now takes more than 0 and up to 50. Timestamps that aren't in ascending order, which the API answers with `NoMatch`, are now rejected.

## 0.18.1-dev.1 - 2026-11-16

## 0.18.0 - 2026-11-11
Expand Down
10 changes: 5 additions & 5 deletions src/tools/map-matching-tool/MapMatchingTool.input.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,17 @@ export const MapMatchingInputSchema = z.object({
.optional()
.describe(
'Array of Unix timestamps (in seconds) corresponding to each coordinate. ' +
'If provided, must have the same length as coordinates array. ' +
'If provided, must have the same length as coordinates array and be in ascending order. ' +
'Used to improve matching accuracy based on speed.'
),
radiuses: z
.array(z.number().min(0))
.array(z.number().positive().max(50))
.optional()
.describe(
'Array of maximum distances (in meters) each coordinate can snap to the road network. ' +
'Array of maximum distances (in meters, greater than 0 and up to 50) each coordinate can snap to the road network. ' +
'If provided, must have the same length as coordinates array. ' +
'Default is unlimited. Use smaller values (5-25m) for high-quality GPS, ' +
'larger values (50-100m) for noisy GPS traces.'
'Default is 5 meters. Use smaller values (1-10m) for clean GPS traces, ' +
'larger values (20-50m) for noisy GPS traces.'
),
annotations: z
.array(z.enum(['speed', 'distance', 'duration', 'congestion']))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ const MatchingSchema = z.object({
confidence: z.number().min(0).max(1),
distance: z.number(),
duration: z.number(),
geometry: z.union([GeoJSONLineStringSchema, z.string()]),
// Omitted when the request sets overview=false.
geometry: z.union([GeoJSONLineStringSchema, z.string()]).optional(),
legs: z
.array(
z.object({
Expand Down
42 changes: 36 additions & 6 deletions src/tools/map-matching-tool/MapMatchingTool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,22 @@ import { buildSelfFetchRef } from '../../utils/selfFetchRef.js';

// Docs: https://docs.mapbox.com/api/navigation/map-matching/

const SPARSE_POINTS_HINT =
' Map matching needs a dense GPS trace with points seconds or tens of meters apart.' +
' To get a route between a few places, use directions_tool instead.';

export class MapMatchingTool extends MapboxApiBasedTool<
typeof MapMatchingInputSchema,
typeof MapMatchingOutputSchema
> {
name = 'map_matching_tool';
description =
'Snap GPS traces to roads using Mapbox Map Matching API. Takes noisy/inaccurate ' +
'coordinate sequences (2-100 points) and returns clean routes aligned with actual ' +
'roads, bike paths, or walkways. Useful for analyzing recorded trips, cleaning ' +
'fleet tracking data, or processing fitness activity traces. Returns confidence ' +
'Snap a recorded GPS trace to roads using Mapbox Map Matching API. Takes a dense, ' +
'noisy coordinate sequence (2-100 points, recorded seconds or tens of meters apart) ' +
'and returns a clean route aligned with actual roads, bike paths, or walkways. ' +
'Useful for analyzing recorded trips, cleaning fleet tracking data, or processing ' +
'fitness activity traces. Not for routing between a few places or addresses: points ' +
'kilometers apart fail to match, so use directions_tool for that. Returns confidence ' +
'scores, matched geometry, and optional traffic/speed annotations.';
annotations = {
title: 'Map Matching Tool',
Expand Down Expand Up @@ -62,6 +68,25 @@ export class MapMatchingTool extends MapboxApiBasedTool<
};
}

// The API needs timestamps in ascending order, and returns NoMatch when
// they aren't.
if (
input.timestamps &&
input.timestamps.some(
(t, idx) => idx > 0 && t <= input.timestamps![idx - 1]
)
) {
return {
content: [
{
type: 'text',
text: 'The timestamps must be in strictly ascending order, one per coordinate in the order the points were recorded.'
}
],
isError: true
};
}

// Validate radiuses array length matches coordinates
if (input.radiuses && input.radiuses.length !== input.coordinates.length) {
return {
Expand Down Expand Up @@ -89,7 +114,9 @@ export class MapMatchingTool extends MapboxApiBasedTool<
content: [
{
type: 'text',
text: `Map Matching API error: ${errorMessage}`
text:
`Map Matching API error: ${errorMessage}` +
(/too far away/i.test(errorMessage) ? SPARSE_POINTS_HINT : '')
}
],
isError: true
Expand All @@ -107,7 +134,10 @@ export class MapMatchingTool extends MapboxApiBasedTool<
content: [
{
type: 'text',
text: `Map Matching API could not match the trace (code: ${data.code}). Try adjusting the coordinates or radiuses.`
text:
`Map Matching API could not match the trace (code: ${data.code}). ` +
'Try larger radiuses (up to 50 meters) for a noisy trace.' +
SPARSE_POINTS_HINT
}
],
isError: true
Expand Down
6 changes: 4 additions & 2 deletions src/tools/matrix-tool/MatrixTool.output.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@ export const MatrixResponseSchema = z.object({
code: z.string(),
durations: z.array(z.array(z.number().nullable())).optional(),
distances: z.array(z.array(z.number().nullable())).optional(),
sources: z.array(MatrixWaypointSchema),
destinations: z.array(MatrixWaypointSchema),
// A waypoint is null when its coordinate can't be snapped to the road
// network (for example, a point in the water).
sources: z.array(MatrixWaypointSchema.nullable()),
destinations: z.array(MatrixWaypointSchema.nullable()),
message: z.string().optional() // Present in error responses
});

Expand Down
131 changes: 91 additions & 40 deletions src/tools/matrix-tool/MatrixTool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ export class MatrixTool extends MapboxApiBasedTool<
> {
name = 'matrix_tool';
description =
'Calculates travel times and distances between multiple points using Mapbox Matrix API.';
'Calculates travel times and distances between multiple points using Mapbox Matrix API. ' +
'Put all the points in one call (up to 25, 10 for driving-traffic) rather than one call ' +
'per pair: the API allows 60 requests per minute (30 for driving-traffic).';
annotations = {
title: 'Matrix Tool',
readOnlyHint: true,
Expand Down Expand Up @@ -211,34 +213,31 @@ export class MatrixTool extends MapboxApiBasedTool<
};
}

// Validate that when specifying both sources and destinations, all coordinates are used
if (
input.sources &&
input.sources !== 'all' &&
input.destinations &&
input.destinations !== 'all'
) {
// Get all unique coordinate indices that are used
const sourcesIndices = input.sources
.split(';')
.map((idx) => parseInt(idx, 10));
const destinationsIndices = input.destinations
.split(';')
.map((idx) => parseInt(idx, 10));
const usedIndices = new Set([...sourcesIndices, ...destinationsIndices]);

// Check if all coordinate indices are used
if (usedIndices.size < input.coordinates.length) {
return {
content: [
{
type: 'text',
text: 'When specifying both sources and destinations, all coordinates must be used as either a source or destination.'
}
],
isError: true
};
}
// The API needs at least two matrix elements (sources x destinations).
const sourceCount =
input.sources && input.sources !== 'all'
? input.sources.split(';').length
: input.coordinates.length;
const destinationCount =
input.destinations && input.destinations !== 'all'
? input.destinations.split(';').length
: input.coordinates.length;
// A single source-destination pair is one matrix element, which the API
// refuses. Ask for a 1x2 matrix (the source to itself and to the
// destination) and return only the requested pair.
const singlePair =
sourceCount * destinationCount === 1 &&
input.sources !== input.destinations;
if (sourceCount * destinationCount < 2 && !singlePair) {
return {
content: [
{
type: 'text',
text: 'The sources and destinations must give at least two matrix elements (sources x destinations). Add another source or destination index.'
}
],
isError: true
};
}

// Format coordinates for API request
Expand Down Expand Up @@ -266,7 +265,12 @@ export class MatrixTool extends MapboxApiBasedTool<
}

// Add destinations parameter if specified
if (input.destinations) {
if (singlePair) {
queryParams.append(
'destinations',
`${input.sources};${input.destinations}`
);
} else if (input.destinations) {
queryParams.append('destinations', input.destinations);
}

Expand All @@ -287,7 +291,11 @@ export class MatrixTool extends MapboxApiBasedTool<
content: [
{
type: 'text',
text: `Matrix API error: ${errorMessage}`
text:
`Matrix API error: ${errorMessage}` +
(response.status === 429
? ' The Matrix API allows 60 requests per minute (30 for driving-traffic). Put all the points in one call (up to 25) instead of one call per pair, or wait a minute and retry.'
: '')
}
],
isError: true
Expand All @@ -297,20 +305,63 @@ export class MatrixTool extends MapboxApiBasedTool<
// Return the matrix data
const data = await response.json();

// Validate the response data against our schema
let validatedData: MatrixResponse;
try {
validatedData = MatrixResponseSchema.parse(data);
} catch (error) {
// If validation fails, fall back to the original data
this.log('warning', `MatrixTool: Response validation failed: ${error}`);
validatedData = data as MatrixResponse;
// Validate the response data against our schema. Never return
// schema-violating structuredContent: the MCP SDK rejects it with an
// output validation error.
const parsed = MatrixResponseSchema.safeParse(data);
if (!parsed.success) {
this.log(
'warning',
`MatrixTool: Response validation failed: ${parsed.error.message}`
);
return {
content: [
{
type: 'text',
text: `Matrix API returned a response that didn't match the expected format: ${parsed.error.message}`
}
],
isError: true
};
}
const validatedData: MatrixResponse = singlePair
? pickSecondDestination(parsed.data)
: parsed.data;

// A coordinate the API can't snap to the road network (in the water,
// or with latitude and longitude swapped) comes back as a null waypoint.
const unroutable = input.coordinates
.map((_, idx) => idx)
.filter(
(idx) =>
validatedData.sources[idx] === null ||
validatedData.destinations[idx] === null
);
const note =
unroutable.length > 0 && !input.sources && !input.destinations
? `\n\nNote: coordinates at index ${unroutable.join(', ')} could not be snapped to the road network, so their travel times are null. Check that they are on land and in longitude,latitude order.`
: '';

return {
content: [{ type: 'text', text: JSON.stringify(validatedData, null, 2) }],
content: [
{ type: 'text', text: JSON.stringify(validatedData, null, 2) + note }
],
structuredContent: validatedData,
isError: false
};
}
}

// Keep only the second destination of a 1x2 matrix (see singlePair above).
function pickSecondDestination(data: MatrixResponse): MatrixResponse {
return {
...data,
destinations: data.destinations.slice(1, 2),
...(data.durations && {
durations: data.durations.map((row) => row.slice(1, 2))
}),
...(data.distances && {
distances: data.distances.map((row) => row.slice(1, 2))
})
};
}
Loading
Loading