Playbook: deploy code from your AI agent
Nội dung này hiện chưa có sẵn bằng ngôn ngữ của bạn.
Goal: the user says “deploy this” in Claude Code, Cursor or another agent. You take the project folder you are working in, ship it to one of their servers and hand back a working HTTPS URL, a database if the code needs one, and the build log. No Git remote, no domain and no dashboard needed.
Token: operate. Plan: every plan (on Free, writes through a token are a 30-day
trial, then 402 automation_trial_ended). Creating a new app counts against the
plan’s Docker apps & stacks quota across all servers (Free 3, Plus 5 per server, Pro and Max
unlimited); redeploying an app you already created never does. Server: agent 0.2.144 or newer, Docker installed,
and at least 1.5 GB free RAM+swap and 3 GB free disk for the build.
The build runs on the user’s server (Dockerfile if the folder has one, otherwise Nixpacks detects Node.js, Python, Go, Ruby, PHP and more). Nothing is built on MZPanel’s side.
1. Pick the server
Section titled “1. Pick the server”servers_list→ pick the target server’s UUID (ask the user if there is more than one candidate). It must be online. Or let MZPanel pick it: see Let MZPanel pick the server below.- Check Docker:
servers_inventory {id, kind: "services"}. If Docker is missing, tell the user.jobs_createwith{type: "extension.install", id: "docker"}(every plan,fulltoken) orservers_provision {id, body: {components: ["docker"]}}installs it. - Will it fit? Before deploying to a server the user named, ask MZPanel:
apps_placement {body: {placement: {serverId: "<server UUID>"}, memory?: "1g"}}. The answer’sfitisok,tight,shortorunknown, andfitReasonsays why in plain words. See Will it fit? below. Onshort, don’t deploy there: tell the user, pick another server or free resources first. Ontight, deploy only after warning the user.
2. Get an upload URL
Section titled “2. Get an upload URL”MCP:
{ "tool": "apps_source_upload", "arguments": { "id": "<server UUID>" } }REST: POST /v1/servers/{id}/apps/source-upload with body {} (or {"size": <bytes>}).
The answer:
{ "uploadId": "q3Jx…", "method": "PUT", "uploadUrl": "https://…/__mz-upload/…/q3Jx….tar.gz", "headers": { "Content-Type": "application/gzip", "X-Mz-Token": "…" }, "maxBytes": 536870912, "expiresAt": "2026-11-27T10:15:00.000Z", "curl": "tar --exclude=.git --exclude=node_modules -czf - . | curl -fsS -X PUT --data-binary @- -H 'Content-Type: application/gzip' -H 'X-Mz-Token: …' 'https://…'"}3. Upload the folder
Section titled “3. Upload the folder”Run the curl string as is, from the project’s root folder in your shell tool. It packs
the folder without .git and node_modules and sends it straight to the server.
- The URL is valid for 15 minutes and works once.
- The archive can be at most 512 MiB compressed (2 GiB unpacked, 50 000 files). If the
project has other large build output or data folders, add more
--exclude=flags to thetarpart (--exclude=dist --exclude=.venv --exclude=target, …). - Don’t print or store the
X-Mz-Tokenheader anywhere else. It is a one-time upload credential.
4. Deploy
Section titled “4. Deploy”MCP:
{ "tool": "apps_deploy", "arguments": { "id": "<server UUID>", "body": { "source": { "uploadId": "q3Jx…" }, "db": "auto", "env": { "NODE_ENV": "production" } } }}REST: POST /v1/servers/{id}/apps/deploy with the same body.
Body fields:
| Field | Meaning |
|---|---|
source | Exactly one of {uploadId} (from step 2, after the curl ran) or {git: {url, branch?, connectionId?}} for a Git repo (https URL; connectionId from git_connections_list for a private repo). With Git, skip steps 2 and 3. |
name | Optional. Lowercase letters, digits and inner dashes, up to 32 characters. Default: <repo name or "app">-<4 random characters>. The same name on the same server redeploys that app. |
domain | Omit it for an instant URL https://<name>-<first 8 characters of the server id>.<platform domain> with a valid certificate. A string = the user’s own domain (its DNS must point at the server first). null = no domain, existing apps only. |
db | auto attaches PostgreSQL or MariaDB before the first start when the code’s manifests name a driver (package.json, requirements.txt, pyproject.toml, go.mod, Gemfile). none (default), postgres or mariadb force the choice. A DATABASE_URL you pass in env skips the attach. MongoDB drivers are reported, not attached. |
env | {KEY: value} set before the first start. Values are masked in logs. With env, the call is refused with 409 server_offline when the server is offline (it is never queued). |
port | The port the app listens on inside the container (default 3000). |
builder | auto (default), dockerfile or nixpacks. |
context | A subfolder to build from (monorepos). |
buildArgs | {KEY: value} build arguments (sealed on the server, masked in logs). |
The answer is 202:
{ "jobId": "5b0c…", "name": "app-k3f9", "url": "https://app-k3f9-1a2b3c4d.<platform domain>", "domain": "app-k3f9-1a2b3c4d.<platform domain>", "quota": { "used": 1, "limit": 2 }, "statusUrl": "/v1/servers/<id>/apps/deploy/5b0c…"}quota.limit is null on plans with unlimited apps. A note field, when present, explains
something the user should know (for example that the instant URL may take a moment to
resolve). Remember name: every later redeploy uses it.
A new app also answers "defaults": {"status": "pending"}: see
Safe defaults. Pass "defaults": false in the body to skip them
("status": "off").
5. Poll until it is done
Section titled “5. Poll until it is done”apps_deploy_status {id, jobId} (REST GET /v1/servers/{id}/apps/deploy/{jobId}) every
5–10 seconds. Builds take from under a minute to several minutes.
{ "jobId": "5b0c…", "status": "completed", "exitCode": 0, "url": "https://app-k3f9-1a2b3c4d.<platform domain>", "detected": { "db": "postgres", "evidence": "package.json: pg" }, "dbAttached": { "engine": "postgres", "database": "app_k3f9", "user": "app_k3f9" }}status is queued, running, completed, failed, timeout or cancelled. For the
full build log, jobs_output {id: jobId}.
Verify: fetch url and check it answers. Then tell the user the URL, the app name, and
whether a database was attached (its connection details are in the app’s env as
DATABASE_URL, DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASSWORD; never print the
password).
6. When the build fails: fix and redeploy
Section titled “6. When the build fails: fix and redeploy”A failed status carries a failure block and the agent’s error:
{ "status": "failed", "failure": { "stage": "health", "exitCode": 1, "logTail": "…last lines of the build and container log…", "hint": "Nothing answered on the app's port. The app must listen on 0.0.0.0 (not 127.0.0.1) on the port given with --port (default 3000; many frameworks read $PORT — set --env PORT=<port>) and start within 60s." }, "error": { "code": "health_check_failed", "message": "…" }}Read hint first, then logTail. hint is empty when the failure is not one of the common
cases below (for example a failing RUN line in the Dockerfile): the cause is then in logTail.
Typical stages and fixes:
stage | Usual cause | Fix |
|---|---|---|
preflight | Not enough free RAM or disk for a build (low_resources) | Ask the user to free resources or add swap. Don’t force it on a small box without asking. |
extract | archive_too_large or archive_invalid | Exclude more folders from the tar; upload a plain gzip tarball of the folder. |
detect / build | No Dockerfile and Nixpacks couldn’t tell the stack; a compile or install error; out of memory (exit 137) | Add a Dockerfile or a start script, set context, fix the error in logTail, or lower build memory (for example buildArgs: {NODE_OPTIONS: "--max-old-space-size=512"}). |
start | The container exited right away (missing start command, crash on boot, a database error) | Fix the start command or the crash shown in logTail. |
health | Nothing answered on the port within 60 seconds | Listen on 0.0.0.0 and the given port, or pass env: {PORT: "<port>"} and the matching port. |
unknown | An older agent without the structured block | Read logTail and hint (the job’s error message). |
Then redeploy:
- Fix the code or the options.
- Upload again (
apps_source_upload+ itscurl). An upload works once: the failed build already removed it, and reusing the olduploadIdreturns400 bad_upload. apps_deploywith the samenameand the newuploadId. A new app whose first start failed is left in place, so this is a redeploy and does not use another app slot.
Stop after two failed attempts with the same cause and report the hint, the stage and the
relevant log lines to the user instead of looping.
Let MZPanel pick the server
Section titled “Let MZPanel pick the server”When the user has several servers and doesn’t care which one runs the app, use the
account-level calls. They take the same bodies as the per-server ones, plus an optional
placement object, and run the same deploy underneath.
apps_fleet_source_upload {body: {placement?: {tags?, region?}}}(RESTPOST /v1/apps/source-upload) picks the server and returns the upload fields from step 2 plusserverIdandplacement. The upload goes straight to that server, so the deploy will run there.- Run its
curl(step 3). apps_fleet_deploy {body: {source: {uploadId}, db?, env?}}(RESTPOST /v1/apps/deploy) → the step 4 answer plusserverIdandplacement. For a Git repo skip the upload:apps_fleet_deploy {body: {source: {git: {url}}, placement?}}places it at deploy time.- Poll
apps_deploy_status {id: serverId, jobId}(step 5).
apps_placement {body: {name?, source?: "upload" | "git", db?, memory?, placement?}}
(REST POST /v1/apps/placement) is the dry run: it uploads and deploys nothing.
How the server is chosen:
- An app with that
namealready exists → its server (a redeploy never moves an app). placement.serverId→ that server.- Otherwise every server is a candidate that is online, in the caller’s scope and the
token’s server allowlist, is not excluded by the owner (
servers_updatewithplacementExcluded: true) or a homelab box without a tunnel, matchesplacement.tags(the server’s tag, any of) andplacement.region(a case-insensitive part of the server’s location, set withservers_update {location}; a server without a location never matches a region), runs agent 0.2.144+ (for uploads ordb), and has at least 1.5 GB RAM+swap and 3 GB disk free (the build floor; free swap counts, as in the agent’s build preflight). The one with the most free RAM wins, then the most free disk, then the fewest apps. When you passmemory, a server with less free RAM than that is not eligible either.
The placement block says what happened:
{ "serverId": "1a2b…", "serverName": "web-2", "reason": "Most free memory of 2 eligible servers matching tag prod: 6.0 GB RAM and 60.0 GB disk free, CPU 12%.", "candidates": [ { "serverId": "1a2b…", "name": "web-2", "eligible": true, "reason": "6.0 GB RAM and 60.0 GB disk free, CPU 12%", "freeRamMb": 6144, "freeDiskGb": 60, "cpuPct": 12.5, "apps": 3, "tag": "prod", "location": "Sydney", "online": true, "agentVersion": "0.2.144", "fit": "ok", "fitReason": "needs ~1.5 GB RAM to build (the app ~512 MB, estimated), 6.0 GB free, 60.0 GB disk free" }, { "serverId": "9f8e…", "name": "db-1", "eligible": false, "reason": "only 1.0 GB RAM free (a build needs 1.5 GB)", "fit": "short", "fitReason": "needs ~1.5 GB RAM to build (the app ~512 MB, estimated), 1000 MB free", "…": "…" } ], "fit": "ok", "fitReason": "needs ~1.5 GB RAM to build (the app ~512 MB, estimated), 6.0 GB free, 60.0 GB disk free", "need": { "ramMb": 1536, "diskGb": 3, "buildRamMb": 1536, "appMemoryMb": 512, "appMemorySource": "default" }}Tell the user which server was picked and why. Resource numbers come from the agents’ last heartbeat (about every 10 seconds).
Will it fit?
Section titled “Will it fit?”Every candidate, and the top level for the chosen server, carries a pre-deploy verdict:
fit | Meaning |
|---|---|
ok | The build and the app fit with room to spare. |
tight | It fits, but with less than max(512 MB, need / 4) RAM to spare (for example a build that only fits by swapping), or under 5 GB disk free. Expect slow builds, swapping or out-of-memory kills under load. |
short | It doesn’t fit: free RAM+swap is below the build floor, free RAM is below the app’s memory, or free disk is under 3 GB. The build would be refused or the app killed. |
unknown | The agent hasn’t reported resource metrics yet. |
The need (need block) is the larger of the build floor (1.5 GB free RAM+swap, which the agent
checks before every build) and the app’s memory: the memory you pass ("512m", "1g", or a
number of MB, for example the cap you plan to set with app.update {memory}), or a 512 MB
estimate when you pass none (appMemorySource: "default"). Disk needs 3 GB for the build.
One named server: apps_placement {body: {placement: {serverId: "<UUID>"}, memory?}} answers
for that server even when it would not be picked: read the top-level fit and fitReason, and
quote fitReason to the user (“needs ~1.5 GB RAM to build (the app ~512 MB, estimated), 380 MB
free”). The same verdict is in the placement block of apps_fleet_source_upload and
apps_fleet_deploy.
Safe defaults for new apps
Section titled “Safe defaults for new apps”A new app deployed with apps_deploy or apps_fleet_deploy gets three things once its first
build has completed (about 30 seconds after, so the URL is up when it is first checked):
- an uptime monitor on its URL, expecting the status code the app answered then;
- a “Containers unhealthy or restarting” alert rule on its server (one per server); it notifies the server’s alert channels, or the in-app notifications inbox when the server has none;
- a daily backup job of the app (03:00, kept 7 days) to the account’s local backup destination, unless a job already covers it.
Each one is skipped with a note when it doesn’t apply: the plan’s backup job limit is used up,
there is no local destination, or the same monitor, rule or job already exists. A skipped
default never fails the deploy. apps_deploy_status shows the outcome:
"defaults": { "status": "applied", "result": { "uptime": { "status": "created", "id": "…" }, "alerts": { "status": "exists", "id": "…" }, "backup": { "status": "skipped", "note": "Your plan allows 2 backup job(s) and they are all in use." } }}status is pending (waiting for the build), applied, or expired (the app never built
within 7 days). A failed first build keeps it pending; the next deploy of the same name
re-arms it. Pass "defaults": false to skip all three.
See every app at once
Section titled “See every app at once”apps_list_all (REST GET /v1/apps, filters ?serverId=, ?tag=, ?state=) returns every
managed app of the fleet with its server, state (running, exited, restarting, …, or
deploying while a first build runs, syncing when a build finished after the last inventory
sync), url, lastDeploy {jobId, type, status, createdAt, completedAt} and container load {cpuPct, memPct, memUsage}, plus a servers list with
each server’s free RAM, free disk, CPU and app count. Use it before deploying (does the app
exist? where?) and after (is it running?). It reads the cached inventory (syncedAt): a new app
whose first build has just completed is listed with state: "syncing" (no container, URL or
load yet) until the next inventory sync; apps_deploy_status is the source of truth right
after a deploy.
Errors
Section titled “Errors”| Code | Meaning | What to do |
|---|---|---|
402 app_limit | A new app would exceed the plan’s Docker apps & stacks quota (details.used, details.limit, details.tier) | Report it. The user deletes an app or stack, or upgrades. Redeploying an existing name still works. |
402 automation_trial_ended | Free plan, its 30-day API write trial is over (details.required_tier: "plus", details.trial_ended_at) | Don’t retry. Tell the user to upgrade to Plus or deploy from the dashboard. Reads still work. |
400 bad_upload | Unknown, expired or used uploadId, or apps_deploy ran before the curl finished | Run the curl first; otherwise call apps_source_upload again. |
400 domain_required | A new app has no domain and no instant URL is available, or you sent domain: null for a new app | Pass domain with a hostname that points at the server. |
409 agent_update_required | The server’s agent is older than 0.2.144 (details.current, details.required) | Run agent_update {id}, wait for it to reconnect, then retry. |
409 server_offline | env was given and the server is offline | Wait for the server to come online. |
503 direct_upload_unavailable | Direct uploads to this server aren’t available | Deploy from a Git repository instead (source: {git: {url}}). |
403 forbidden | The token owner can only manage some sites, not the whole server | Ask for a token from a member with access to the whole server. |
409 no_placement | No server fits (details.candidates gives each server’s reason) | Relax placement, free resources, update the agent, or pin a server with placement.serverId. |
409 ambiguous_app | An app with that name runs on several servers | Pass placement.serverId, or use the per-server apps_deploy. |
409 placement_conflict | The app exists on another server than the one the upload went to | Call apps_fleet_source_upload with the same name (it uploads to the app’s server), then deploy. |
Later changes
Section titled “Later changes”- New code: repeat steps 2–5 with the same
name. - Rebuild the last upload (for example after changing env):
jobs_createwith{type: "app.rebuild", name}. The last three successful archives are kept on the server, so rebuilds and rollbacks (app.releases→app.rollback {name, to}) work without Git.app.rollbackneeds afulltoken with the opt-inbackups:restorescope, and removing an app (app.delete) needsfull+sites:delete— unless this same token created the app and carriesapps:own(the Deploy ability), which is enough for both on its own apps. - Env:
app.env-set {name, vars: ["K=V"]}. Own domain:app.domain-add {name, domain}. - Auto-deploy on git push (every plan; the app must be built from a Git repository):
app_webhooks_set {id, name, body: {branch?, cancel_previous?}}(RESTPOST /v1/servers/{id}/apps/{name}/webhook,operate+webhooks:admin) returns{webhook: {url, secret, branch, cancel_previous}}. The user addsurlto the repository’s webhooks (GitHub:secretas the HMAC secret, content type JSON; GitLab:secretas the secret token). Each matching push runsapp.rebuild, which never counts against the app limit. A new push supersedes the app’s earlier rebuilds percancel_previous:queued(default) cancels the ones still queued for an offline server,buildingalso aborts the one running,nonekeeps them all. A cancelled rebuild endscancelledwith an error message naming the newer commit; only that app’sapp.rebuildjobs are touched. Apull_requestevent on the same webhook builds a PR preview only on Pro and Max; on Free and Plus it answers{"ok": true, "skipped": "tier-required"}. - Everything else (logs, updates, removal) is in Deploy a Docker app or stack.
Related
Section titled “Related”- Docker apps & stacks — the full app lifecycle.
- Tiers & quotas — the app limit per plan.
- Jobs — polling,
jobs_outputand job states.