From 1c6db1edaa218b7eccb829e557ba1fdab1104924 Mon Sep 17 00:00:00 2001 From: Matthew Podwysocki Date: Mon, 16 Nov 2026 13:11:18 -0500 Subject: [PATCH 1/2] fix: fewer failed matrix_tool and map_matching_tool calls - matrix_tool: allow null waypoints for unroutable coordinates, return a tool error instead of schema-violating structuredContent, and replace the "all coordinates used" check with the API's two-element minimum. - map_matching_tool: say it's for dense GPS traces and point to directions_tool, fix the radius default in the description, reject a radius of 0 and non-ascending timestamps. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 ++ .../MapMatchingTool.input.schema.ts | 10 +- .../map-matching-tool/MapMatchingTool.ts | 42 +++++++-- .../matrix-tool/MatrixTool.output.schema.ts | 6 +- src/tools/matrix-tool/MatrixTool.ts | 92 +++++++++++-------- .../map-matching-tool/MapMatchingTool.test.ts | 68 +++++++++++++- test/tools/matrix-tool/MatrixTool.test.ts | 75 +++++++++++++-- 7 files changed, 243 insertions(+), 58 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bce77e7f..48757b74 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ ## 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. Each cause below was reproduced against the live APIs. + - **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. + - **`matrix_tool` refused valid requests:** 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). The real limit is at least two matrix elements, which is what the tool checks now. + - **`map_matching_tool` was used for routing:** models called 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, with a documented range up to 50. A radius of 0, which the API refuses, is now rejected, and so are timestamps that aren't in ascending order, which the API answers with `NoMatch`. + ## 0.18.1-dev.1 - 2026-11-16 ## 0.18.0 - 2026-11-11 diff --git a/src/tools/map-matching-tool/MapMatchingTool.input.schema.ts b/src/tools/map-matching-tool/MapMatchingTool.input.schema.ts index 6ad43dfd..5a652ece 100644 --- a/src/tools/map-matching-tool/MapMatchingTool.input.schema.ts +++ b/src/tools/map-matching-tool/MapMatchingTool.input.schema.ts @@ -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()) .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; the documented range is 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'])) diff --git a/src/tools/map-matching-tool/MapMatchingTool.ts b/src/tools/map-matching-tool/MapMatchingTool.ts index 089180f8..7579a5c3 100644 --- a/src/tools/map-matching-tool/MapMatchingTool.ts +++ b/src/tools/map-matching-tool/MapMatchingTool.ts @@ -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', @@ -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 { @@ -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 @@ -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 diff --git a/src/tools/matrix-tool/MatrixTool.output.schema.ts b/src/tools/matrix-tool/MatrixTool.output.schema.ts index 2b22226e..c60f70ef 100644 --- a/src/tools/matrix-tool/MatrixTool.output.schema.ts +++ b/src/tools/matrix-tool/MatrixTool.output.schema.ts @@ -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 }); diff --git a/src/tools/matrix-tool/MatrixTool.ts b/src/tools/matrix-tool/MatrixTool.ts index 56d65400..5ddea09d 100644 --- a/src/tools/matrix-tool/MatrixTool.ts +++ b/src/tools/matrix-tool/MatrixTool.ts @@ -211,34 +211,25 @@ 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; + if (sourceCount * destinationCount < 2) { + 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 @@ -297,18 +288,45 @@ 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 = 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 }; diff --git a/test/tools/map-matching-tool/MapMatchingTool.test.ts b/test/tools/map-matching-tool/MapMatchingTool.test.ts index 35baff12..935fda9d 100644 --- a/test/tools/map-matching-tool/MapMatchingTool.test.ts +++ b/test/tools/map-matching-tool/MapMatchingTool.test.ts @@ -211,6 +211,72 @@ describe('MapMatchingTool', () => { }); }); + it('returns error when timestamps are not ascending', async () => { + const { httpRequest, mockHttpRequest } = setupHttpRequest(); + + const tool = new MapMatchingTool({ httpRequest }); + const result = await tool.run({ + coordinates: [ + { longitude: -122.4194, latitude: 37.7749 }, + { longitude: -122.4195, latitude: 37.775 } + ], + profile: 'driving', + timestamps: [1700000000, 1700000000] + }); + + expect(result.isError).toBe(true); + expect(mockHttpRequest).not.toHaveBeenCalled(); + expect(result.content[0]).toMatchObject({ + type: 'text', + text: expect.stringContaining('strictly ascending order') + }); + }); + + it('rejects a radius of 0, which the API refuses', async () => { + const { httpRequest, mockHttpRequest } = setupHttpRequest(); + + const tool = new MapMatchingTool({ httpRequest }); + const result = await tool.run({ + coordinates: [ + { longitude: -122.4194, latitude: 37.7749 }, + { longitude: -122.4195, latitude: 37.775 } + ], + profile: 'driving', + radiuses: [0, 0] + }); + + expect(result.isError).toBe(true); + expect(mockHttpRequest).not.toHaveBeenCalled(); + }); + + it('points to directions_tool when the points are too far apart', async () => { + const { httpRequest } = setupHttpRequest({ + ok: false, + status: 422, + statusText: 'Unprocessable Entity', + text: async () => + JSON.stringify({ + code: 'InvalidInput', + message: 'All coordinates are too far away from each other' + }) + }); + + const tool = new MapMatchingTool({ httpRequest }); + const result = await tool.run({ + coordinates: [ + { longitude: -122.42, latitude: 37.78 }, + { longitude: -118.24, latitude: 34.05 } + ], + profile: 'driving' + }); + + expect(result.isError).toBe(true); + expect(result.content[0]).toMatchObject({ + type: 'text', + text: expect.stringContaining('use directions_tool instead') + }); + }); + it('supports different routing profiles', async () => { const { httpRequest, mockHttpRequest } = setupHttpRequest({ json: async () => sampleMapMatchingResponse @@ -247,7 +313,7 @@ describe('MapMatchingTool', () => { expect(result.structuredContent).toBeUndefined(); expect(result.content[0]).toMatchObject({ type: 'text', - text: expect.stringContaining('NoMatch') + text: expect.stringMatching(/NoMatch.*directions_tool/) }); }); diff --git a/test/tools/matrix-tool/MatrixTool.test.ts b/test/tools/matrix-tool/MatrixTool.test.ts index 3ffc1d2b..31055536 100644 --- a/test/tools/matrix-tool/MatrixTool.test.ts +++ b/test/tools/matrix-tool/MatrixTool.test.ts @@ -800,7 +800,7 @@ describe('MatrixTool', () => { expect(resultWithSuccess2.isError).toBe(false); }); - it('rejects sources and destinations with unused coordinates', async () => { + it('rejects sources and destinations that give a single matrix element', async () => { const { httpRequest, mockHttpRequest } = setupHttpRequest({ json: () => Promise.resolve(sampleMatrixResponse) }); @@ -818,7 +818,7 @@ describe('MatrixTool', () => { expect(result.isError).toBe(true); expect(mockHttpRequest).not.toHaveBeenCalled(); - // Test direct error message for unused coordinates + // Test direct error message for a single-element matrix const unusedCoordsResult = await tool['execute']( { coordinates: [ @@ -837,12 +837,12 @@ describe('MatrixTool', () => { expect(unusedCoordsResult.content[0].type).toBe('text'); if (unusedCoordsResult.content[0].type === 'text') { expect(unusedCoordsResult.content[0].text).toContain( - 'When specifying both sources and destinations, all coordinates must be used as either a source or destination.' + 'The sources and destinations must give at least two matrix elements' ); } }); - it('accepts sources and destinations with single indices when all coordinates are used', async () => { + it('accepts sources and destinations that leave some coordinates unused', async () => { const { httpRequest, mockHttpRequest } = setupHttpRequest({ json: () => Promise.resolve(sampleMatrixResponse) }); @@ -850,15 +850,76 @@ describe('MatrixTool', () => { await tool.run({ coordinates: [ { longitude: -122.42, latitude: 37.78 }, - { longitude: -122.45, latitude: 37.91 } + { longitude: -122.45, latitude: 37.91 }, + { longitude: -122.48, latitude: 37.73 }, + { longitude: -122.4, latitude: 37.79 } ], profile: 'mapbox/driving', sources: '0', - destinations: '1' + destinations: '1;2' }); const url = mockHttpRequest.mock.calls[0][0]; expect(url).toContain('sources=0'); - expect(url).toContain('destinations=1'); + expect(url).toContain('destinations=1%3B2'); + }); + + it('returns null waypoints for unroutable coordinates with a note', async () => { + const response = { + code: 'Ok', + durations: [ + [0, 2391.7, null], + [2470.9, 0, null], + [null, null, null] + ], + sources: [ + sampleMatrixResponse.sources[0], + sampleMatrixResponse.sources[1], + null + ], + destinations: [ + sampleMatrixResponse.destinations[0], + sampleMatrixResponse.destinations[1], + null + ] + }; + const { httpRequest } = setupHttpRequest({ + json: () => Promise.resolve(response) + }); + const tool = new MatrixTool({ httpRequest }); + const result = await tool.run({ + coordinates: [ + { longitude: -122.42, latitude: 37.78 }, + { longitude: -122.45, latitude: 37.91 }, + { longitude: -140, latitude: 30 } + ], + profile: 'mapbox/driving' + }); + + expect(result.isError).toBe(false); + expect(result.structuredContent).toEqual(response); + expect(result.content[0].type).toBe('text'); + if (result.content[0].type === 'text') { + expect(result.content[0].text).toContain( + 'coordinates at index 2 could not be snapped to the road network' + ); + } + }); + + it('returns an error instead of a response that fails the output schema', async () => { + const { httpRequest } = setupHttpRequest({ + json: () => Promise.resolve({ code: 'Ok', durations: [[0, 1]] }) + }); + const tool = new MatrixTool({ httpRequest }); + const result = await tool.run({ + coordinates: [ + { longitude: -122.42, latitude: 37.78 }, + { longitude: -122.45, latitude: 37.91 } + ], + profile: 'mapbox/driving' + }); + + expect(result.isError).toBe(true); + expect(result.structuredContent).toBeUndefined(); }); it('accepts both annotations orders', async () => { From 483c1c581191d6e50f3909c42f888fd0d774e62f Mon Sep 17 00:00:00 2001 From: Matthew Podwysocki Date: Mon, 16 Nov 2026 13:16:06 -0500 Subject: [PATCH 2/2] fix: handle single-pair matrices, 429s and map matching without geometry From the hosted server's logs: most matrix_tool errors were one-element matrices the API refuses (944 of 1,181), then 429s (215). Map matching's were matchings without geometry from overview=false (10 of 16). - matrix_tool: ask for a 1x2 matrix for a single pair and return only that pair; explain the rate limit in the description and on a 429. - map_matching_tool: geometry is optional; radiuses go up to 50, which the API enforces. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 +-- .../MapMatchingTool.input.schema.ts | 4 +- .../MapMatchingTool.output.schema.ts | 3 +- src/tools/matrix-tool/MatrixTool.ts | 43 +++++++++-- .../map-matching-tool/MapMatchingTool.test.ts | 23 ++++++ test/tools/matrix-tool/MatrixTool.test.ts | 72 ++++++++++++++++++- 6 files changed, 141 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 48757b74..4efb638e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,11 +2,14 @@ ### 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. Each cause below was reproduced against the live APIs. +- **`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. - - **`matrix_tool` refused valid requests:** 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). The real limit is at least two matrix elements, which is what the tool checks now. - - **`map_matching_tool` was used for routing:** models called 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, with a documented range up to 50. A radius of 0, which the API refuses, is now rejected, and so are timestamps that aren't in ascending order, which the API answers with `NoMatch`. + - **`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 diff --git a/src/tools/map-matching-tool/MapMatchingTool.input.schema.ts b/src/tools/map-matching-tool/MapMatchingTool.input.schema.ts index 5a652ece..24fb862c 100644 --- a/src/tools/map-matching-tool/MapMatchingTool.input.schema.ts +++ b/src/tools/map-matching-tool/MapMatchingTool.input.schema.ts @@ -33,10 +33,10 @@ export const MapMatchingInputSchema = z.object({ 'Used to improve matching accuracy based on speed.' ), radiuses: z - .array(z.number().positive()) + .array(z.number().positive().max(50)) .optional() .describe( - 'Array of maximum distances (in meters, greater than 0; the documented range is up to 50) 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 5 meters. Use smaller values (1-10m) for clean GPS traces, ' + 'larger values (20-50m) for noisy GPS traces.' diff --git a/src/tools/map-matching-tool/MapMatchingTool.output.schema.ts b/src/tools/map-matching-tool/MapMatchingTool.output.schema.ts index 8c47e6b3..f16eb6a4 100644 --- a/src/tools/map-matching-tool/MapMatchingTool.output.schema.ts +++ b/src/tools/map-matching-tool/MapMatchingTool.output.schema.ts @@ -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({ diff --git a/src/tools/matrix-tool/MatrixTool.ts b/src/tools/matrix-tool/MatrixTool.ts index 5ddea09d..10dd902e 100644 --- a/src/tools/matrix-tool/MatrixTool.ts +++ b/src/tools/matrix-tool/MatrixTool.ts @@ -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, @@ -220,7 +222,13 @@ export class MatrixTool extends MapboxApiBasedTool< input.destinations && input.destinations !== 'all' ? input.destinations.split(';').length : input.coordinates.length; - if (sourceCount * destinationCount < 2) { + // 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: [ { @@ -257,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); } @@ -278,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 @@ -307,7 +324,9 @@ export class MatrixTool extends MapboxApiBasedTool< isError: true }; } - const validatedData: MatrixResponse = parsed.data; + 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. @@ -332,3 +351,17 @@ export class MatrixTool extends MapboxApiBasedTool< }; } } + +// 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)) + }) + }; +} diff --git a/test/tools/map-matching-tool/MapMatchingTool.test.ts b/test/tools/map-matching-tool/MapMatchingTool.test.ts index 935fda9d..409c71fe 100644 --- a/test/tools/map-matching-tool/MapMatchingTool.test.ts +++ b/test/tools/map-matching-tool/MapMatchingTool.test.ts @@ -277,6 +277,29 @@ describe('MapMatchingTool', () => { }); }); + it('accepts matchings without geometry when overview is false', async () => { + const { geometry: _geometry, ...matching } = + sampleMapMatchingResponse.matchings[0]; + const { httpRequest } = setupHttpRequest({ + json: async () => ({ + ...sampleMapMatchingResponse, + matchings: [matching] + }) + }); + + const tool = new MapMatchingTool({ httpRequest }); + const result = await tool.run({ + coordinates: [ + { longitude: -122.4194, latitude: 37.7749 }, + { longitude: -122.4195, latitude: 37.775 } + ], + profile: 'driving', + overview: 'false' + }); + + expect(result.isError).toBe(false); + }); + it('supports different routing profiles', async () => { const { httpRequest, mockHttpRequest } = setupHttpRequest({ json: async () => sampleMapMatchingResponse diff --git a/test/tools/matrix-tool/MatrixTool.test.ts b/test/tools/matrix-tool/MatrixTool.test.ts index 31055536..18d34578 100644 --- a/test/tools/matrix-tool/MatrixTool.test.ts +++ b/test/tools/matrix-tool/MatrixTool.test.ts @@ -800,7 +800,7 @@ describe('MatrixTool', () => { expect(resultWithSuccess2.isError).toBe(false); }); - it('rejects sources and destinations that give a single matrix element', async () => { + it('rejects a source that is also its only destination', async () => { const { httpRequest, mockHttpRequest } = setupHttpRequest({ json: () => Promise.resolve(sampleMatrixResponse) }); @@ -813,7 +813,7 @@ describe('MatrixTool', () => { ], profile: 'mapbox/driving', sources: '1', - destinations: '2' + destinations: '1' }); expect(result.isError).toBe(true); expect(mockHttpRequest).not.toHaveBeenCalled(); @@ -828,7 +828,7 @@ describe('MatrixTool', () => { ], profile: 'mapbox/driving', sources: '1', - destinations: '2' + destinations: '1' }, 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0In0.signature' ); @@ -842,6 +842,72 @@ describe('MatrixTool', () => { } }); + it('asks for a 1x2 matrix for a single pair and returns only that pair', async () => { + const response = { + code: 'Ok', + durations: [[0, 1510.9]], + distances: [[0, 9100.4]], + sources: [sampleMatrixResponse.sources[0]], + destinations: [ + sampleMatrixResponse.destinations[0], + sampleMatrixResponse.destinations[2] + ] + }; + const { httpRequest, mockHttpRequest } = setupHttpRequest({ + json: () => Promise.resolve(response) + }); + const tool = new MatrixTool({ httpRequest }); + const result = await tool.run({ + coordinates: [ + { longitude: -122.42, latitude: 37.78 }, + { longitude: -122.45, latitude: 37.91 }, + { longitude: -122.48, latitude: 37.73 } + ], + profile: 'mapbox/driving', + annotations: 'duration,distance', + sources: '0', + destinations: '2' + }); + + const url = mockHttpRequest.mock.calls[0][0]; + expect(url).toContain('sources=0'); + expect(url).toContain('destinations=0%3B2'); + expect(result.isError).toBe(false); + expect(result.structuredContent).toEqual({ + code: 'Ok', + durations: [[1510.9]], + distances: [[9100.4]], + sources: [sampleMatrixResponse.sources[0]], + destinations: [sampleMatrixResponse.destinations[2]] + }); + }); + + it('explains the rate limit on a 429', async () => { + const { httpRequest } = setupHttpRequest({ + ok: false, + status: 429, + statusText: 'Too Many Requests', + text: async () => JSON.stringify({ message: 'Too Many Requests' }) + }); + const tool = new MatrixTool({ httpRequest }); + const result = await tool['execute']( + { + coordinates: [ + { longitude: -122.42, latitude: 37.78 }, + { longitude: -122.45, latitude: 37.91 } + ], + profile: 'mapbox/driving' + }, + 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0In0.signature' + ); + + expect(result.isError).toBe(true); + expect(result.content[0]).toMatchObject({ + type: 'text', + text: expect.stringContaining('60 requests per minute') + }); + }); + it('accepts sources and destinations that leave some coordinates unused', async () => { const { httpRequest, mockHttpRequest } = setupHttpRequest({ json: () => Promise.resolve(sampleMatrixResponse)