---
title: "Connect Medusa to AI Agents: Automate Promotions and Shipping"
slug: connect-medusa-to-ai-agents-automate-promotions-and-shipping
date: 2026-10-19
author: Sidharth Verma
categories: ["AI & Agents"]
excerpt: "Learn how to connect Medusa to AI agents using Truto's Unified Tools API to autonomously manage promotions, process fulfillments, and handle complex order edits."
tldr: "Skip building custom integration code for Medusa. This guide shows you how to fetch Medusa tools via Truto's /tools endpoint, bind them to AI frameworks like LangChain, and safely automate e-commerce ops."
canonical: https://truto.one/blog/connect-medusa-to-ai-agents-automate-promotions-and-shipping/
---

# Connect Medusa to AI Agents: Automate Promotions and Shipping


You want to connect Medusa to an AI agent so your system can autonomously configure promotions, trigger outbound shipments, reconcile inventory, and modify live orders. Here is exactly how to do it using Truto's `/tools` endpoint and SDK, bypassing the need to build and maintain a custom e-commerce connector from scratch.

Giving a Large Language Model (LLM) read and write access to your Medusa instance requires strict architectural controls. Headless commerce APIs are highly relational and heavily stateful. When an agent attempts to edit an order, it cannot afford to hallucinate payload structures or guess at fulfillment provider IDs. If your team uses ChatGPT, check out our guide on [connecting Medusa to ChatGPT](https://truto.one/connect-medusa-to-chatgpt-sync-orders-inventory-and-customers/), or if you are building on Anthropic's models, read our guide on [connecting Medusa to Claude](https://truto.one/connect-medusa-to-claude-manage-catalogs-and-complex-order-flows/). For developers building custom autonomous workflows, you need a programmatic way to fetch these tools and bind them natively to your agent framework.

This guide breaks down exactly how to fetch AI-ready tools for Medusa, bind them to an LLM using frameworks like LangChain, LangGraph, CrewAI, or the Vercel AI SDK, and execute complex e-commerce operations safely. For a broader look at this design pattern across all your SaaS apps, refer to our research on [architecting AI agents and the SaaS integration bottleneck](https://truto.one/architecting-ai-agents-langgraph-langchain-and-the-saas-integration-bottleneck/).

## Why a Unified Tool Layer Matters for Agent Safety

Before writing your integration layer, you have to decide how your agent will interact with the external world. Direct point-to-point API tools—where you manually write a Python or TypeScript wrapper for every Medusa endpoint—push the entire burden of API quirks into the LLM's prompt context. 

The model has to magically remember that Medusa relies on an intricate combination of Campaigns, Promotions, and Target Rules just to offer a discount. It has to know exactly which relation parameters to expand to see an order's line items. Every one of these vendor-specific API mechanics is a hallucination waiting to happen.

By leveraging Truto's [unified proxy architecture](https://truto.one/best-unified-api-for-llm-function-calling-ai-agent-tools-2026/), your agent interacts with a standardized, structured JSON schema. The tools endpoint (`/integrated-account/:id/tools`) dynamically provides exact [functional descriptions and strict input validation schemas](https://truto.one/best-unified-api-for-llm-function-calling-ai-agent-tools-2026/) for every available Medusa method. This collapses the attack surface for hallucination and guarantees that invalid arguments are caught at the integration boundary before they ever reach your Medusa admin server.

## The Engineering Reality of the Medusa API

Connecting AI agents to e-commerce data sounds straightforward in a local prototype. You wrap a fetch request to `/admin/orders` in an `@tool` decorator and assume the LLM will figure it out. Against Medusa's highly normalized, modular backend, this naive approach collapses immediately. 

Medusa's architecture introduces specific integration challenges that will derail standard LLM function calling if not strictly managed.

### The Order Edit State Machine Trap

Standard REST assumptions dictate that to change an order, you send a `PATCH` request to the order endpoint. Medusa completely rejects this pattern for line items and totals to maintain financial integrity. 

If an agent decides a customer deserves a replacement item, it cannot just update the order record. It must navigate a strict state machine:
1. Create an Order Edit (`create_a_medusa_order_edit`).
2. Add the new item to the edit (`medusa_order_edits_add_items`), which flags it with an `ITEM_ADD` action.
3. Request the edit (`medusa_order_edits_request`).
4. Confirm the edit (`medusa_order_edits_confirm`) to actually mutate the parent order.

If you expose raw HTTP requests to the LLM, it will invariably attempt to `POST` a new item directly to the order object and crash. Exposing these specific lifecycle methods as distinct, strictly typed tools ensures the agent follows the mandatory state progression.

### The Relation Expansion Blindspot

Medusa optimizes database queries by returning extremely shallow JSON objects by default. If your agent calls `list_all_medusa_orders`, it will receive the order IDs, customer references, and basic totals. It will *not* receive the line items, the shipping methods, or the applied promotions.

If a user prompts the agent to "Find order #1004 and tell me what the customer bought," an agent interacting with the raw API will falsely claim the order has no items. 

Your tool definitions must handle Medusa's `expand` query parameters. Truto's query schemas explicitly define these parameters, allowing the LLM to selectively request expanded relations (e.g., `expand=items,shipping_methods`) only when needed, rather than blindly fetching megabytes of relational data on every request.

### Promotion and Campaign Fragmentation

Creating a discount in Medusa is not a single database insert. Medusa separates the marketing wrapper (Campaigns) from the mathematical discount (Promotions) from the qualification logic (Rules). 

To automate a "20% off shirts" sale, the agent must sequence multiple tool calls: creating the promotion, applying a promotion rule for the specific cart value, and then explicitly associating target rules pointing to the `product_category` of "shirts". If an agent lacks the schema constraints for rule attributes, it will invent field names that Medusa's rule engine will reject.

## Handling Medusa Rate Limits Safely

When deploying autonomous agents against live e-commerce infrastructure, rate limits are a critical failure point. A looping agent can easily overwhelm an admin API. 

Truto does not retry, throttle, or apply backoff on rate limit errors. When the upstream Medusa API returns an HTTP 429 Too Many Requests, Truto passes that error directly to the caller. Truto normalizes the upstream rate limit information into [standardized headers](https://truto.one/handling-api-rate-limits-and-webhooks-from-dozens-of-integrations/) (`ratelimit-limit`, `ratelimit-remaining`, `ratelimit-reset`) following the IETF specification. 

The caller—your agent execution loop—is strictly responsible for handling the retry and backoff logic. Do not assume the integration layer will absorb these errors. Your agent's tool execution framework must catch the 429 status, read the `ratelimit-reset` header, and pause execution, preventing infinite failure loops.

## Hero Tools for Medusa Automation

Instead of exposing hundreds of raw endpoints, Truto's proxy architecture surfaces specific, actionable methods. Here are the highest-leverage tools to bind to your AI agent for e-commerce automation.

### create_a_medusa_promotion
**Description:** Create a new promotion defining the discount type, value, and basic application logic.
**Contextual usage:** Use this tool as the first step when orchestrating a new sale, discount code, or automatic cart deduction. The agent must specify if the promotion is a standard discount or a buy-get offer.
> "Set up a new Summer Flash Sale promotion offering 20% off all standard retail orders."

### medusa_promotions_batch_rules
**Description:** Manage the rules of a promotion to create, update, or delete them.
**Contextual usage:** This tool defines *when* the promotion applies. Agents use this to attach currency restrictions, minimum cart values, or specific customer group qualifications to the promotion created in the previous step.
> "Restrict the Summer Flash Sale promotion so it only applies to carts over $100."

### create_a_medusa_fulfillment
**Description:** Create a fulfillment for an order, return, exchange, or claim.
**Contextual usage:** This initiates the logistics process. The agent will select specific line items from an existing order and assign them to a fulfillment provider, generating the necessary staging data for warehouse operations.
> "Create a fulfillment for the two pending items on order #ORD-9932 using our default warehouse provider."

### medusa_orders_create_shipment
**Description:** Create a shipment for an order's fulfillment, officially marking it as shipped and providing tracking.
**Contextual usage:** Once a fulfillment is packed, this tool executes the shipment step. The agent must provide the fulfillment ID and the tracking numbers generated by the carrier.
> "Mark fulfillment #FUL-882 as shipped and attach tracking number 1Z9999999999999999."

### create_a_medusa_order_edit
**Description:** Create an order edit to begin modifying a finalized order.
**Contextual usage:** Medusa orders are immutable. To change one, the agent must first call this tool to spawn an active edit session. The agent will then use subsequent edit tools to modify items before confirming.
> "Open an order edit for order #ORD-4410 so we can swap out the backordered shirt."

### medusa_order_edits_confirm
**Description:** Confirm an order edit request and apply the changes to the parent order.
**Contextual usage:** This is the commit phase of the order edit state machine. After the agent has added or removed items from the edit, calling this tool recalculates the totals and permanently alters the order state.
> "Confirm the pending order edit on #ORD-4410 and finalize the item changes."

To see the complete list of available operations, view the full [Medusa integration tool inventory](https://truto.one/integrations/detail/medusa).

## Workflows in Action

Exposing tools to an LLM is only useful if the agent can sequence them to solve actual business problems. Here is how an AI agent uses the Medusa toolset to handle complex, multi-step e-commerce workflows.

### Scenario 1: Automated Flash Sale Execution

A merchandising manager needs to immediately spin up a targeted promotion based on excess inventory levels. They instruct the agent via a Slack bot or internal dashboard.

> "We have too much inventory in the 'Winter Apparel' category. Create a 30% off promotion called 'Winter Clearance' that applies automatically at checkout, but only for customers in the 'VIP' customer group."

**Agent Execution Sequence:**
1. The agent calls `create_a_medusa_promotion` with `is_automatic: true`, `type: "standard"`, and setting the discount value to 30%.
2. The agent calls `medusa_promotions_batch_rules` to attach a rule to the promotion restricting it to the specific `customer_group_id` for VIPs.
3. The agent calls `medusa_promotions_batch_target_rules` to ensure the 30% discount mathematically applies only to line items where the `product_category` matches Winter Apparel.

**Result:** The agent autonomously orchestrates the relational complexity of Medusa's promotion engine. The manager receives a confirmation that the automatic discount is live and strictly bounded to the requested audience and catalog segment.

### Scenario 2: Autonomous Shipping and Tracking Updates

A warehouse automation script drops a CSV of dispatched tracking numbers into an S3 bucket, triggering an AI agent to reconcile the store backend.

> "Process the dispatch logs for order #ORD-7741. The items have been packed and shipped via FedEx. Tracking number is 771234567890. Update the customer's order."

**Agent Execution Sequence:**
1. The agent calls `get_single_medusa_order_by_id` (passing `expand=items,fulfillments`) to audit the current state of the order.
2. Noting no fulfillment exists, the agent calls `create_a_medusa_fulfillment` for the line items on the order.
3. The agent immediately calls `medusa_orders_create_shipment`, passing the newly generated fulfillment ID, the carrier name, and the tracking number string.

**Result:** The customer automatically receives their shipment notification email from Medusa, the admin dashboard reflects the updated logistics state, and the agent moves on to the next dispatch record without human intervention.

## Building Multi-Step Workflows

To build these autonomous systems, you need an orchestration layer that handles the back-and-forth between the LLM and the Truto API. This architectural pattern works seamlessly with standard frameworks like LangChain, LangGraph, or the Vercel AI SDK.

Below is a conceptual architecture using TypeScript and LangChain to demonstrate fetching Medusa tools, binding them to an LLM, and handling the strict rate limit requirements discussed earlier.

```mermaid
sequenceDiagram
    participant App as Agent Execution Loop
    participant Truto as Truto Tool Manager
    participant Medusa as Upstream Medusa API
    
    App->>Truto: GET /integrated-account/{id}/tools
    Truto-->>App: Returns JSON Schemas (Proxy APIs)
    App->>App: llm.bindTools(schemas)
    
    Note over App: LLM determines action<br>based on user prompt
    
    App->>Truto: execute(tool: "create_a_medusa_fulfillment", args)
    Truto->>Medusa: POST /admin/orders/{id}/fulfillments
    
    alt Rate Limit Exceeded
        Medusa-->>Truto: 429 Too Many Requests
        Truto-->>App: 429 Error with ratelimit-reset headers
        Note over App: Agent backoff logic<br>pauses execution
        App->>Truto: Retry execution after reset
        Truto->>Medusa: POST /admin/orders/{id}/fulfillments
    end
    
    Medusa-->>Truto: 200 OK
    Truto-->>App: Standardized JSON Result
```

Here is how you implement this loop in your application code. Notice how the agent framework natively understands the JSON schema returned by Truto, and how the execution loop actively catches the `429` status code.

```typescript
import { ChatOpenAI } from "@langchain/openai";
import { AgentExecutor, createOpenAIFunctionsAgent } from "langchain/agents";
import { TrutoToolManager } from "truto-langchainjs-toolset";

async function runMedusaAgent(prompt: string, accountId: string) {
  // Initialize the LLM
  const llm = new ChatOpenAI({
    modelName: "gpt-4o",
    temperature: 0,
  });

  // Fetch dynamically generated tools for the specific Medusa account
  const toolManager = new TrutoToolManager({
    apiKey: process.env.TRUTO_API_KEY,
    integratedAccountId: accountId,
  });

  const tools = await toolManager.getTools();

  // Bind the strict JSON schemas to the model
  const llmWithTools = llm.bindTools(tools);

  // Create the agent execution loop
  const agent = await createOpenAIFunctionsAgent({
    llm: llmWithTools,
    tools,
    prompt: customMedusaPromptTemplate,
  });

  const executor = new AgentExecutor({
    agent,
    tools,
    maxIterations: 10,
  });

  try {
    console.log(`Executing Medusa workflow: ${prompt}`);
    const result = await executor.invoke({ input: prompt });
    console.log("Workflow complete:", result.output);
    
  } catch (error) {
    // Critical: Truto passes 429s directly. The agent must handle the backoff.
    if (error.status === 429) {
      const resetTime = error.headers['ratelimit-reset'];
      console.warn(`Medusa rate limit hit. Agent must back off until ${resetTime}.`);
      // Implement your custom DLQ, sleep, or retry logic here.
    } else {
      console.error("Agent execution failed:", error);
    }
  }
}
```

This architecture completely insulates your engineering team from Medusa API maintenance. When Medusa updates their admin endpoints or changes a query parameter requirement, Truto updates the integration model on the backend. The next time `getTools()` runs, your LLM automatically receives the updated JSON schema and adjusts its behavior. Zero code deploys required on your end.

## Safely Scaling Autonomous Commerce

Integrating AI agents with complex e-commerce backends like Medusa exposes the harsh reality of SaaS API orchestration. Relying on raw, handwritten REST wrappers results in brittle agents that hallucinate state machine transitions, fail on un-expanded relations, and crash on unhandled rate limits.

By leveraging a unified tool layer, you abstract the heavy lifting of authentication, pagination, and schema mapping. Your agent interacts with a deterministic, strictly typed proxy, allowing you to focus your engineering cycles on improving the LLM's reasoning and business logic, rather than chasing down obscure e-commerce API quirks.

> Stop handwriting e-commerce integrations for your AI agents. Let Truto handle the integration layer so you can focus on building intelligent autonomous workflows.
>
> [Talk to us](https://truto.one/book-a-demo/)
