Skip to main content
Glama

Address Normalizer

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

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

With no annotations provided, the description carries the full burden. It successfully discloses transformation logic (st→ST examples) and output structure (confidence score levels: high/medium/low). However, it omits operational characteristics like idempotency, error handling for invalid addresses, or whether the operation is read-only.

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?

Two efficiently structured sentences with zero waste. The first states the core purpose; the second provides concrete transformation examples (parenthetical) and return value specification. Information is front-loaded and every clause earns its place.

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

Completeness4/5

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

For a low-complexity tool (2 parameters, no output schema), the description adequately compensates by detailing return values (confidence scoring, component parsing) and input constraints (US-only). A perfect score would require explicit error behavior or validation rules.

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%, establishing a baseline of 3. The description adds marginal semantic context by referencing 'parsed components' in the return description, which connects to the includeComponents parameter's purpose, but does not elaborate on parameter syntax or the address input format beyond the schema definition.

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

Purpose5/5

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

The description opens with a precise verb ('Normalize') and specific resource ('US mailing address'), clearly distinguishing it from all siblings (none handle address processing). It further clarifies the USPS standard scope and explains exactly what normalization entails (abbreviation expansion, directional standardization, state code conversion).

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

Usage Guidelines4/5

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

The description provides clear context through the 'US mailing address' scope constraint, implicitly defining when to use it (US addresses only). However, it lacks explicit 'when not to use' guidance (e.g., international addresses) or named alternatives, though none exist in the sibling set.

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

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