Skip to main content
Glama

What's Inside

Two exports, one package:

Export

Import

Use Case

MCP Server

envia-mcp

AI agents (Claude Code, Claude Desktop, Cursor) interact with Envia via natural language

Client Library

envia-mcp/client

Node.js/TypeScript apps call the Envia API directly with full type safety

Type Definitions

envia-mcp/types

Zod schemas and TypeScript types for all API entities

Supported Countries

Americas

Country

Code

Carriers

Notable Carriers

Mexico

MX

34

DHL, FedEx, Estafeta, Paquetexpress, UPS

United States

US

33

FedEx, UPS, USPS, DHL, Sendle, LSO

Colombia

CO

16

FedEx, DHL, Coordinadora, Servientrega, TCC

Argentina

AR

12

Andreani, Correo Argentino, FedEx, DHL, OCA

Brazil

BR

11

Correios, FedEx, DHL, Jadlog, Loggi

Chile

CL

10

Chilexpress, Correos Chile, FedEx, DHL, Starken

Guatemala

GT

7

Cargo Expreso, DHL, Telomando

Canada

CA

4

Canada Post, Canpar, DHL, Purolator

Uruguay

UY

3

DHL, Treggo

Peru

PE

1

Olva

Europe, Asia & Oceania

Country

Code

Carriers

Notable Carriers

Spain

ES

16

Correos, DHL, FedEx, GLS, SEUR, UPS

India

IN

9

BlueDart, Delhivery, FedEx, Aramex, Xpressbees

France

FR

4

Chronopost, Mondial Relay, UPS

Italy

IT

4

Poste Italiane, BRT, InPost, UPS

Australia

AU

3

Aramex, FedEx, Sendle

Hong Kong

HK

1

FedEx

Japan

JP

1

—

China

CN

1

—

Envia adds carriers and countries over time. Use envia_get_carriers to get the current list.


Related MCP server: Easyship MCP

Quick Start

As an MCP Server

The server connects to Envia's sandbox by default — no real charges, safe to experiment.

Add to your Claude Code config (.mcp.json):

{
  "mcpServers": {
    "envia": {
      "command": "node",
      "args": ["/path/to/envia-mcp/dist/index.js"],
      "env": {
        "ENVIA_API_KEY": "your-sandbox-api-key"
      }
    }
  }
}

Or, if installed globally via npm:

{
  "mcpServers": {
    "envia": {
      "command": "npx",
      "args": ["envia-mcp"],
      "env": {
        "ENVIA_API_KEY": "your-sandbox-api-key"
      }
    }
  }
}

As a Client Library

import { EnviaClient } from 'envia-mcp/client';

// Sandbox (default — safe for testing)
const client = new EnviaClient({
  apiKey: process.env.ENVIA_API_KEY!,
  shippingUrl: 'https://api-test.envia.com',
  queriesUrl: 'https://queries-test.envia.com',
  geocodesUrl: 'https://geocodes.envia.com',
});

// Get rates from all carriers, sorted by price
const quotes = await client.getQuotesAllCarriers(origin, destination, packages);

// Purchase a label (charges your prepaid balance in USD)
const label = await client.createLabel(origin, destination, packages, 'fedex', 'ground');

// Track a shipment
const tracking = await client.trackShipments(['TRACK123']);

MCP Tools

The server exposes 11 tools that AI agents can call:

Tool

Description

Destructive

envia_quote

Get shipping rates from all carriers for a route

envia_create_label

Purchase a shipping label (charges USD balance)

Yes

envia_track

Track one or more shipments by tracking number

envia_cancel

Cancel a shipment and request refund

Yes

envia_validate_zipcode

Validate a postal code and get address info

envia_get_carriers

List available carriers for a country

envia_get_services

List services for a specific carrier

envia_shipment_history

Get shipment history for a given month/year

envia_schedule_pickup

Schedule a carrier pickup

Yes

envia_classify_hscode

Classify product description into HS code for customs

envia_lookup_city

Look up cities by name, get postal codes (no auth)

All tools return both Markdown (for display) and structured data (for programmatic use).

MCP Resources

7 documentation resources provide AI agents with context about the Envia API:

URI

Content

envia://docs/overview

API hosts, auth model, sandbox vs production

envia://docs/address-format-mx

Mexican address fields, state codes, colonia mapping

envia://docs/carriers

34 carriers, service counts, weight limits

envia://docs/rate-response

Price breakdown, MXN currency, additional charges

envia://docs/label-response

USD currency, permanent label URLs, no idempotency

envia://docs/errors

Error codes and how to handle them

envia://docs/international

International shipping guide: HS codes, commercial invoices, currency, duties

MCP Prompts

4 workflow prompts guide agents through multi-step tasks:

Prompt

What It Does

diagnose-shipment

Investigate tracking status, identify stuck/failed shipments

compare-rates

Quote all carriers for a route, compare price vs speed

verify-address

Validate a postal code, return neighborhoods and coordinates

prepare-international-shipment

Step-by-step international shipment workflow


Client API

The EnviaClient class provides typed methods for every Envia operation:

import { EnviaClient } from 'envia-mcp/client';

const client = new EnviaClient({ apiKey, shippingUrl, queriesUrl, geocodesUrl });

Method

Returns

Description

getQuotes(origin, dest, packages, carrier)

RateQuoteItem[]

Rates from one carrier

getQuotesAllCarriers(origin, dest, packages)

RateQuoteItem[]

Fan-out to all carriers, sorted by price

createLabel(origin, dest, packages, carrier, service)

LabelItem

Purchase a shipping label

trackShipments(trackingNumbers)

TrackingItem[]

Track one or more shipments

cancelShipment(carrier, trackingNumber)

CancellationItem

Cancel and request refund

validateZipCode(postalCode, countryCode?)

PostalCodeItem[]

Validate postal code (no auth needed)

getCarriers(countryCode?)

Carrier[]

List available carriers

getServices(carrier, countryCode?)

CarrierService[]

List services for a carrier

getShipmentHistory(month, year)

ShipmentHistoryItem[]

Get shipment history for a month

schedulePickup(request)

PickupResult

Schedule a carrier pickup

classifyHsCode(description, options?)

HsCodeClassification

Classify product into HS code

generateCommercialInvoice(request)

CommercialInvoiceResult

Generate commercial invoice for customs

lookupCity(city, countryCode?)

CityLookupItem[]

Look up cities by name, get postal codes

getAvailableCarriers(countryCode?, international?)

AvailableCarrier[]

List carriers with availability details


Envia API Gotchas

Things that will bite you if you're not careful:

Gotcha

Details

phone_code differs

Country code string for quotes (e.g. "MX"), dialing code for labels (e.g. "52")

Quotes are MXN, labels are USD

Prepaid balance is denominated in USD

Labels are NOT idempotent

Duplicate call = double charge, different tracking number

Sandbox geocodes is DOWN

Always use production geocodes.envia.com

Carrier is required per quote

The client fans out automatically, but the raw API needs one carrier per call

Track by tracking number

shipmentId does NOT work as a tracking key


Configuration

The MCP server reads configuration from environment variables:

Variable

Required

Default

Description

ENVIA_API_KEY

Yes

—

Your Envia.com API key

ENVIA_SHIPPING_URL

https://api-test.envia.com

Shipping API base URL

ENVIA_QUERIES_URL

https://queries-test.envia.com

Queries API base URL

ENVIA_GEOCODES_URL

https://geocodes.envia.com

Geocodes API base URL

Sandbox vs Production

The server defaults to Envia's sandbox environment. This is intentional.

The envia_create_label tool purchases real shipping labels — it costs money and is not idempotent (calling it twice creates two labels with different tracking numbers, charged twice). AI agents can trigger this tool multiple times during a conversation, and there is no undo. Defaulting to sandbox prevents accidental charges during development, testing, and experimentation.

This follows industry best practice: Supabase MCP recommends "never connect to production"; Stripe separates test/live keys; Slack MCP disables destructive operations by default.

Switching to production

To use the live Envia API, set the URL environment variables to production hosts:

{
  "mcpServers": {
    "envia": {
      "command": "node",
      "args": ["/path/to/envia-mcp/dist/index.js"],
      "env": {
        "ENVIA_API_KEY": "your-production-api-key",
        "ENVIA_SHIPPING_URL": "https://api.envia.com",
        "ENVIA_QUERIES_URL": "https://queries.envia.com"
      }
    }
  }
}

Important notes:

  • Sandbox and production use separate API keys — a sandbox key won't work on production and vice versa

  • Geocodes (geocodes.envia.com) always uses production — the sandbox geocodes endpoint is down (503)

  • The server logs (sandbox) or (PRODUCTION) on startup so you always know which environment you're hitting


Currency

The Envia API defaults to USD when the currency field is omitted from requests. This is a common source of confusion for Latin American users who expect MXN (or their local currency). The official @envia/envia-mcp server inherits this behavior, silently quoting and charging in USD.

Our implementation defaults to MXN. You can override this globally or per call:

// Default: MXN
const client = new EnviaClient({ apiKey, shippingUrl, queriesUrl, geocodesUrl });

// Override globally (e.g., for Colombia)
const client = new EnviaClient({
  apiKey,
  shippingUrl,
  queriesUrl,
  geocodesUrl,
  defaultCurrency: 'COP',
});

// Override per call via the currency parameter
const quotes = await client.getQuotesAllCarriers(origin, destination, packages, {
  currency: 'USD',
});

The MCP server also defaults to MXN. Set ENVIA_DEFAULT_CURRENCY to change it.


HTTP Features

The client includes production-grade HTTP handling:

  • SSRF protection — hostname allowlist restricts requests to known Envia API domains only

  • Retry with exponential backoff — failed requests retry up to 3 times with increasing delays

  • Retry-After header support — respects server-requested cooldown periods before retrying


Comparison with @envia/envia-mcp

Envia maintains an official MCP server at @envia/envia-mcp. Here is a factual comparison:

Feature

envia-mcp (this project)

@envia/envia-mcp (official)

Typed TypeScript client library

Yes

No

Configurable currency default

Yes (MXN default)

No (USD default)

Zod response validation

Yes

No

Structured MCP output (data + Markdown)

Yes

No

Sandbox geocodes fallback

Yes

No

SSRF protection (hostname allowlist)

Yes

No

Retry with exponential backoff

Yes

No

Official Envia branding

No

Yes

Sandbox by default

Yes

Yes

10+ MCP tools

Yes (11)

Yes

Known issues in the official server:

  • Missing settings object on label creation causes HTTP 400 errors

  • Defaults to USD instead of MXN, which is unexpected for the primary market (Mexico)


Development

# Clone and install
git clone https://github.com/amak07/envia-mcp.git
cd envia-mcp
npm.cmd install

# Build
npm.cmd run build

# Type check
npm.cmd run typecheck

# Run tests (30 unit tests, mocked API)
npm.cmd run test:run

# Dev mode (watch + restart)
npm.cmd run dev

Project Structure

src/
  index.ts          # MCP server entry point (shebang, stdio transport)
  client.ts         # EnviaClient class (standalone, no MCP dependency)
  types.ts          # Zod schemas + TypeScript types for all API entities
  utils.ts          # HTTP helpers, error handling, formatting
  constants.ts      # API URLs, character limits, response format
  tools/
    quote.ts        # envia_quote — fan-out rate quoting
    create-label.ts # envia_create_label — label purchase
    track.ts        # envia_track — shipment tracking
    cancel.ts       # envia_cancel — shipment cancellation
    validate-zipcode.ts  # envia_validate_zipcode — postal code lookup
    get-carriers.ts # envia_get_carriers — carrier directory
    get-services.ts # envia_get_services — service catalog
    index.ts        # Barrel — registerAllTools()
  resources/
    index.ts        # 6 inline documentation resources
  prompts/
    index.ts        # 3 workflow prompts
  client.test.ts    # 30 unit tests (mocked fetch)
tests/
  fixtures/         # Real API response snapshots (JSON)

Tech Stack

  • TypeScript with strict mode

  • MCP SDK @modelcontextprotocol/sdk 1.27+

  • Zod for runtime schema validation

  • Native fetch (Node.js 18+ built-in, no axios)

  • Vitest for unit testing

  • ESM ("type": "module")


License

MIT


Available Tools

11 tools
envia_cancelCancel Envia ShipmentA
Destructive

Cancel a shipment and request a refund. This is a DESTRUCTIVE operation.

WARNING: Cancellation cannot be undone. Confirm with the user before proceeding. If the shipment is already canceled, error 1115 will be returned.

Args: carrier — Carrier string (e.g., "dhl", "fedex", "estafeta") tracking_number — Tracking number of the shipment to cancel response_format — "markdown" (default) or "json"

Returns: Cancellation status, refunded amount, and balance return info.

Errors: 1115 — Shipment is already canceled 400 — Invalid carrier or tracking number 403 — Invalid API key

Inputs: carrier (required), tracking_number (required), response_format. Returns: status, carrier, refunded_amount, tracking_number, +2 more

envia_classify_hscodeClassify HS CodeA
Read-onlyIdempotent

Classify a product description into a Harmonized System (HS) code for customs declarations.

Args: description — Product description to classify (e.g., "ceramic brake pads for automobiles") destination_countries — Comma-separated destination country codes (optional, e.g., "US,CA") include_alternatives — Include alternative HS codes (default: true) response_format — "markdown" (default) or "json"

Returns: HS code, description, confidence score, and alternative codes.

Errors: 400 — Invalid or empty description 403 — Invalid API key

Inputs: description (required), response_format, include_alternatives, destination_countries. Returns: hs_code, description, alternatives, confidence_score

envia_create_labelPurchase Envia Shipping LabelA

Purchase a shipping label from Envia.com. THIS COSTS REAL MONEY.

WARNING: This tool is NOT idempotent. Each call creates a NEW shipment and charges your account. Do NOT call this tool multiple times for the same shipment — you will be double-charged. Always confirm with the user before calling this tool.

Args: origin_* — Sender address fields (name, company, street, street_number, neighborhood, city, state, postal_code, phone, email) origin_rfc — RFC / tax ID (default: XAXX010101000 for general public) dest_* — Recipient address fields (same structure) package_name — Short name for the package package_weight_kg, package_length_cm, package_width_cm, package_height_cm — Dimensions package_contents — Description of contents declared_value_mxn — Declared value (optional, default 0) carrier — Carrier string from quote response (e.g., "dhl") service — Service string from quote response (e.g., "ground") print_format — "PDF" (default) or "ZPL" print_size — "STOCK_4X6" (default) or "PAPER_8.5X11" response_format — "markdown" (default) or "json"

Returns: Shipment ID, tracking number, label URL, total price in USD, and remaining balance.

Errors: 400 — Invalid address/package fields or carrier/service mismatch 403 — Invalid API key Insufficient balance — Check current_balance_usd in response

Inputs: carrier (required), service (required), dest_city (required), dest_name (required), +29 more. Returns: carrier, service, currency, label_url, +5 more

envia_get_carriersList Envia CarriersA
Read-onlyIdempotent

List available shipping carriers on Envia.com for a country.

Mexico has 34+ carriers including DHL, FedEx, Estafeta, PaqueteExpress, Redpack, etc.

Args: country_code — Country code (default: "MX") limit — Max results per page (1-50, default: 20) offset — Pagination offset (default: 0) response_format — "markdown" (default) or "json"

Returns: Paginated list of carriers with ID, name, endpoint, weight limits, and pickup info.

Examples: First page: limit=20, offset=0 Second page: limit=20, offset=20 All MX carriers: limit=50, offset=0

Errors: 403 — Invalid API key

Inputs: limit, offset, country_code, response_format. Returns: count, total, offset, carriers, +2 more

envia_get_servicesList Carrier ServicesA
Read-onlyIdempotent

List available services for a specific carrier on Envia.com.

Service counts vary by carrier: DHL=31, FedEx=130, Estafeta=8.

Args: carrier — Carrier string (e.g., "dhl", "fedex", "estafeta") country_code — Country code (default: "MX") limit — Max results per page (1-100, default: 20) offset — Pagination offset (default: 0) response_format — "markdown" (default) or "json"

Returns: Paginated list of services with ID, name, description, delivery estimate, and capabilities.

Examples: DHL services: carrier="dhl" FedEx page 2: carrier="fedex", limit=20, offset=20

Errors: 400 — Invalid carrier name 403 — Invalid API key

Inputs: carrier (required), limit, offset, country_code, +1 more. Returns: count, total, offset, carrier, +3 more

envia_lookup_cityLook Up CityA
Read-onlyIdempotent

Look up cities by name to find postal codes, state, and region information.

Uses the Envia Geocodes API which requires no authentication.

Args: city — City name to search for (e.g., "Monterrey", "Guadalajara") country_code — Country code (default: "MX") response_format — "markdown" (default) or "json"

Returns: List of matching cities with state, postal codes, and region info.

Examples: Look up Monterrey: city="Monterrey" Look up with country: city="Monterrey", country_code="MX"

Errors: 500+ — Geocodes API temporarily unavailable (auto-retries with production fallback)

Inputs: city (required), country_code, response_format. Returns: total, cities, city_query

envia_quoteGet Envia Shipping QuotesA
Read-onlyIdempotent

Get shipping rate quotes from 34+ Mexican carriers via Envia.com.

Args: origin_* — Sender address fields (name, street, street_number, neighborhood, city, state, postal_code, phone, email) dest_* — Recipient address fields (same structure) package_weight_kg — Weight in kg package_length_cm, package_width_cm, package_height_cm — Dimensions in cm package_contents — Description of contents declared_value_mxn — Declared value (optional, default 0) carrier — Carrier filter: "dhl", "fedex", "estafeta", etc. Omit to quote ALL carriers. response_format — "markdown" (default) or "json"

Returns: List of rate options sorted by price (cheapest first) with carrier, service, delivery days, and price breakdown.

Examples: Quote all carriers: omit carrier field Quote single carrier: carrier="fedex"

Errors: 400 — Invalid address or package fields 403 — Invalid API key

Inputs: dest_city (required), dest_name (required), dest_email (required), dest_phone (required), +24 more. Returns: count, total, quotes, truncated

envia_schedule_pickupSchedule Envia Carrier PickupA
Destructive

Schedule a carrier pickup for one or more packages. This is a DESTRUCTIVE operation — it creates a real pickup request.

WARNING: Duplicate calls may create duplicate pickups. Confirm with the user before proceeding.

Args: origin_* — Pickup address fields (name, street, street_number, neighborhood, city, state, postal_code, phone, email) carrier — Carrier string (e.g., "dhl", "fedex", "estafeta") tracking_numbers — Comma-separated tracking numbers to pick up date — Pickup date in YYYY-MM-DD format time_from — Pickup window start hour (0-23) time_to — Pickup window end hour (0-23) total_weight — Total weight in kg total_packages — Number of packages instructions — Special instructions (optional) response_format — "markdown" (default) or "json"

Returns: Pickup confirmation number, carrier, date, time window, and status.

Errors: 400 — Invalid address, carrier, or time fields 403 — Invalid API key

Inputs: date (required), carrier (required), time_to (required), time_from (required), +16 more. Returns: date, status, carrier, time_to, +2 more

envia_shipment_historyGet Envia Shipment HistoryA
Read-onlyIdempotent

Get shipment history for a given month and year.

Args: month — Month number (1-12) year — Year (2020 or later) response_format — "markdown" (default) or "json"

Returns: List of shipments with tracking number, carrier, status, route, price, and label URL.

Errors: 400 — Invalid month or year 403 — Invalid API key

Inputs: year (required), month (required), response_format. Returns: year, month, total, shipments

envia_trackTrack Envia ShipmentsA
Read-onlyIdempotent

Track one or more shipments by tracking number.

Args: tracking_numbers — Comma-separated tracking numbers (e.g., "2456698904,2456699011") response_format — "markdown" (default) or "json"

Returns: Tracking status, carrier, dates, URLs, and event history for each shipment.

Examples: Single: tracking_numbers="2456698904" Batch: tracking_numbers="2456698904,2456699011,2456699128"

Errors: 1125 — No shipments found for the given tracking numbers 403 — Invalid API key

Inputs: tracking_numbers (required), response_format. Returns: total, shipments

envia_validate_zipcodeValidate Mexican Postal CodeA
Read-onlyIdempotent

Validate a Mexican postal code and return address details (city, state, neighborhoods, coordinates).

Uses the Envia Geocodes API which requires no authentication.

Args: postal_code — 5-digit Mexican postal code (e.g., "06700") country_code — Country code (default: "MX") response_format — "markdown" (default) or "json"

Returns: Validity status, city, state, state codes, neighborhoods, coordinates, and timezone.

Examples: Valid code: postal_code="06700" -> Roma Norte, Ciudad de Mexico Invalid code: postal_code="99999" -> { valid: false }

Errors: 500+ — Geocodes API temporarily unavailable (auto-retries with production fallback)

Inputs: postal_code (required), country_code, response_format. Returns: city, state, valid, timezone, +5 more

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4/5.0

    Scored across 11 tools

    Disambiguation5/5

    Each tool targets a distinct resource+action: quote (read rates), create_label (write/purchase), track, cancel, plus discovery (carriers, services) and geocoding (validate_zipcode, lookup_city). The only near-overlap is validate_zipcode vs lookup_city, but they are differentiated by input (postal code → address vs city name → postal codes). An agent can reliably select the right tool.

    Naming Consistency4/5

    All tools share the envia_ prefix and mostly follow a verb_noun pattern (create_label, validate_zipcode, get_carriers, schedule_pickup, classify_hscode, lookup_city). Minor deviations exist: envia_quote, envia_track, envia_cancel are verb-only, and envia_shipment_history is noun-only. Still highly readable and predictable.

    Tool Count5/5

    11 tools is well within the ideal band and each maps to a real shipping workflow step (quote, buy, track, cancel, pickup, history, discovery, address resolution, customs). No redundant or filler tools.

    Completeness4/5

    Full lifecycle coverage from quoting through label purchase, tracking, cancellation/refund, and pickup, plus supporting lookups (carriers, services, zipcode, city, HS codes). Minor gap: no explicit tool to retrieve a specific shipment/label detail or reprint a label by shipment ID independent of tracking.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI agents to manage global shipping operations, including rate comparison, shipment creation, label purchasing, tracking, pickup scheduling, address validation, billing, and analytics, via natural language.
      MIT