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;
    }
Behavior2/5

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

With no annotations provided, the description carries full burden but offers minimal behavioral insight. It mentions 'search' and 'convert' but doesn't disclose rate limits, authentication needs, error handling, or what the output looks like (e.g., coordinates format). This is inadequate for a tool with 5 parameters and no output schema.

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 a single, efficient sentence with zero waste. It's front-loaded with the core purpose and appropriately sized for the tool's complexity, 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 moderate complexity (5 parameters, no annotations, no output schema), the description is incomplete. It lacks behavioral details, usage context, and output information, leaving significant gaps for an agent to operate effectively without trial and error.

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?

Schema description coverage is 100%, so the schema fully documents all 5 parameters. The description adds no additional meaning beyond implying geocoding functionality, which aligns with the schema but doesn't enhance parameter understanding. Baseline 3 is appropriate as the schema does the heavy lifting.

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 like mapbox_directions by focusing on geocoding rather than routing, though it doesn't explicitly name the differentiation.

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 alternatives like mapbox_directions or mapbox_matrix. 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.

Install Server

Other Tools

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