Blog/Category
Shipping Tips & Tricks

Error Handling for Shipping Agents: Addresses, Rates, Retries and Voids

November 25, 2026
Founder and CEO
Error Handling for Shipping Agents: Addresses, Rates, Retries and Voids

Updated November 2026. Facts verified against vendor and carrier documentation; see references at the end.

A shipping agent needs to sort every error into one of 3 buckets: retry it, fix the input and try again, or stop and ask a human. Rate limits get a timed retry, and bad addresses and expired rates get fixed and re-run. Spending caps, billing problems (including card cooldowns) and auth failures go to a person. Below are the real error strings from the Ship.com MCP server and REST API, what causes each one and what your agent should do.

Why does error handling matter more for shipping agents?

Because a label costs money. If a read call fails and your agent retries it, you lose a second. If a label purchase half-fails and your agent retries without thinking, you can pay for 2 labels. On Ship.com, buy_label buys a real USPS or UPS label from your postage balance, so error handling is part of your spend control.

Two rules cover most of the risk. Every purchase goes through a preview first (confirm defaults to false), and every confirmed purchase carries a max_cost cap. We cover that pattern in depth in how to let an AI agent buy shipping labels safely. Here we cover what to do when a step fails.

How do Ship.com errors come back?

REST and MCP report errors differently.

  • REST (https://app.ship.com/public/) returns HTTP 200 for every call, success or failure. Check the success boolean in the body. When it is false, error (sometimes with message) says why.
  • MCP (https://app.ship.com/mcp) uses HTTP status codes for the transport layer: 401 for auth, 403 for a blocked browser origin, 429 for rate limits. Tool failures come back as HTTP 200 with "isError": true and the reason in the text content.

A REST check is short:

const data = await res.json();
// HTTP 200 doesn't mean it worked. Check success.
if (!data.success) {
  throw new Error(`${data.error}${data.message ? ": " + data.message : ""}`);
}

An MCP tool error looks like this:

{"jsonrpc":"2.0","id":7,"result":{"content":[{"type":"text","text":"Order 48213 was not found in this account."}],"isError":true}}

In our tutorials, label purchases, voids, tracking and address checks go through MCP tools (buy_label, cancel_shipping_label, track_order, validate_address). REST has no void, tracking or address-validation endpoint, so most of the errors below are MCP errors.

Which shipping errors should your agent retry, fix or escalate?

ErrorCauseWhat your agent should do
HTTP 429 rate_limited, Retry-After: 60Over 60 requests per minute on this token. Every authenticated request counts, including initialize and tools/listWait the Retry-After seconds, then retry. The window resets at the start of each minute (UTC)
Refusing to buy: rate is $<price> which exceeds max_cost $<max>. Nothing was purchased.The live rate is above your capDon't retry with a higher cap on its own. Show the new price to a human and let them decide
rate_id is invalid or has expired. Call get_rates again and use a fresh rate_id.The rate token is staleCall get_rates again, re-check the price against your cap, then preview and buy
Label purchase failed — Unauthorized"The package_id is from a different get_rates response than the rate_id."Take package_id and rate_id from the same get_rates response
Label purchase failed — CooldownNeededRepeated card declines. The docs say "Wait 60 seconds, then fix the card before retrying."Stop. Alert a human to fix the card. Retrying before the card is fixed won't help
Label purchase failed — AutoRechargeOff, NeedPayment, ChargeFailed, MissingBillingBilling or postage balance problemStop. Alert a human to fix billing. Retrying won't help
Label purchase failed — Limit reachedPlan limit hitStop and escalate. Check the plan's monthly shipment allowance
Rating failed: the destination address failed validation. Correct it with update_order_address before buying a label.Bad ship-to addressRun validate_address, fix the order with update_order_address, rate again. If you can't fix it with confidence, ask the customer or a human
Rating failed: the account's ship-from address is missing or invalid. Fix it in Settings before rating or buying labels.Account setup problem, not the orderStop. A human fixes the ship-from address in Settings
zip is required. / weight_oz must be greater than 0.Missing or bad input to quote_shippingFix the input. Send ZIPs as strings and weight in ounces
Order <id> was not found in this account.Wrong order ID, or the wrong account's tokenDon't retry. Look the order up with list_orders
The tool 'buy_label' is not available on this server. Call tools/list to see the available tools.The client's tool list is stale or filtered. Both connection types include all 40 tools, including buy_labelCall tools/list again and check any tool filter in your client
HTTP 401 missing_bearer_token, invalid_token, expired_tokenHeader empty, whole header pasted into the value, or token expired or replacedStop and alert. Fix the key, then restart
HTTP 403 forbidden_originThe request came from a browser on another websiteMove the call to server-side code
REST "Invalid or Expired Credentials"Bad or expired REST tokenStop and alert. Don't loop on it
Plan messages, such as "Your current Ship.com plan does not include carrier pickup scheduling."The tool needs a plan feature you don't haveStop and tell a human. Don't retry

The long dash inside the Label purchase failed strings is part of the server's message. Match on the code after it.

What does a retry-safe purchase look like in code?

Here is one TypeScript module for Node 18+ that calls the Ship.com MCP server over Streamable HTTP. It handles 429s, treats auth errors as fatal, previews before buying and buys with a cap. Keep the connection key in an environment variable or secret store on your server, never in browser code.

// ship.ts: server-side only. SHIPCOM_TOKEN is your Ship.com connection key.
const MCP_URL = "https://app.ship.com/mcp";
const TOKEN = process.env.SHIPCOM_TOKEN!;
let nextId = 1;
const sleep = (s: number) => new Promise((r) => setTimeout(r, s * 1000));

export class ToolError extends Error {}

export async function callTool(name: string, args: object, attempt = 1): Promise<any> {
  const res = await fetch(MCP_URL, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${TOKEN}`,
      "Content-Type": "application/json",
      Accept: "application/json, text/event-stream",
    },
    body: JSON.stringify({
      jsonrpc: "2.0", id: nextId++, method: "tools/call",
      params: { name, arguments: args },
    }),
  });

  if (res.status === 429 && attempt <= 3) {
    await sleep(Number(res.headers.get("Retry-After") ?? 60));
    return callTool(name, args, attempt + 1);
  }
  if (res.status === 401 || res.status === 403) {
    const body = await res.json();
    throw new Error(`Fatal auth error, do not retry: ${body.error}`);
  }
  const msg = await res.json();
  if (msg.error) throw new Error(`JSON-RPC ${msg.error.code}: ${msg.error.message}`);
  if (msg.result.isError) throw new ToolError(msg.result.content[0].text);
  return msg.result.structuredContent;
}

export async function buyCheapest(orderId: number, weightOz: number, maxCost: number) {
  for (let tries = 0; tries < 2; tries++) {
    const quote = await callTool("get_rates", { order_id: orderId, weight_oz: weightOz });
    const best = quote.rates.reduce((a: any, b: any) => (b.rate < a.rate ? b : a));
    const label = {
      order_id: orderId, rate_id: best.rate_id, package_id: quote.package_id,
      method: best.method, service_level: best.service_level,
    };

    // 1. Preview. confirm defaults to false, so nothing is bought here.
    const preview = await callTool("buy_label", label);
    if (preview.total_charge > maxCost) {
      return { status: "needs_human", preview }; // show the price, let a person decide
    }

    // 2. Buy with a cap. The server refuses if the rate is above max_cost.
    try {
      return await callTool("buy_label", { ...label, confirm: true, max_cost: maxCost });
    } catch (e) {
      const text = String((e as Error).message);
      if (text.includes("rate_id is invalid or has expired")) continue; // re-rate once
      throw e; // max_cost refusal, billing (incl. CooldownNeeded), limits: escalate
    }
  }
  throw new Error("Could not buy a label after re-rating; escalate to a human.");
}

2 notes on that code. max_cost caps postage only, while the preview's total_charge can include insurance and the pay-as-you-go fee, so the check above is the stricter of the 2. And a clean preview can still fail on confirm. The docs say "the preview doesn't check package_id, plan limits, billing, ship date, address or account standing."

How do you avoid duplicate orders and duplicate labels?

Retries are only safe when the thing you retry is idempotent. Here is what Ship.com gives you.

  • Pass external_order_id on create_order or bulk_create_orders. A retry or re-import "returns the existing order instead of creating a duplicate." A duplicate comes back with created: false, skipped_existing: true.
  • Simultaneous calls with the same ID can still create duplicates. Serialize work per order with a queue or a lock.
  • The ID is stored in the order notes as [ext:YOUR-ID]. If you replace the notes with update_order, duplicate protection is gone for that order.
  • If an order already has a label, buy_label returns it without charging. So retrying a purchase on the same order after a timeout won't double-buy.
  • bulk_create_orders isn't all-or-nothing. A wrong type (such as "two" for a quantity) stops the whole call after earlier entries were already saved. Re-run with the same external_order_id values and the saved ones come back as skipped.
  • Email tools have no duplicate protection. "Confirming twice sends two emails." Never auto-retry send_customer_email.

Batches have their own rules: one batch at a time, and an order that already has a label isn't bought twice. See batch label purchase with an AI agent.

How should an agent handle bad addresses?

Validate before you rate. validate_address takes street, city, state (2 letters) and zip, plus an optional street2, and returns is_valid and a standardized address. It is US only, it saves nothing, and it is an MCP tool (REST has no address endpoint).

Read is_valid: false carefully. The docs say it "means either that no match exists or that the validation service was briefly unavailable." So retry once after a short wait before you bother the customer. Also, "Street lines are never corrected," so the agent shouldn't assume the street came back fixed.

Some shipments can't go through MCP at all. Customs shipments (non-US, APO/FPO/DPO and US territories) "can't be rated or bought through MCP yet." Route those to a human or the web app.

How do voids and refunds work when an agent buys the wrong label?

Use cancel_shipping_label with the order_id. Like a purchase, it previews first and only voids with confirm: true. The rules:

  • You can void within 29 days of the ship date. Past that, the tool returns an error instead of a preview.
  • The label must not have been scanned by the carrier. No refund once it is scanned.
  • The refund goes to your postage balance, not your card, "once the carrier accepts the void, typically within about 14 days."
  • Return labels aren't handled by this tool. cancel_order also voids the label if the order hasn't shipped.

Two more date rules can trip a purchase. A ship_date more than 24 hours in the past is refused, and for USPS the mailing date is kept between today and 7 days ahead (US Eastern time).

What about tracking that looks stale?

track_order returns status, tracking number, ship, in-transit and delivered dates, and any exception. It "doesn't query the carrier live, so calling it again won't refresh anything." Don't let an agent poll it in a tight loop and burn your 60 requests a minute. If last_tracking_update is null, treat freshness as unknown. For the full MCP-vs-REST picture, see our developer's guide to shipping for AI agents.

Frequently asked questions

How should an AI agent handle a 429 from a shipping API?

Read the Retry-After header and wait that long before retrying. On Ship.com's MCP server the limit is 60 requests per minute per token, the window resets at the start of each minute (UTC), and a 429 comes with Retry-After: 60. Every authenticated request counts, including initialize and tools/list, so cache the tool list instead of fetching it each time.

Is it safe to retry a failed label purchase?

On Ship.com it usually is, as long as you retry on the same order. If an order already has a label, buy_label returns that label without charging again. Don't retry a max_cost refusal or a billing failure automatically. Those need a human. Re-rate first when the error says the rate_id is invalid or expired.

Why does the Ship.com REST API return 200 when a call fails?

By design. The REST docs say every response is JSON and returns HTTP 200 whether the call succeeded or failed. Check the success boolean in the body. If it is false, error and sometimes message explain why. Code that only checks the HTTP status will treat failures as successes, so always test success before using the result.

Can I void a shipping label an agent bought by mistake?

Yes, within limits. Ship.com's cancel_shipping_label voids a label within 29 days of the ship date, as long as the carrier hasn't scanned it. It previews first and voids only when you confirm. The refund goes back to your postage balance, not your card, typically within about 14 days after the carrier accepts the void.

Build with the Ship.com API

Ship.com gives you up to 89% off USPS and up to 87% off UPS, with a preview mode and a spending cap your agent can set on every purchase. Sign up, then get your key in app.ship.com under Settings > API Integration. Setup for each editor is in our MCP setup guide for Claude Code, Cursor and VS Code, and plans are on our pricing page.

Get your API key

Create a Ship.com account

References

Joe DiSorbo
About the author
Joe DiSorbo
Founder and CEO

Joe DiSorbo is the founder and CEO of Ship.com, the shipping platform that gives more than 10,000 business customers discounted USPS and UPS rates and simplifies logistics for ecommerce brands and software platforms. Before Ship.com, he founded and led Webgistix, an ecommerce technology and global fulfillment company that grew internationally before Rakuten acquired it in 2013. His background spans global operations, software development, finance and logistics, with experience across the United States and Asia. Joe holds undergraduate degrees in Economics and Geography, masters degrees in Finance and International Management, and is a graduate of Harvard Business School (OPM 41).

Shipping software built for online sellers

Ship.com saves you time and money, giving you more freedom to live your life.

  • No credit card required.
  • Up to 89% off USPS and up to 87% off UPS.
  • Connects with major e-commerce platforms.
  • Free home pickup. Skip the trip to the post office.
Try for free
UPS
UP TO 87% OFF
Daily Rates*
USPS
UP TO 89% OFF
Retail Prices*
Today's orders
Order #1042USPS Ground AdvantageReady
Order #1043UPS Ground SaverReady
Order #1044USPS Priority MailReady
★★★★★Trusted by 10,000+ business customers

More on this topic

See all