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;
    }

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/AidenYangX/mapbox-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server