Skip to main content
Glama

normalize_address

Standardize US mailing addresses to USPS format by expanding abbreviations, converting state names to codes, and normalizing directionals. Returns parsed components and confidence scores.

Instructions

Normalize a US mailing address to USPS standard format. Expands abbreviations (st→ST, ave→AVE), standardizes directionals, converts state names to codes. Returns parsed components and a confidence score (high/medium/low).

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
addressYesThe US address to normalize
includeComponentsNoInclude parsed address components in response

Implementation Reference

  • The handler function for the address normalization tool, which calls the parsing utility and returns the normalized result.
    async function handler(input: Input) {
      const { components, normalized, confidence } = parseAddress(input.address);
    
      return {
        original: input.address,
        normalized,
        confidence,
        ...(input.includeComponents && { components }),
      };
    }
  • Input schema validation for the address normalization tool.
    const inputSchema = z.object({
      address: z.string().min(1).max(500).describe("The address string to normalize"),
      includeComponents: z
        .boolean()
        .default(true)
        .describe("Include parsed address components in the response"),
    });
  • The tool definition and registration call for 'address-normalizer'. Note that while the tool name in the code is 'address-normalizer', the MCP server index.ts references it as 'normalize_address'.
    const addressNormalizerTool: ToolDefinition<Input> = {
      name: "address-normalizer",
      description:
        "Normalize and standardize US mailing addresses to USPS format. Expands abbreviations, corrects capitalization, standardizes street types and directionals, and parses address components (street number, street name, unit, city, state, ZIP).",
      version: "1.0.0",
      inputSchema,
      handler,
      metadata: {
        tags: ["address", "normalization", "usps", "postal", "parsing"],
        pricing: "$0.0005 per call",
        exampleInput: {
          address: "123 main st apt 4b, springfield, il 62701",
          includeComponents: true,
        },
      },
    };
    
    registerTool(addressNormalizerTool);
  • Helper function that performs the core address parsing and normalization logic using USPS standard maps.
    function parseAddress(input: string): { components: AddressComponents; normalized: string; confidence: "high" | "medium" | "low" } {
      // Clean input
      const raw = input.trim().replace(/\s+/g, " ").replace(/[.]/g, "");
    
      // Split on comma to separate street from city/state/zip
      const parts = raw.split(",").map((p) => p.trim());
    
      const components: AddressComponents = {};
    
      // Parse city/state/zip from last parts
      // Last part often: "TX 75001" or "TX 75001-1234" or "Texas 75001"
      // Second-to-last: city name
      if (parts.length >= 3) {
        components.city = parts[parts.length - 2];
    
        const stateZip = parts[parts.length - 1].trim();
        const stateZipMatch = stateZip.match(/^([A-Za-z\s]+)\s+(\d{5})(?:-(\d{4}))?$/);
        if (stateZipMatch) {
          const stateRaw = stateZipMatch[1].trim().toLowerCase();
          components.state = STATE_ABBR[stateRaw] || stateZipMatch[1].trim().toUpperCase();
          components.zip = stateZipMatch[2];
          if (stateZipMatch[3]) components.zip4 = stateZipMatch[3];
        } else {
          // Try just state abbreviation
          const stateOnly = stateZip.match(/^([A-Za-z]{2})$/);
          if (stateOnly) components.state = stateOnly[1].toUpperCase();
          else components.state = stateZip.toUpperCase();
        }
      } else if (parts.length === 2) {
        // Could be "City ST 12345" in second part
        const second = parts[1].trim();
        const cityStateZip = second.match(/^(.+?)\s+([A-Za-z]{2})\s+(\d{5})(?:-(\d{4}))?$/);
        if (cityStateZip) {
          components.city = cityStateZip[1].trim();
          components.state = cityStateZip[2].toUpperCase();
          components.zip = cityStateZip[3];
          if (cityStateZip[4]) components.zip4 = cityStateZip[4];
        } else {
          // Might just be city
          components.city = second;
        }
      }
    
      // Parse street line (first part)
      const streetLine = parts[0];
      const tokens = streetLine.split(/\s+/);
    
      // Street number (first token if numeric)
      let idx = 0;
      if (/^\d+[A-Za-z]?$/.test(tokens[0])) {
        components.streetNumber = tokens[0].toUpperCase();
        idx = 1;
      }
    
      // Pre-directional
      if (idx < tokens.length && DIRECTIONAL[tokens[idx].toLowerCase()]) {
        // Only treat as directional if the next token looks like a street name
        const maybeDir = DIRECTIONAL[tokens[idx].toLowerCase()];
        if (idx + 1 < tokens.length) {
          components.preDirectional = maybeDir;
          idx++;
        }
      }
    
      // Street type and name — scan remaining tokens for a street type suffix
      const remaining = tokens.slice(idx);
      let streetTypeIdx = -1;
      for (let i = remaining.length - 1; i >= 0; i--) {
        const t = remaining[i].toLowerCase();
        if (STREET_TYPES[t]) {
          streetTypeIdx = i;
          break;
        }
      }
    
      if (streetTypeIdx >= 0) {
        components.streetName = remaining.slice(0, streetTypeIdx).map((t) => {
          const d = DIRECTIONAL[t.toLowerCase()];
          return d || t.charAt(0).toUpperCase() + t.slice(1).toLowerCase();
        }).join(" ");
        components.streetType = STREET_TYPES[remaining[streetTypeIdx].toLowerCase()];
    
        // Post-directional and secondary unit after street type
        const after = remaining.slice(streetTypeIdx + 1);
        let afterIdx = 0;
    
        if (afterIdx < after.length && DIRECTIONAL[after[afterIdx].toLowerCase()]) {
          components.postDirectional = DIRECTIONAL[after[afterIdx].toLowerCase()];
          afterIdx++;
        }
    
        // Secondary unit designator
        if (afterIdx < after.length) {
          const unitKey = after[afterIdx].toLowerCase();
          if (SECONDARY_UNIT[unitKey]) {
            components.secondaryUnit = SECONDARY_UNIT[unitKey];
            afterIdx++;
            if (afterIdx < after.length) {
              components.secondaryNumber = after[afterIdx].toUpperCase();
            }
          } else if (/^#/.test(after[afterIdx])) {
            components.secondaryUnit = "APT";
            components.secondaryNumber = after[afterIdx].replace("#", "").toUpperCase();
          }
        }
      } else {
        // No street type found — just use all remaining as street name
        components.streetName = remaining.join(" ");
      }
    
      // Capitalize city
      if (components.city) {
        components.city = components.city
          .split(" ")
          .map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
          .join(" ");
      }
    
      // Build normalized string
      const lineParts: string[] = [];
    
      // Line 1: street
      const street = [
        components.streetNumber,
        components.preDirectional,
        components.streetName,
        components.streetType,
        components.postDirectional,
        components.secondaryUnit && components.secondaryNumber
          ? `${components.secondaryUnit} ${components.secondaryNumber}`
          : components.secondaryUnit,
      ].filter(Boolean).join(" ");
      if (street) lineParts.push(street);
    
      // Line 2: city state zip
      const cityStateZip = [
        components.city,
        components.state,
        components.zip4 ? `${components.zip}-${components.zip4}` : components.zip,
      ].filter(Boolean).join(" ");
      if (cityStateZip) lineParts.push(cityStateZip);
    
      const normalized = lineParts.join(", ");
    
      // Confidence heuristic
      const hasStreetNum = !!components.streetNumber;
      const hasStreetType = !!components.streetType;
      const hasCity = !!components.city;
      const hasState = !!components.state;
      const hasZip = !!components.zip;
    
      const score = [hasStreetNum, hasStreetType, hasCity, hasState, hasZip].filter(Boolean).length;
      const confidence: "high" | "medium" | "low" = score >= 4 ? "high" : score >= 2 ? "medium" : "low";
    
      return { components, normalized, confidence };
    }

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/marras0914/agent-toolbelt'

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