Create internal AI agents for Medusa-based operational and commerce workflows.
---
name: creating-agents-in-medusa
description: Use when building an internal admin-facing AI agent in a Medusa project. These agents are operated by merchants and store operators — not customers. Covers data models, module service, agent runtime (tools, system prompt, streamText), streaming API routes (NDJSON), and admin UI chat extensions. Load for any internal agent type: store operations assistant, product audit, cohort analysis, customer service tooling for support staff, etc. Do NOT use for customer-facing agents (storefront chatbots, buyer-side assistants).
---
# Creating Agents in Medusa
This skill covers the full stack for adding an **internal, admin-facing** AI agent to a Medusa project. These agents are used by merchants and store operators through the Medusa admin dashboard — not by customers on a storefront. For customer-facing agents (e.g. a storefront chatbot), a different architecture is needed: public API routes, no MedusaExec, and storefront auth.
## Constraints
- **Internal use only** — this architecture is for admin users (merchants, operators, support staff), not customers. Routes live under `src/api/admin/`, the UI lives in the Medusa admin dashboard, and access is gated by admin authentication throughout.
- **Authentication is non-negotiable** — MedusaExec runs arbitrary TypeScript with full database access. All agent routes must use `AuthenticatedMedusaRequest` and live under `src/api/admin/`. An unauthenticated endpoint is a remote code execution vulnerability.
- **Use MedusaExec, not custom tools** — for any data operation, the agent writes TypeScript and executes it via MedusaExec. Only build a custom tool for capabilities that cannot be expressed as executable TypeScript (e.g. calling an external API with a secret key).
- **One shared module, multiple agents** — `AgentSession` and `AgentMessage` are shared infrastructure. Use `agent_type` to distinguish sessions per agent. Never create separate models per agent.
- **Pass `MedusaContainer` via `experimental_context`** — never import services directly in tool files; that causes circular dependencies.
- **Stream format is NDJSON** — `Content-Type: application/x-ndjson`, one JSON object per line followed by `\n`.
- **Run migrations** after adding or changing models (`npx medusa db:generate agent && npx medusa db:migrate`).
- **Tool descriptions live in config**, not inline in `tool()` — the config object overrides them at runtime.
## CRITICAL: Load Reference Files When Needed
**⚠️ The quick reference below is NOT sufficient for implementation.** Load the relevant reference file before writing any code.
| Task | Load this file |