---
title: Python SDK
description: Install the microvms Python package, run a first command, and find every class, function, and exception it exports.
---

The `microvms` package on PyPI. This reference is generated from `bindings/microvms-py/microvms.pyi`, the type stub the wheel ships, so a signature here is the one a type checker sees.

## Install

```sh
python3 -m venv .venv
. .venv/bin/activate
python -m pip install microvms
```

Requires **CPython 3.11+**. On Windows, activate with
`.venv\Scripts\Activate.ps1` in PowerShell. Wheels ship for Linux x64/ARM64
(glibc), macOS Intel/Apple Silicon, and Windows x64. Type declarations are included.

## Run your first command

This example starts a VM from an image, runs a command, and cleans up.
Set up AWS and build the image first. Each launch creates resources that
AWS bills to your account.

You need Lambda MicroVMs access, your normal AWS credential configuration,
and an execution role. Follow [AWS setup](/microvms-agentd/learn/tutorial/first-run/)
to set `AWS_REGION` and `MICROVM_EXECUTION_ROLE_ARN`. Then use the
[CLI](/microvms-agentd/learn/tutorial/install/)
to prepare an image containing `agentd`:

```sh
microvm build --name agent-tools --json
export MICROVM_IMAGE='paste data.imageIdentifier from the result'
```

Use the **image ARN**, in the same account and region as your credentials.
The SDK can also look up an image by name in that region. This example uses
the ARN returned by the build.
The CLI provisions `agentd` and uploads the build artifact for you. Shell
examples use Bash or Zsh; in PowerShell, set variables with `$env:NAME='value'`.

Save as `hello.py`:

```python
import os
import sys
from microvms import Region, Sandbox

image = os.environ["MICROVM_IMAGE"]
role = os.environ["MICROVM_EXECUTION_ROLE_ARN"]
vm = Sandbox(Region.parse(os.environ.get("AWS_REGION", "us-east-1")))
try:
    session = vm.run(image_identifier=image, execution_role_arn=role)
    result = session.run_sync(["echo", "hello from a sandbox"])
    print(result.stdout, end="")
    print(result.stderr, end="", file=sys.stderr)
    if not result.ok:
        raise RuntimeError(f"Command exited with {result.exit_code}")
finally:
    cleanup = vm.terminate()
    if cleanup.failures or cleanup.undeleted:
        print("Cleanup needs attention:", cleanup.to_dict(), file=sys.stderr)
```

```sh
python hello.py
```

Expected output: `hello from a sandbox`. The VM is terminated after the
command; the image stays available for reuse. `terminate()` returns once
termination is accepted by default. Pass `wait_for_terminated=True` to
wait for the final state. Inspect `failures` and `undeleted` because cleanup
reports failures in its result.

## Everything the package exports

Each class has its own page. Functions, constants, and exceptions share [one page](/microvms-agentd/reference/python/module/).

| Name | Kind | Summary |
| --- | --- | --- |
| [`AgentSpec`](/microvms-agentd/reference/python/classes/agentspec/) | class | One agent to install: its name, and the two defaults a caller may override. |
| [`AgentVm`](/microvms-agentd/reference/python/classes/agentvm/) | class | One VM with coding agents in it: the sandbox plus the specs it is built for. |
| [`Amount`](/microvms-agentd/reference/python/classes/amount/) | class | What a line item's cost can be: an estimate, or unpriced. |
| [`BaseImage`](/microvms-agentd/reference/python/classes/baseimage/) | class | The platform's managed base image, paired with the Dockerfile `FROM` it goes with. |
| [`BearerToken`](/microvms-agentd/reference/python/classes/bearertoken/) | class | A Bedrock bearer token, the region it was minted for, and when it stops working. |
| [`BudgetVerdict`](/microvms-agentd/reference/python/classes/budgetverdict/) | class | A report's total judged against a budget: core's `Budget::check`, the verdict `microvm cost --max-cost` renders. |
| [`BuildHookTimeout`](/microvms-agentd/reference/python/classes/buildhooktimeout/) | class | A timeout for the `ready` or `validate` image-build hook: 1..=3600 seconds. |
| [`ByteStream`](/microvms-agentd/reference/python/classes/bytestream/) | class | One side of a spawned exec's output, as an iterator of `bytes`. |
| [`ConnectionEnd`](/microvms-agentd/reference/python/classes/connectionend/) | class | A connection that didn't end clean. |
| [`ControlPlane`](/microvms-agentd/reference/python/classes/controlplane/) | class | MicroVM lifecycle by ID (get, list, suspend, resume, terminate, and wait) and image administration (list, delete, versions and their status, builds). |
| [`CostReport`](/microvms-agentd/reference/python/classes/costreport/) | class | Per-phase attribution for one sandbox, measured or projected. |
| [`Detached`](/microvms-agentd/reference/python/classes/detached/) | class | What another process needs to adopt a VM handed off by `Sandbox.detach()`. |
| [`Discovery`](/microvms-agentd/reference/python/classes/discovery/) | class | Image configuration. A missing discovery response means an older daemon. |
| [`DownloadedFile`](/microvms-agentd/reference/python/classes/downloadedfile/) | class | One file `Session.download_dir` wrote, relative to the local directory. |
| [`Duration`](/microvms-agentd/reference/python/classes/duration/) | class | Seconds, plus how we know them. |
| [`EnsuredImage`](/microvms-agentd/reference/python/classes/ensuredimage/) | class | What `Sandbox.ensure_image` returns: the ready image and how this call got it. |
| [`EstimatedUsd`](/microvms-agentd/reference/python/classes/estimatedusd/) | class | Dollars derived from published rates. Not the bill. |
| [`ExecHandle`](/microvms-agentd/reference/python/classes/exechandle/) | class | One exec, addressed by its caller-minted id. |
| [`ExecProcess`](/microvms-agentd/reference/python/classes/execprocess/) | class | A running exec as two byte iterators, a `wait()`, and an idempotent `kill()`. |
| [`ExecResult`](/microvms-agentd/reference/python/classes/execresult/) | class | An exec's phase and, once it has one, its outcome. |
| [`ExecStream`](/microvms-agentd/reference/python/classes/execstream/) | class | A Python iterator, and async iterator, over an exec's output. |
| [`Exit`](/microvms-agentd/reference/python/classes/exit/) | class | The terminal event. Its **absence** is what distinguishes a cut connection from a finished command — the byte sequences are otherwise identical. |
| [`Gap`](/microvms-agentd/reference/python/classes/gap/) | class | A byte range that is gone for good — the replay ring evicted it, or this subscriber lagged the live channel. |
| [`HandlerOutcome`](/microvms-agentd/reference/python/classes/handleroutcome/) | class | What a workload's hook handler did. Its output is in the daemon's log, not here. |
| [`Health`](/microvms-agentd/reference/python/classes/health/) | class | The daemon's liveness answer. `bootstrapped` is the useful field. |
| [`HookObservation`](/microvms-agentd/reference/python/classes/hookobservation/) | class | One lifecycle-hook invocation, as the daemon observed it. |
| [`IdentityStep`](/microvms-agentd/reference/python/classes/identitystep/) | class | One identity-repair step. |
| [`IdlePolicy`](/microvms-agentd/reference/python/classes/idlepolicy/) | class | The idle policy the service reports a VM is running under. |
| [`Image`](/microvms-agentd/reference/python/classes/image/) | class | A built image, and the log group the service created alongside it. |
| [`ImageBuild`](/microvms-agentd/reference/python/classes/imagebuild/) | class | One build of an image version: one per Graviton generation, so a version's builds differ in `chipset_generation`. `get_image_build` adds the snapshot sizes the listing lacks. |
| [`ImageSummary`](/microvms-agentd/reference/python/classes/imagesummary/) | class | One `ListMicrovmImages` item: an image's ARN, name and state. |
| [`ImageVersion`](/microvms-agentd/reference/python/classes/imageversion/) | class | One image version as `ListMicrovmImageVersions` or `UpdateMicrovmImageVersion` reads it back: its build state, whether `RunMicrovm` launches it, and what it was built with. |
| [`KeepAwake`](/microvms-agentd/reference/python/classes/keepawake/) | class | A running keepalive. Use as a context manager, or call `stop()`. |
| [`KeepAwakeReport`](/microvms-agentd/reference/python/classes/keepawakereport/) | class | What a finished keepalive did. |
| [`LineItem`](/microvms-agentd/reference/python/classes/lineitem/) | class | One phase's one billing line: what was consumed, and what that costs. |
| [`ManagedBaseVersion`](/microvms-agentd/reference/python/classes/managedbaseversion/) | class | One version of a managed base image, from `ListManagedMicrovmImageVersions`. |
| [`Microvm`](/microvms-agentd/reference/python/classes/microvm/) | class | A MicroVM as `GetMicrovm` last described it. |
| [`MicrovmSummary`](/microvms-agentd/reference/python/classes/microvmsummary/) | class | One `ListMicrovms` item: narrower than `Microvm`, with no endpoint or reason. |
| [`NameRecord`](/microvms-agentd/reference/python/classes/namerecord/) | class | One named VM: everything `Sandbox.adopt` needs, under a name. |
| [`NameRegistry`](/microvms-agentd/reference/python/classes/nameregistry/) | class | The CLI's name registry: one owner-only JSON file per name under `<state_dir>/names/`. |
| [`OutputChunk`](/microvms-agentd/reference/python/classes/outputchunk/) | class | Output bytes, with the offset they start at. |
| [`OutputGap`](/microvms-agentd/reference/python/classes/outputgap/) | class | One byte range the daemon couldn't replay, under `gap_policy="event"`. |
| [`PortForward`](/microvms-agentd/reference/python/classes/portforward/) | class | A running port-forward. Use as a context manager, or call `stop()`. |
| [`PortForwardReport`](/microvms-agentd/reference/python/classes/portforwardreport/) | class | What a stopped port-forward did. |
| [`PreflightCheck`](/microvms-agentd/reference/python/classes/preflightcheck/) | class | One line of a preflight report. |
| [`PreflightReport`](/microvms-agentd/reference/python/classes/preflightreport/) | class | What `preflight` found: three checks and whether a launch could proceed. |
| [`ProcGroup`](/microvms-agentd/reference/python/classes/procgroup/) | class | One exec's process group, as `GET /v1/procs` reports it. |
| [`ProvisionedAgentd`](/microvms-agentd/reference/python/classes/provisionedagentd/) | class | A provisioned `agentd` binary and how it got here: `provision_agentd_report()`'s answer. |
| [`RateTable`](/microvms-agentd/reference/python/classes/ratetable/) | class | The pinned rate table, and everything it says about itself. |
| [`Region`](/microvms-agentd/reference/python/classes/region/) | class | An AWS region, by its name. |
| [`ResidencyComparison`](/microvms-agentd/reference/python/classes/residencycomparison/) | class | Running versus suspended for the same VM over the same wall time. |
| [`RunHookTimeout`](/microvms-agentd/reference/python/classes/runhooktimeout/) | class | A timeout for the `run`, `resume`, `suspend`, or `terminate` hook: 1..=60 seconds. |
| [`Sandbox`](/microvms-agentd/reference/python/classes/sandbox/) | class | One MicroVM's whole life. |
| [`Session`](/microvms-agentd/reference/python/classes/session/) | class | One running MicroVM's control API, with the proxy auth handled for you. |
| [`SizeClass`](/microvms-agentd/reference/python/classes/sizeclass/) | class | One of the five documented size classes. |
| [`StdinAck`](/microvms-agentd/reference/python/classes/stdinack/) | class | What a stdin write accomplished. |
| [`SweepFailure`](/microvms-agentd/reference/python/classes/sweepfailure/) | class | One resource operation that failed during a sweep. |
| [`SweepReport`](/microvms-agentd/reference/python/classes/sweepreport/) | class | Inventory and confirmed outcomes of prefix cleanup. |
| [`SyncReport`](/microvms-agentd/reference/python/classes/syncreport/) | class | What one `Session.sync_dir` did. |
| [`TeardownReport`](/microvms-agentd/reference/python/classes/teardownreport/) | class | What a teardown did, and what it left behind. |
| [`Total`](/microvms-agentd/reference/python/classes/total/) | class | A report's total, which is a lower bound whenever anything is unpriced. |
| [`Tunnel`](/microvms-agentd/reference/python/classes/tunnel/) | class | A running tunnel. Use as a context manager, or call `stop()`. |
| [`TunnelIdentity`](/microvms-agentd/reference/python/classes/tunnelidentity/) | class | What a launcher keeps to verify its VM: the host's secret seed and the VM's public key, both base64. |
| [`TunnelReport`](/microvms-agentd/reference/python/classes/tunnelreport/) | class | What a stopped tunnel did. |
| [`Unpriced`](/microvms-agentd/reference/python/classes/unpriced/) | class | A quantity we can measure but cannot price, because no rate is published. |
| [`agent_constants`](/microvms-agentd/reference/python/module/#agent_constants) | function | The layer's fixed values, for a caller that wants to reason about the guest. |
| [`build_unpriced_reason`](/microvms-agentd/reference/python/module/#build_unpriced_reason) | function | Why the image build has no price, as the reason that lands on the line item. |
| [`check_budget`](/microvms-agentd/reference/python/module/#check_budget) | function | Judges `report`'s total against a ceiling of `max_usd` (a decimal string, such as `"1.50"`), with `on_breach` (`"warn"` or `"abort"`) saying what a breach does. |
| [`compare_residency`](/microvms-agentd/reference/python/module/#compare_residency) | function | The warm-pool argument, with its own counter-argument attached. |
| [`core_version`](/microvms-agentd/reference/python/module/#core_version) | function | The core crate's version, for a `doctor` or `manifest` command to report. |
| [`cost_constants`](/microvms-agentd/reference/python/module/#cost_constants) | function | The documented facts a caller may want to assert on, as strings and flags. |
| [`egress_posture_for`](/microvms-agentd/reference/python/module/#egress_posture_for) | function | The egress posture `Sandbox.run` with these options would report, without launching. |
| [`estimate_run`](/microvms-agentd/reference/python/module/#estimate_run) | function | What a plan will cost, before spending anything (COST-10). |
| [`install_agent_access`](/microvms-agentd/reference/python/module/#install_agent_access) | function | Installs Bedrock access for `agents` into a running VM over `session`. |
| [`install_agent_access_async`](/microvms-agentd/reference/python/module/#install_agent_access_async) | function | The awaitable twin of `install_agent_access`. |
| [`installed_agents`](/microvms-agentd/reference/python/module/#installed_agents) | function | The agents a running VM was provisioned with, read from its guest marker. |
| [`installed_agents_async`](/microvms-agentd/reference/python/module/#installed_agents_async) | function | The awaitable twin of `installed_agents`. |
| [`mint_bedrock_token`](/microvms-agentd/reference/python/module/#mint_bedrock_token) | function | Mints a Bedrock bearer token from the default credential chain. |
| [`mint_bedrock_token_async`](/microvms-agentd/reference/python/module/#mint_bedrock_token_async) | function | The awaitable twin of `mint_bedrock_token`. |
| [`mint_bedrock_token_with_credentials`](/microvms-agentd/reference/python/module/#mint_bedrock_token_with_credentials) | function | Mint with explicit STS credentials and their expiry without changing process env. `credentials_expires_at` is Unix seconds from STS Expiration. Secrets never enter repr. |
| [`preflight`](/microvms-agentd/reference/python/module/#preflight) | function | Whether a harness can launch in `region` (default: `$AWS_REGION`, `$AWS_DEFAULT_REGION`, then us-east-1), checked before it queues work. |
| [`preflight_async`](/microvms-agentd/reference/python/module/#preflight_async) | function | The awaitable twin of `preflight`. Never raises either; read `report.ok`. |
| [`prompt_agent`](/microvms-agentd/reference/python/module/#prompt_agent) | function | Starts one task for `agent` over `session` and returns its handle. Does not wait. |
| [`prompt_agent_async`](/microvms-agentd/reference/python/module/#prompt_agent_async) | function | The awaitable twin of `prompt_agent`. |
| [`provision_agentd`](/microvms-agentd/reference/python/module/#provision_agentd) | function | The `agentd` daemon binary for `version` (default: this client's own), as bytes. |
| [`provision_agentd_async`](/microvms-agentd/reference/python/module/#provision_agentd_async) | function | The awaitable twin of `provision_agentd`. |
| [`provision_agentd_report`](/microvms-agentd/reference/python/module/#provision_agentd_report) | function | `provision_agentd`, answering with the bytes and how they got here: the source, the verification, the path, the version, and the digest. |
| [`provision_agentd_report_async`](/microvms-agentd/reference/python/module/#provision_agentd_report_async) | function | The awaitable twin of `provision_agentd_report`. |
| [`run_report`](/microvms-agentd/reference/python/module/#run_report) | function | Per-phase attribution for one sandbox's lifecycle. |
| [`session_constants`](/microvms-agentd/reference/python/module/#session_constants) | function | The daemon's protocol constants, for a caller asserting against the wire contract. |
| [`wrap_dockerfile`](/microvms-agentd/reference/python/module/#wrap_dockerfile) | function | A task Dockerfile with the agentd stanza appended, ready for `build_image`. |
| [`wrap_dockerfile_preserving_user`](/microvms-agentd/reference/python/module/#wrap_dockerfile_preserving_user) | function | Preserve the final Dockerfile USER's uid and primary gid as the workload default. The builder resolves stage inheritance, variables and names. Explicit image AGENTD\_DEFAULT\_USER and request users win. The daemon starts as root and workloads start only after readiness. Requires COPY `--chmod`. |
| [`__version__`](/microvms-agentd/reference/python/module/#__version__) | constant | - |
| [`MicrovmError`](/microvms-agentd/reference/python/module/#microvmerror) | exception | Base of every exception this library raises. Carries `.code`, `.kind`, `.wire_kind`, and `.retryable` so nothing has to parse a message. |
| [`BuildWedgedError`](/microvms-agentd/reference/python/module/#buildwedgederror) | exception | ERR\_BUILD\_WEDGED — the image build was never scheduled: the clientToken replay signature. |
| [`CredentialsError`](/microvms-agentd/reference/python/module/#credentialserror) | exception | ERR\_CREDENTIALS — an identity is wrong or absent; waiting will not fix it. |
| [`ExecFailedError`](/microvms-agentd/reference/python/module/#execfailederror) | exception | ERR\_EXEC\_FAILED — the sandbox worked and the command in it exited non-zero. The one failure that means nothing is wrong with the platform. |
| [`InterruptedError`](/microvms-agentd/reference/python/module/#interruptederror) | exception | ERR\_INTERRUPTED — interrupted after launch; teardown ran and any leak is named. |
| [`InvalidArgError`](/microvms-agentd/reference/python/module/#invalidargerror) | exception | ERR\_INVALID\_ARG — refused locally, before any AWS call. Every trap closure lands here. |
| [`LaunchDiedError`](/microvms-agentd/reference/python/module/#launchdiederror) | exception | ERR\_LAUNCH\_DIED — the MicroVM reached a terminal state before RUNNING. Read the message's stateReason. |
| [`PlatformError`](/microvms-agentd/reference/python/module/#platformerror) | exception | ERR\_PLATFORM — a control-plane failure with no more specific class. |
| [`PreconditionError`](/microvms-agentd/reference/python/module/#preconditionerror) | exception | ERR\_PRECONDITION — a prerequisite is missing. |
| [`ProtocolError`](/microvms-agentd/reference/python/module/#protocolerror) | exception | ERR\_PROTOCOL — the daemon rejected the request on its merits. Read `.wire_kind` to tell a 400 from a 404. |
| [`RetryableError`](/microvms-agentd/reference/python/module/#retryableerror) | exception | ERR\_RETRYABLE — transient. Run the identical request again. |
| [`TimeoutError`](/microvms-agentd/reference/python/module/#timeouterror) | exception | ERR\_TIMEOUT — a client-side deadline elapsed. The VM and the exec are untouched. |
| [`UnexpectedError`](/microvms-agentd/reference/python/module/#unexpectederror) | exception | ERR\_UNEXPECTED — no handler claimed this. A bug in the client, not the platform. |
| [`WindowClosedError`](/microvms-agentd/reference/python/module/#windowclosederror) | exception | ERR\_WINDOW\_CLOSED — the MicroVM ended before the resume (the suspended window, the maximum duration, or a terminate), and it can't be resumed; launch a new one. The suspended window ends a VM the idle policy suspended; an explicit suspend stayed resumable 1283 s into a 60 s window (measured 2026-10-12, us-east-1). |

## Provenance

This page is generated from `bindings/microvms-py/microvms.pyi` by Griffe 2.3.0, run from `site/scripts/gen-reference.mjs` on every `pnpm run sync`, so an edit made here is overwritten by the next run.

To change the page, change the doc comment in the binding's Rust source, then regenerate the declarations with `mise run stubs`. `mise run stubs:check` fails when the committed file no longer matches the source.