
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.
pip install openai-agents. The current release on PyPI is 0.26.0.OPENAI_API_KEY.OAUTH2. and lasts 180 days.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.
Use both. The SDK can give an agent tools from an MCP server and from your own Python functions in the same run.
| Approach | What you write | Best for |
|---|---|---|
MCPServerStreamableHttp to https://app.ship.com/mcp | A few lines of connection config | Rating 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 tool | Your 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.
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.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())
There are 3 layers, and only the first one depends on the model behaving.
require_approval on buy_label matters.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.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.
| Tool | Required arguments | Fields your agent will use |
|---|---|---|
get_rates | order_id (pass weight_oz too) | package_id, rates[] |
buy_label preview | order_id, rate_id, package_id, method, service_level | price, total_charge, balance_after, message |
buy_label confirm | Same, plus confirm: true and max_cost | label_url, tracking_number, tracking_url |
track_order | order_id | status, 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.
update_order_address. Hand that one to a human.Retry-After: 60. Every call counts, including tools/list, which is why cache_tools_list=True helps.success, as quick_quote does.More patterns are in our post on error handling for shipping agents.
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.
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.
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.
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.
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.
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.
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.
MCPServerStreamableHttp, headers, tool_filter, create_static_tool_filter, require_approval forms, HostedMCPTool (accessed November 2026)result.interruptions, state.approve, state.reject, resuming a run (accessed November 2026)OPENAI_API_KEY (accessed November 2026)tool is an alias for function_tool (accessed November 2026)max_cost refusal, rate limits, void rules (accessed November 2026)success field (accessed November 2026)