Blog/Category
Shipping Tips & Tricks

Add Shipping Tools to the OpenAI Agents SDK (Python)

November 27, 2026
Founder and CEO
Add Shipping Tools to the OpenAI Agents SDK (Python)

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

To add shipping tools to the OpenAI Agents SDK in Python, connect the Ship.com MCP server with MCPServerStreamableHttp and your connection key as a Bearer header, then pass it to your agent with mcp_servers=[...]. Your agent can then rate orders, buy labels and track them. Put require_approval on buy_label, preview the price first, and cap the spend with max_cost. Your own @function_tool functions can sit next to the server for anything else.

What do you need before you start?

  • Python and the SDK: pip install openai-agents. The current release on PyPI is 0.26.0.
  • An OpenAI key in OPENAI_API_KEY.
  • A Ship.com account and your connection key. Sign up, then go to app.ship.com > Settings > API Integration. The key starts with OAUTH2. and lasts 180 days.
  • The key in an environment variable, SHIPCOM_TOKEN. Keep it in server-side code only. Anyone who has it can act on your account and buy labels.

You don't need your own USPS account or eVS. Ship.com buys the postage from your Ship.com balance.

Should you use MCP or write function tools?

Use both. The SDK can give an agent tools from an MCP server and from your own Python functions in the same run.

ApproachWhat you writeBest for
MCPServerStreamableHttp to https://app.ship.com/mcpA few lines of connection configRating an order, buying labels, tracking, address checks. You get all 40 tools.
@function_tool (or the @tool alias)A Python function the SDK turns into a toolYour own logic, or a quick REST call like a price check with no order

One rule for this tutorial: labels are bought through the MCP server's buy_label tool. It has a preview mode, a hard cost cap and a no-double-charge rule built in, so it's the safer way to spend money from an agent.

A note on decorators. The SDK docs now show @tool, which the source code defines as an alias for function_tool. from agents import function_tool still works, and it's what most readers will recognize, so we use it below.

How do you connect Ship.com to the OpenAI Agents SDK?

The Ship.com server speaks MCP Streamable HTTP and is stateless, so the SDK's MCPServerStreamableHttp class connects to it directly. Put the token in the headers, never in the URL. The SDK docs say the same thing: keep access tokens in authorization fields or headers.

Two options keep the agent on a short leash:

  • tool_filter with create_static_tool_filter(allowed_tool_names=[...]) exposes only the tools you list. Our example allows 5 of the 40.
  • require_approval={"always": {"tool_names": ["buy_label"]}} pauses the run every time the agent calls buy_label, so your code decides.

What does the full example look like?

This script lets an agent ship one existing Ship.com order the cheapest way. It previews the label, shows a human the exact price and asks before it buys. It also adds one function tool that calls the REST quote endpoint for quick price checks.

import asyncio
import json
import os

import requests
from agents import Agent, Runner, function_tool
from agents.mcp import MCPServerStreamableHttp, create_static_tool_filter

SHIPCOM_TOKEN = os.environ["SHIPCOM_TOKEN"]  # server-side only, never in browser code
MAX_COST = 15.00  # your hard ceiling in dollars (postage only)

INSTRUCTIONS = f"""You help ship Ship.com orders.
To buy a label: call get_rates for the order, pick the rate, then call buy_label
with confirm false to preview it. Then call buy_label again with confirm true and
max_cost set to the exact price from the preview. Never go above {MAX_COST} dollars.
Use quick_quote only for price checks. Its rates can't be bought.
Weights are in ounces. ZIP codes are strings."""


@function_tool
def quick_quote(from_zip: str, to_zip: str, weight: float) -> str:
    """Price-check a package between two US ZIP codes. Read-only."""
    res = requests.post(
        "https://app.ship.com/public/quote",
        headers={
            "Authorization": f"Bearer {SHIPCOM_TOKEN}",
            "Content-Type": "application/json",
        },
        # The REST docs don't state weight units. The MCP docs use ounces. Verify.
        json={"fromZip": from_zip, "toZip": to_zip, "weight": weight},
        timeout=30,
    )
    data = res.json()
    if not data.get("success"):  # REST returns HTTP 200 even when it fails
        return f"Quote failed: {data.get('error')} {data.get('message', '')}"
    rows = [
        {k: p[k] for k in ("serviceLevel", "rate", "retailRate", "deliveryDate")}
        for p in data["result"]["prices"]
    ]
    return json.dumps(rows)


async def main() -> None:
    async with MCPServerStreamableHttp(
        name="Ship.com",
        params={
            "url": "https://app.ship.com/mcp",
            "headers": {"Authorization": f"Bearer {SHIPCOM_TOKEN}"},
            "timeout": 30,
        },
        cache_tools_list=True,
        max_retry_attempts=3,
        tool_filter=create_static_tool_filter(
            allowed_tool_names=["get_order", "get_rates", "buy_label",
                                "track_order", "validate_address"]
        ),
        require_approval={"always": {"tool_names": ["buy_label"]}},
    ) as shipcom:
        agent = Agent(
            name="Shipping assistant",
            instructions=INSTRUCTIONS,
            tools=[quick_quote],
            mcp_servers=[shipcom],
        )
        result = await Runner.run(
            agent, "Ship order 48210551 the cheapest way and give me the tracking link."
        )

        # A resumed run can pause again, so loop until nothing is pending.
        while result.interruptions:
            state = result.to_state()
            for item in result.interruptions:
                args = item.arguments
                if isinstance(args, str):
                    args = json.loads(args or "{}")
                if not args.get("confirm"):
                    state.approve(item)  # a preview spends nothing
                    continue
                cap = args.get("max_cost")
                if cap is None or cap > MAX_COST:
                    state.reject(item)  # no cap, or over our ceiling
                    continue
                answer = input(
                    f"Buy {args.get('service_level')} label for order "
                    f"{args.get('order_id')} at ${cap:.2f}? [y/N] "
                )
                if answer.strip().lower() == "y":
                    state.approve(item)
                else:
                    state.reject(item)
            result = await Runner.run(agent, state)

        print(result.final_output)


asyncio.run(main())

How does the approval step protect you?

There are 3 layers, and only the first one depends on the model behaving.

  1. The prompt asks for a preview first. The server doesn't force one, which is why require_approval on buy_label matters.
  2. Your code sees every buy_label call before it runs. Previews (confirm false) go through, because they buy nothing. A real purchase without max_cost, or above your ceiling, is rejected. Anything else goes to a human, who sees the service, the order and the exact price.
  3. The server enforces max_cost. If the rate is higher than the cap, the purchase is refused with "Refusing to buy: rate is $<price> which exceeds max_cost $<max>. Nothing was purchased."

max_cost covers postage only. Insurance and fees sit outside the cap. And if an order already has a label, buy_label returns that label without charging again, so a retried purchase doesn't buy twice. For the full pattern, see our guide on how to let an AI agent buy shipping labels safely.

What do the Ship.com tools return?

ToolRequired argumentsFields your agent will use
get_ratesorder_id (pass weight_oz too)package_id, rates[]
buy_label previeworder_id, rate_id, package_id, method, service_levelprice, total_charge, balance_after, message
buy_label confirmSame, plus confirm: true and max_costlabel_url, tracking_number, tracking_url
track_orderorder_idstatus, tracking_url, delivered_date

Pass the weight to get_rates. The docs say the weight saved on the order isn't used for pricing. Also keep the rate_id and package_id from the same get_rates response. Mixing them fails with an Unauthorized error.

A clean preview can still fail on confirm. The preview doesn't check the package, plan limits, billing, ship date or address. Only the confirm result tells you a label was bought.

What should your agent do when something fails?

  • An expired rate returns "rate_id is invalid or has expired. Call get_rates again and use a fresh rate_id." Let the agent re-rate.
  • A bad destination returns a message telling you to correct it with update_order_address. Hand that one to a human.
  • The MCP endpoint allows 60 requests per minute per token. Over that you get HTTP 429 with Retry-After: 60. Every call counts, including tools/list, which is why cache_tools_list=True helps.
  • A REST call that fails still returns HTTP 200. Check success, as quick_quote does.

More patterns are in our post on error handling for shipping agents.

How do you undo a label the agent bought by mistake?

Use the cancel_shipping_label MCP tool. It voids a label within 29 days of the ship date, and the refund goes back to your postage balance (not your card) once the carrier accepts the void, typically within about 14 days. There's no refund if the carrier already scanned the package. It takes confirm too, so preview first. We left it out of the allow-list above so the agent can't void labels on its own. Add it if you want a human-approved undo.

Can you use HostedMCPTool instead?

The SDK also has HostedMCPTool, where OpenAI's side calls the MCP server for you. We don't cover it here. This tutorial uses MCPServerStreamableHttp because it connects from your own process, and the approval loop above is written for it.

Frequently asked questions

How do I connect an MCP server with a Bearer token in the OpenAI Agents SDK?

Use MCPServerStreamableHttp from agents.mcp. Pass params={"url": "https://app.ship.com/mcp", "headers": {"Authorization": f"Bearer {token}"}}, open it with async with, and add it to your agent with mcp_servers=[server]. Read the token from an environment variable, and keep it out of the URL and out of any browser code.

How do I require human approval before an agent buys a shipping label?

Set require_approval={"always": {"tool_names": ["buy_label"]}} on the MCP server. When the agent calls the tool, the run pauses and the call shows up in result.interruptions. Call state.approve(item) or state.reject(item), then resume with Runner.run(agent, state). Loop, because a resumed run can pause again.

Should I use @tool or @function_tool?

Either one works. The OpenAI Agents SDK source defines tool as an alias for function_tool, and the current docs show @tool. @function_tool is still exported from the package root and is what most existing tutorials use. Pick one and stay consistent across your codebase so your team isn't reading two styles for the same thing.

Can my agent buy labels with Ship.com OAuth sign-in?

Yes. Both connection types get all 40 tools, including buy_label and trigger_batch_purchase. From the OpenAI Agents SDK, the simplest path is your connection key as a Bearer header, which skips the sign-in flow. Find the key under Settings, API Integration in the Ship.com app.

New to shipping agents? Start with the developer's guide to MCP and API for AI agents, or set up the same server in your IDE with our Claude Code and Cursor guide. The MCP reference is at ship.com/api/mcp.

Build with the Ship.com API

Give your agent USPS and UPS labels at up to 89% off USPS and up to 87% off UPS. Sign up, grab your key from Settings, and make your first call. The REST reference is at ship.com/api/overview, and API questions go to api-support@ship.com.

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