Skip to main content
Glama

mapbox_geocoding

Convert addresses to geographic coordinates and search for places using Mapbox's geocoding API. Supports filtering by location types and language preferences.

Instructions

Search for places and convert addresses into coordinates

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
searchTextYesThe search text to geocode
limitNoLimit the number of results
typesNoFilter results by feature types
languageNoLanguage of the search results
fuzzyMatchNoEnable/disable fuzzy matching

Implementation Reference

  • The handleGeocoding function implements the core tool logic: constructs the Mapbox API request URL with search parameters (searchText, limit, types, language, fuzzyMatch), handles API errors and empty results, transforms the response to a simplified format with name, full_address, coordinates, type, relevance, and properties, and returns MCP-formatted content.
    export async function handleGeocoding(
      args: z.infer<typeof GeocodingArgsSchema>
    ) {
      const { searchText, limit, types, language, fuzzyMatch } = args;
    
      const url = new URL(
        "https://api.mapbox.com/geocoding/v5/mapbox.places/" +
          encodeURIComponent(searchText) +
          ".json"
      );
      url.searchParams.append("access_token", MAPBOX_ACCESS_TOKEN);
      url.searchParams.append("limit", limit.toString());
    
      if (types?.length) {
        url.searchParams.append("types", types.join(","));
      }
      if (language) {
        url.searchParams.append("language", language);
      }
      url.searchParams.append("fuzzyMatch", fuzzyMatch.toString());
    
      try {
        const response = await fetch(url.toString());
    
        // Handle Server Error (HTTP Status Code >= 500)
        if (response.status >= 500) {
          return {
            content: [
              {
                type: "text",
                text: `Mapbox Server Error: HTTP ${response.status}`,
              },
            ],
            isError: true,
          };
        }
    
        const data = (await response.json()) as MapboxGeocodingResponse;
    
        // Handle Business Logic Error
        if (!data.features || data.features.length === 0) {
          return {
            content: [
              {
                type: "text",
                text: "No results found for the given search text",
              },
            ],
            isError: true,
          };
        }
    
        // Success Case
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify({
                results: data.features.map((feature) => ({
                  name: feature.text,
                  full_address: feature.place_name,
                  coordinates: {
                    longitude: feature.center[0],
                    latitude: feature.center[1],
                  },
                  type: feature.place_type[0],
                  relevance: feature.relevance,
                  properties: feature.properties,
                })),
              }),
            },
          ],
          isError: false,
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: `Request Failed: ${
                error instanceof Error ? error.message : String(error)
              }`,
            },
          ],
          isError: true,
        };
      }
    }
  • SearchHandler class registers 'mapbox_geocoding' tool (line 15), stores the tool definition (line 16), and routes requests to the handler by validating args with GeocodingArgsSchema and calling handleGeocoding (lines 21-24).
    export class SearchHandler extends BaseHandler {
      constructor() {
        super();
        this.tools.add("mapbox_geocoding");
        this.toolDefinitions.push(GEOCODING_TOOL);
      }
    
      async handle({ name, args }: { name: string; args: any }) {
        switch (name) {
          case "mapbox_geocoding": {
            const validatedArgs = GeocodingArgsSchema.parse(args);
            return await handleGeocoding(validatedArgs);
          }
          default:
            throw new Error(`Unsupported search tool: ${name}`);
        }
      }
  • GEOCODING_TOOL definition for MCP: defines tool name 'mapbox_geocoding', description, and inputSchema with properties for searchText (required), limit (1-10, default 5), types (enum array), language (2-letter code), and fuzzyMatch (boolean, default true).
    export const GEOCODING_TOOL: Tool = {
      name: "mapbox_geocoding",
      description: "Search for places and convert addresses into coordinates",
      inputSchema: {
        type: "object",
        properties: {
          searchText: {
            type: "string",
            description: "The search text to geocode",
          },
          limit: {
            type: "number",
            description: "Limit the number of results",
            minimum: 1,
            maximum: 10,
            default: 5,
          },
          types: {
            type: "array",
            items: {
              type: "string",
              enum: [
                "country",
                "region",
                "postcode",
                "district",
                "place",
                "locality",
                "neighborhood",
                "address",
                "poi",
              ],
            },
            description: "Filter results by feature types",
          },
          language: {
            type: "string",
            description: "Language of the search results",
            pattern: "^[a-z]{2}$",
          },
          fuzzyMatch: {
            type: "boolean",
            description: "Enable/disable fuzzy matching",
            default: true,
          },
        },
        required: ["searchText"],
      },
    };
  • Zod validation schema (GeocodingArgsSchema) for runtime argument validation: defines searchText as required string, limit as number (1-10, default 5), types as optional enum array, language as optional 2-letter regex, and fuzzyMatch as boolean with default true.
    export const GeocodingArgsSchema = z.object({
      searchText: z.string().min(1).describe("The search text to geocode"),
      limit: z
        .number()
        .min(1)
        .max(10)
        .default(5)
        .describe("Limit the number of results"),
      types: z
        .array(
          z.enum([
            "country",
            "region",
            "postcode",
            "district",
            "place",
            "locality",
            "neighborhood",
            "address",
            "poi",
          ])
        )
        .optional()
        .describe("Filter results by feature types"),
      language: z
        .string()
        .regex(/^[a-z]{2}$/)
        .optional()
        .describe("Language of the search results"),
      fuzzyMatch: z
        .boolean()
        .default(true)
        .describe("Enable/disable fuzzy matching"),
    });
  • MapboxGeocodingResponse TypeScript interface defining the API response structure: FeatureCollection type with query array, features array containing id, type, place_type, relevance, properties, text, place_name, center coordinates, geometry, and optional context.
    export interface MapboxGeocodingResponse {
      type: "FeatureCollection";
      query: string[];
      features: Array<{
        id: string;
        type: "Feature";
        place_type: string[];
        relevance: number;
        properties: {
          accuracy?: string;
          address?: string;
          category?: string;
          maki?: string;
        };
        text: string;
        place_name: string;
        center: [number, number];
        geometry: {
          type: "Point";
          coordinates: [number, number];
        };
        context?: Array<{
          id: string;
          text: string;
          wikidata?: string;
          short_code?: string;
        }>;
      }>;
      attribution: string;
    }

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observedv1.0.0

TDQS

C2.9/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions the core functionality but omits critical details such as rate limits, authentication requirements, error handling, response format, or whether this is a read-only operation. For a geocoding tool with external API dependencies, this is a significant gap.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is extremely concise (one sentence) and front-loaded with the core purpose. Every word earns its place, with no redundant or unnecessary information, making it easy for an agent to parse quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (geocoding with 5 parameters), lack of annotations, and no output schema, the description is incomplete. It doesn't address behavioral aspects like API constraints, response structure, or error conditions, which are essential for proper tool invocation in a real-world context.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema description coverage is 100%, providing clear documentation for all 5 parameters. The description adds no additional parameter semantics beyond what's in the schema, so it meets the baseline score of 3. It doesn't explain how parameters interact or provide usage examples.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with specific verbs ('Search for places' and 'convert addresses into coordinates') and identifies the resource (geographic data). It distinguishes from sibling tools by focusing on geocoding rather than directions or matrix calculations, though it doesn't explicitly name those alternatives.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus the sibling tools (mapbox_directions, mapbox_directions_by_places, mapbox_matrix, mapbox_matrix_by_places). It doesn't mention use cases, prerequisites, or exclusions, leaving the agent to infer usage from the purpose alone.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.