Raw
1 import { Note, Table, CodeTab, CodeTabs } from "docs-ui"
2
3 export const metadata = {
4 title: `Cloud CLI for AI Agents`,
5 }
6
7 # {metadata.title}
8
9 This guide is written for AI agents that manage Cloud resources through the Cloud CLI. It covers best practices, working principles, and common workflows for using the CLI in an agentic development context.
10
11 If you're a human user, copy the following instructions to your agent to get started:
12
13 ```markdown title="Prompt"
14 Fetch https://docs.medusajs.com/cloud/cli/agents and set up the Medusa Cloud CLI.
15 ```
16
17 You can also install the instructions in this document as a skill in your agent:
18
19 <CodeTabs group="agent-skills">
20 <CodeTab label="Claude Code" value="claude-code">
21
22 ```bash
23 claude # start claude code
24 /plugin marketplace add medusajs/medusa-agent-skills
25 /plugin install medusa-cloud@medusa
26 ```
27
28 </CodeTab>
29 <CodeTab label="Other AI Agents" value="skills-command">
30
31 ```bash
32 npx skills add medusajs/medusa-agent-skills
33 # choose the following skill:
34 # - using-medusa-cloud
35 ```
36
37 </CodeTab>
38 </CodeTabs>
39
40 ## Working Principles
41
42 AI agents should follow these defaults whenever they operate the CLI:
43
44 - **Always pass `--json` when parsing output.** The plaintext output is for human readers and may change without warning; machine-readable JSON is stable and structured.
45 - **Confirm context before acting.** Run [`mcloud whoami`](../commands/whoami/page.mdx) before any state change so you know which organization, project, and environment you'll affect.
46 - **Set context once, not per command.** Use [`mcloud use`](../commands/use/page.mdx) to persist organization, project, and environment, then drop the flags from subsequent commands.
47 - **Read before you write.** Run a `get` or `list` before any `delete`, `redeploy`, or `trigger-build` to verify you're targeting the right resource.
48 - **Use `--yes` for irreversible operations.** [`mcloud projects delete`](../commands/projects/page.mdx#projects-delete), [`mcloud environments delete`](../commands/environments/page.mdx#environments-delete), and [`mcloud variables delete`](../commands/variables/page.mdx#variables-delete) require confirmation in interactive mode and refuse to run without `--yes` in non-interactive mode.
49 - **Production environments cannot be deleted.** [`mcloud environments delete`](../commands/environments/page.mdx#environments-delete) errors on production environments by design. Do not attempt to bypass it.
50 - **Pipe to `jq` for extraction.** Avoid string-parsing JSON; pipe `--json` output into `jq` for structured access.
51
52 ---
53
54 ## Set Up the CLI
55
56 AI agents should run this one-time setup before any other CLI work, then never repeat it on the same machine. Skip the steps whose checks already pass.
57
58 ### 1. Check Whether the CLI Is Already Installed
59
60 Before doing anything else, check whether the CLI is already on the system:
61
62 ```bash
63 mcloud --version
64 ```
65
66 If the command exits with `0` and prints a version string, the CLI is installed. Skip the rest of this section and move on to [Confirm Authentication and Context](#confirm-authentication-and-context). If the command is not found, continue to the next step.
67
68 ### 2. Verify Node.js Version
69
70 The CLI requires Node.js v22 or later. Check the installed version:
71
72 ```bash
73 node --version
74 ```
75
76 If the version is below `v22`, ask the user to upgrade Node.js (for example, via [nvm](https://github.com/nvm-sh/nvm) or [the official installer](https://nodejs.org/en/download)) and rerun the check before continuing. Do not attempt to upgrade Node.js without authorization.
77
78 ### 3. Install the Cloud CLI
79
80 Install `@medusajs/mcloud` globally with the user's preferred package manager:
81
82 ```bash npm2yarn
83 npm install @medusajs/mcloud -g
84 ```
85
86 Verify the install:
87
88 ```bash
89 mcloud --version
90 ```
91
92 A successful version string confirms the CLI is on `PATH`. If the command is not found, ask the user to check their global npm bin directory is on `PATH` or to reinstall with a different package manager.
93
94 ### 4. Log In or Sign Up
95
96 Ask the user whether they already have a Cloud account.
97
98 If yes, run [`mcloud login`](../commands/login/page.mdx) to authenticate. The CLI opens a browser to complete the flow:
99
100 ```bash
101 mcloud login
102 ```
103
104 If no, run [`mcloud signup`](../commands/signup/page.mdx) to open the sign-up page. After the user creates an account, run `mcloud login`:
105
106 ```bash
107 mcloud signup
108 mcloud login
109 ```
110
111 For non-interactive environments (CI, headless containers, restricted shells), skip the browser flow entirely and use an access key instead:
112
113 ```bash
114 export MCLOUD_TOKEN=<access-key>
115 ```
116
117 When `MCLOUD_TOKEN` is set, the CLI uses it on every command and `mcloud login` is rejected. See the [login command reference](../commands/login/page.mdx#non-interactive-authentication) for personal vs organization access keys.
118
119 ### 5. Confirm the Setup
120
121 Run [`mcloud whoami`](../commands/whoami/page.mdx) to verify authentication, then move on to setting the active context:
122
123 ```bash
124 mcloud whoami --json
125 ```
126
127 ---
128
129 ## Confirm Authentication and Context
130
131 Before running any command that mutates state, AI agents should verify the active identity and scope:
132
133 ```bash
134 mcloud whoami --json
135 ```
136
137 The response includes the auth kind, expiry (for JWT-based auth), and the active organization, project, and environment. Inspect `auth.kind` and `organization.id` to assert the CLI is ready to use:
138
139 ```bash
140 mcloud whoami --json | jq -e '.auth.kind != "none" and .organization.id != null'
141 ```
142
143 Exit code `0` means authenticated and scoped; on a non-zero exit, stop and ask the user to authenticate or set the active context.
144
145 <Note title="Authentication precedence">
146
147 If `MCLOUD_TOKEN` is set, it overrides any credentials stored on disk and `mcloud login` is rejected. To switch accounts, unset the variable first.
148
149 </Note>
150
151 ---
152
153 ## Set the Active Context Programmatically
154
155 AI agents should persist the active organization, project, and environment so subsequent commands can run without `--organization`, `--project`, or `--environment` flags. Pass values directly when running non-interactively:
156
157 ```bash
158 mcloud use \
159 --organization org_123 \
160 --project proj_123 \
161 --environment env_123
162 ```
163
164 If you only have names instead of IDs or handles, look them up first:
165
166 ```bash
167 # Resolve organization ID by name
168 ORGANIZATION_ID=$(
169 mcloud organizations list --json \
170 | jq -r '.[] | select(.name == "My Organization") | .id'
171 )
172
173 # Resolve project handle by name
174 PROJECT_HANDLE=$(
175 mcloud projects list --organization "$ORGANIZATION_ID" --json \
176 | jq -r '.[] | select(.name == "My Store") | .handle'
177 )
178
179 # Resolve environment handle by name
180 ENVIRONMENT_HANDLE=$(
181 mcloud environments list --organization "$ORGANIZATION_ID" --project "$PROJECT_HANDLE" --json \
182 | jq -r '.[] | select(.name == "Production") | .handle'
183 )
184
185 mcloud use \
186 --organization "$ORGANIZATION_ID" \
187 --project "$PROJECT_HANDLE" \
188 --environment "$ENVIRONMENT_HANDLE"
189 ```
190
191 To clear the active context (for example, before switching to a different account or organization), pass `--clear`:
192
193 ```bash
194 mcloud use --clear
195 ```
196
197 <Note type="warning">
198
199 `mcloud use` without flags is interactive (it requires a TTY) and will not work inside CI runners, Docker `RUN` steps, or piped input. Always pass flags instead of relying on the interactive picker.
200
201 </Note>
202
203 ---
204
205 ## Inspect Deployments
206
207 The deployment table returned by [`mcloud deployments list`](../commands/deployments/page.mdx#deployments-list) carries two computed status fields per row that AI agents should route on:
208
209 - `backend_status`: lifecycle of the backend (build + rollout)
210 - `storefront_status`: lifecycle of the storefront
211
212 Both fields use the same value set: `created`, `building`, `built`, `deploying`, `deployed`, `build-failed`, `deployment-failed`, `timed-out` (backend only), `canceled`, and `idle`. See the full reference in the [deployments command guide](../commands/deployments/page.mdx#backend-and-storefront-statuses).
213
214 Use `--json` and `jq` to filter for the relevant deployments:
215
216 ```bash
217 # Most recent failed deployment for the active environment
218 mcloud deployments list --json \
219 | jq -r '[.[] | select(.backend_status == "build-failed" or .backend_status == "deployment-failed")][0].id'
220
221 # All deployments for a specific commit
222 mcloud deployments list --commit a1b2c3d --json | jq '.'
223
224 # Only preview deployments
225 mcloud deployments list --environment-type preview --json | jq '.'
226 ```
227
228 For one specific deployment, use [`mcloud deployments get`](../commands/deployments/page.mdx#deployments-get):
229
230 ```bash
231 mcloud deployments get bld_01ABC123 --json
232 ```
233
234 ---
235
236 ## Debug a Failed Deployment
237
238 The right log source depends on the failure mode. AI agents should route on `backend_status` (or `storefront_status`):
239
240 <Table>
241 <Table.Header>
242 <Table.Row>
243 <Table.HeaderCell>
244 `backend_status`
245 </Table.HeaderCell>
246 <Table.HeaderCell>
247 What failed
248 </Table.HeaderCell>
249 <Table.HeaderCell>
250 Where to look
251 </Table.HeaderCell>
252 </Table.Row>
253 </Table.Header>
254 <Table.Body>
255 <Table.Row>
256 <Table.Cell>
257
258 `build-failed`
259
260 </Table.Cell>
261 <Table.Cell>
262
263 Build step (Docker, dependencies, compilation).
264
265 </Table.Cell>
266 <Table.Cell>
267
268 [`mcloud deployments build-logs`](../commands/deployments/page.mdx#deployments-build-logs)
269
270 </Table.Cell>
271 </Table.Row>
272 <Table.Row>
273 <Table.Cell>
274
275 `deployment-failed`
276
277 </Table.Cell>
278 <Table.Cell>
279
280 Rollout step (the build succeeded but the runtime crashed).
281
282 </Table.Cell>
283 <Table.Cell>
284
285 [`mcloud logs --deployment <id>`](../commands/logs/page.mdx)
286
287 </Table.Cell>
288 </Table.Row>
289 <Table.Row>
290 <Table.Cell>
291
292 `timed-out`
293
294 </Table.Cell>
295 <Table.Cell>
296
297 Build or rollout exceeded the time budget.
298
299 </Table.Cell>
300 <Table.Cell>
301
302 Both: `build-logs` first, then runtime `logs`.
303
304 </Table.Cell>
305 </Table.Row>
306 </Table.Body>
307 </Table>
308
309 ### Build Failure Recipe
310
311 ```bash
312 # Find the most recent build-failed deployment
313 DEPLOYMENT_ID=$(
314 mcloud deployments list --json \
315 | jq -r '[.[] | select(.backend_status == "build-failed")][0].id'
316 )
317
318 # Inspect deployment metadata (commit, environment, timestamps)
319 mcloud deployments get "$DEPLOYMENT_ID" --json
320
321 # Read the build output
322 mcloud deployments build-logs "$DEPLOYMENT_ID"
323
324 # For storefront build failures, pass --type storefront
325 mcloud deployments build-logs "$DEPLOYMENT_ID" --type storefront
326 ```
327
328 `build-logs` returns a `build_status` field (`created`, `in-progress`, `succeeded`, `failed`, `timed-out`, `canceled`). When `failed`, check the build's `metadata.failed_docker_layer` (visible via `mcloud deployments get --json`) to identify the failing layer.
329
330 ### Reproduce a Build Failure Locally
331
332 When `build-logs` alone isn't enough to pinpoint a build failure, reproduce the Cloud build on the local machine with [`mcloud local build`](../commands/local/page.mdx). It runs the same Docker build Cloud runs and infers the root path and build variables from the linked project and environment, so an agent can iterate on a fix without pushing to the tracked branch and waiting for a full Cloud build each time.
333
334 <Note>
335
336 `mcloud local build` requires Docker installed and running, and must run from inside the project's Git repository. Unlike every other command, it has **no `--json` flag**: it streams plaintext build output and signals the result through its exit code (`0` means the build succeeded). Do not parse its output as JSON. It reproduces `build-failed` failures only, not `deployment-failed` (runtime) failures.
337
338 </Note>
339
340 To match the failure exactly, check out the same commit the failed deployment built, then reproduce the build:
341
342 ```bash
343 # Identify the failing deployment and the commit it built
344 DEPLOYMENT_ID=$(
345 mcloud deployments list --json \
346 | jq -r '[.[] | select(.backend_status == "build-failed")][0].id'
347 )
348 COMMIT=$(mcloud deployments get "$DEPLOYMENT_ID" --json | jq -r '.commit_hash')
349
350 # Check out the same commit so the local build matches the failed one
351 git checkout "$COMMIT"
352
353 # Reproduce the backend build locally, then route on the exit code
354 if mcloud local build; then
355 echo "Build succeeded locally; the failure is not reproducible from this commit."
356 else
357 echo "Build failed locally; inspect the streamed output above for the failing step."
358 fi
359
360 # For a storefront build failure, build the storefront instead
361 mcloud local build --type storefront
362 ```
363
364 If the failure only involves environment variables, reproduce and test a fix without editing code by overriding them:
365
366 ```bash
367 # Override a single build variable
368 mcloud local build --var NODE_ENV=production
369
370 # Or build against a local .env file
371 mcloud local build --env-file .env
372 ```
373
374 Once the local build exits `0`, push the fix to the tracked branch and start a fresh Cloud build with [`mcloud environments trigger-build`](#rerun-a-deployment).
375
376 ### Deployment Failure Recipe
377
378 When the build succeeded but the rollout failed, the build logs won't help. Read the runtime logs scoped to that deployment instead. The `--deployment` flag accepts both deployment IDs (`depl_...`) and build IDs (anything else); the CLI resolves a build ID to its latest deployment automatically.
379
380 ```bash
381 # Find the most recent deployment-failed deployment
382 DEPLOYMENT_ID=$(
383 mcloud deployments list --json \
384 | jq -r '[.[] | select(.backend_status == "deployment-failed")][0].id'
385 )
386
387 # Read the runtime logs for that specific deployment
388 mcloud logs --deployment "$DEPLOYMENT_ID" --limit 1000
389
390 # Filter to error-level lines only
391 mcloud logs --deployment "$DEPLOYMENT_ID" --search error --limit 1000
392
393 # Filter by HTTP status (5xx)
394 mcloud logs --deployment "$DEPLOYMENT_ID" --metadata status=500 --limit 1000
395
396 # Machine-readable: pipe to jq for structured analysis
397 mcloud logs --deployment "$DEPLOYMENT_ID" --json | jq '.[] | {timestamp, source, message}'
398 ```
399
400 <Note>
401
402 `--follow` cannot be combined with `--json`. To process logs in a script, use a bounded time window with `--from`/`--to` and `--json`.
403
404 </Note>
405
406 ---
407
408 ## Rerun a Deployment
409
410 After fixing the underlying issue, AI agents have two options. They are not interchangeable:
411
412 <Table>
413 <Table.Header>
414 <Table.Row>
415 <Table.HeaderCell>
416 Command
417 </Table.HeaderCell>
418 <Table.HeaderCell>
419 What it does
420 </Table.HeaderCell>
421 <Table.HeaderCell>
422 When to use
423 </Table.HeaderCell>
424 </Table.Row>
425 </Table.Header>
426 <Table.Body>
427 <Table.Row>
428 <Table.Cell>
429
430 [`mcloud environments redeploy <env>`](../commands/environments/page.mdx#environments-redeploy)
431
432 </Table.Cell>
433 <Table.Cell>
434
435 Re-runs the **active deployment's existing build**.
436
437 </Table.Cell>
438 <Table.Cell>
439
440 The fix is environment-side (variable change, infra issue) and the build itself is fine.
441
442 </Table.Cell>
443 </Table.Row>
444 <Table.Row>
445 <Table.Cell>
446
447 [`mcloud environments trigger-build <env>`](../commands/environments/page.mdx#environments-trigger-build)
448
449 </Table.Cell>
450 <Table.Cell>
451
452 Starts a **new build from the tracked branch**.
453
454 </Table.Cell>
455 <Table.Cell>
456
457 The fix is in the source code that's already on the tracked branch.
458
459 </Table.Cell>
460 </Table.Row>
461 </Table.Body>
462 </Table>
463
464 `redeploy` requires the environment to have an active deployment. If it doesn't, run `trigger-build` first to create one.
465
466 ```bash
467 # After fixing an environment variable
468 mcloud environments redeploy env_123
469
470 # After pushing a fix to the tracked branch
471 mcloud environments trigger-build env_123
472
473 # Verify the new build is running
474 mcloud deployments list --environment env_123 --limit 5 --json \
475 | jq '.[] | {id, backend_status, commit_hash, updated_at}'
476 ```
477
478 ---
479
480 ## Manage Environment Variables
481
482 Environment variables are scoped to a single environment. AI agents should pass `--reveal` to print plaintext secret values only when the user has explicitly asked to see them.
483
484 ```bash
485 # List all variables (secrets masked)
486 mcloud variables list --json
487
488 # Get a single variable by key (requires active project and environment)
489 mcloud variables get DATABASE_URL --json
490
491 # Get a single variable by ID (works without project/environment context)
492 mcloud variables get var_01XYZ --json
493
494 # Reveal a secret value when explicitly requested
495 mcloud variables get STRIPE_SECRET_KEY --reveal --json | jq -r '.value'
496 ```
497
498 <Note type="warning">
499
500 Avoid passing `--reveal` unless the user explicitly asked to see the secret value. The plaintext value is captured by terminal scrollback, log aggregators, and process listings.
501
502 </Note>
503
504 To replicate a Cloud environment's variables locally, export them to a `.env` file:
505
506 ```bash
507 mcloud variables list --reveal --json \
508 | jq -r '.[] | "\(.key)=\(.value)"' \
509 > .env
510 ```
511
512 ---
513
514 ## Manage Environments
515
516 Use this flow when creating a preview environment for a feature branch or tearing down environments after a pull request closes:
517
518 ```bash
519 # Create a long-lived environment that tracks a branch
520 mcloud environments create \
521 --name "Staging" \
522 --branch develop
523
524 # Inspect an environment's current state
525 mcloud environments get env_123 --json | jq '{id, name, type, status, external_id}'
526
527 # Delete an environment without prompting (production environments are protected)
528 mcloud environments delete env_123 --yes
529 ```
530
531 `environments delete` returns a non-zero exit code on production environments. Always check the `type` field via `environments get --json` before attempting a delete in an automated workflow.
532
533 ---
534
535 ## Common Pitfalls
536
537 - **TTY-only commands.** `mcloud login` (browser flow), `mcloud use` (without flags), and any delete command without `--yes` require an interactive TTY. They will error in CI runners, Docker `RUN` steps, or piped input.
538 - **`MCLOUD_TOKEN` precedence.** When `MCLOUD_TOKEN` is set, file-based credentials are ignored and `mcloud login` is rejected. To switch accounts, `unset MCLOUD_TOKEN` first.
539 - **Personal vs organization access keys.** A personal access key requires `--organization` (or an organization in the active context); an organization access key is already scoped to one organization. See the [login reference](../commands/login/page.mdx#non-interactive-authentication) for details.
540 - **`organizations list` requires personal auth.** Organization access keys cannot list organizations and the command will return 401. Use a personal access key or browser login to enumerate organizations.
541 - **Build IDs vs deployment IDs.** `mcloud logs --deployment` accepts both. IDs that start with `depl` are deployments; everything else is treated as a build ID and resolved to the build's latest deployment. Other commands (`deployments get`, `deployments build-logs`, `environments redeploy`) take build IDs only.
542 - **`--json` and `--follow` are incompatible.** Streaming logs with `--follow` always prints plaintext. For programmatic ingestion, use bounded time windows with `--from`/`--to` and `--json`.