Skip to content

Python SDK

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.

Terminal window
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.

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 to set AWS_REGION and MICROVM_EXECUTION_ROLE_ARN. Then use the CLI to prepare an image containing agentd:

Terminal window
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:

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)
Terminal window
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.

Each class has its own page. Functions, constants, and exceptions share one page.

Name Kind Summary
AgentSpec class One agent to install: its name, and the two defaults a caller may override.
AgentVm class One VM with coding agents in it: the sandbox plus the specs it is built for.
Amount class What a line item’s cost can be: an estimate, or unpriced.
BaseImage class The platform’s managed base image, paired with the Dockerfile FROM it goes with.
BearerToken class A Bedrock bearer token, the region it was minted for, and when it stops working.
BudgetVerdict class A report’s total judged against a budget: core’s Budget::check, the verdict microvm cost --max-cost renders.
BuildHookTimeout class A timeout for the ready or validate image-build hook: 1..=3600 seconds.
ByteStream class One side of a spawned exec’s output, as an iterator of bytes.
ConnectionEnd class A connection that didn’t end clean.
ControlPlane class MicroVM lifecycle by ID (get, list, suspend, resume, terminate, and wait) and image administration (list, delete, versions and their status, builds).
CostReport class Per-phase attribution for one sandbox, measured or projected.
Detached class What another process needs to adopt a VM handed off by Sandbox.detach().
Discovery class Image configuration. A missing discovery response means an older daemon.
DownloadedFile class One file Session.download_dir wrote, relative to the local directory.
Duration class Seconds, plus how we know them.
EnsuredImage class What Sandbox.ensure_image returns: the ready image and how this call got it.
EstimatedUsd class Dollars derived from published rates. Not the bill.
ExecHandle class One exec, addressed by its caller-minted id.
ExecProcess class A running exec as two byte iterators, a wait(), and an idempotent kill().
ExecResult class An exec’s phase and, once it has one, its outcome.
ExecStream class A Python iterator, and async iterator, over an exec’s output.
Exit class The terminal event. Its absence is what distinguishes a cut connection from a finished command — the byte sequences are otherwise identical.
Gap class A byte range that is gone for good — the replay ring evicted it, or this subscriber lagged the live channel.
HandlerOutcome class What a workload’s hook handler did. Its output is in the daemon’s log, not here.
Health class The daemon’s liveness answer. bootstrapped is the useful field.
HookObservation class One lifecycle-hook invocation, as the daemon observed it.
IdentityStep class One identity-repair step.
IdlePolicy class The idle policy the service reports a VM is running under.
Image class A built image, and the log group the service created alongside it.
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 class One ListMicrovmImages item: an image’s ARN, name and state.
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 class A running keepalive. Use as a context manager, or call stop().
KeepAwakeReport class What a finished keepalive did.
LineItem class One phase’s one billing line: what was consumed, and what that costs.
ManagedBaseVersion class One version of a managed base image, from ListManagedMicrovmImageVersions.
Microvm class A MicroVM as GetMicrovm last described it.
MicrovmSummary class One ListMicrovms item: narrower than Microvm, with no endpoint or reason.
NameRecord class One named VM: everything Sandbox.adopt needs, under a name.
NameRegistry class The CLI’s name registry: one owner-only JSON file per name under <state_dir>/names/.
OutputChunk class Output bytes, with the offset they start at.
OutputGap class One byte range the daemon couldn’t replay, under gap_policy="event".
PortForward class A running port-forward. Use as a context manager, or call stop().
PortForwardReport class What a stopped port-forward did.
PreflightCheck class One line of a preflight report.
PreflightReport class What preflight found: three checks and whether a launch could proceed.
ProcGroup class One exec’s process group, as GET /v1/procs reports it.
ProvisionedAgentd class A provisioned agentd binary and how it got here: provision_agentd_report()’s answer.
RateTable class The pinned rate table, and everything it says about itself.
Region class An AWS region, by its name.
ResidencyComparison class Running versus suspended for the same VM over the same wall time.
RunHookTimeout class A timeout for the run, resume, suspend, or terminate hook: 1..=60 seconds.
Sandbox class One MicroVM’s whole life.
Session class One running MicroVM’s control API, with the proxy auth handled for you.
SizeClass class One of the five documented size classes.
StdinAck class What a stdin write accomplished.
SweepFailure class One resource operation that failed during a sweep.
SweepReport class Inventory and confirmed outcomes of prefix cleanup.
SyncReport class What one Session.sync_dir did.
TeardownReport class What a teardown did, and what it left behind.
Total class A report’s total, which is a lower bound whenever anything is unpriced.
Tunnel class A running tunnel. Use as a context manager, or call stop().
TunnelIdentity class What a launcher keeps to verify its VM: the host’s secret seed and the VM’s public key, both base64.
TunnelReport class What a stopped tunnel did.
Unpriced class A quantity we can measure but cannot price, because no rate is published.
agent_constants function The layer’s fixed values, for a caller that wants to reason about the guest.
build_unpriced_reason function Why the image build has no price, as the reason that lands on the line item.
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 function The warm-pool argument, with its own counter-argument attached.
core_version function The core crate’s version, for a doctor or manifest command to report.
cost_constants function The documented facts a caller may want to assert on, as strings and flags.
egress_posture_for function The egress posture Sandbox.run with these options would report, without launching.
estimate_run function What a plan will cost, before spending anything (COST-10).
install_agent_access function Installs Bedrock access for agents into a running VM over session.
install_agent_access_async function The awaitable twin of install_agent_access.
installed_agents function The agents a running VM was provisioned with, read from its guest marker.
installed_agents_async function The awaitable twin of installed_agents.
mint_bedrock_token function Mints a Bedrock bearer token from the default credential chain.
mint_bedrock_token_async function The awaitable twin of mint_bedrock_token.
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 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 function The awaitable twin of preflight. Never raises either; read report.ok.
prompt_agent function Starts one task for agent over session and returns its handle. Does not wait.
prompt_agent_async function The awaitable twin of prompt_agent.
provision_agentd function The agentd daemon binary for version (default: this client’s own), as bytes.
provision_agentd_async function The awaitable twin of provision_agentd.
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 function The awaitable twin of provision_agentd_report.
run_report function Per-phase attribution for one sandbox’s lifecycle.
session_constants function The daemon’s protocol constants, for a caller asserting against the wire contract.
wrap_dockerfile function A task Dockerfile with the agentd stanza appended, ready for build_image.
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__ constant -
MicrovmError exception Base of every exception this library raises. Carries .code, .kind, .wire_kind, and .retryable so nothing has to parse a message.
BuildWedgedError exception ERR_BUILD_WEDGED — the image build was never scheduled: the clientToken replay signature.
CredentialsError exception ERR_CREDENTIALS — an identity is wrong or absent; waiting will not fix it.
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 exception ERR_INTERRUPTED — interrupted after launch; teardown ran and any leak is named.
InvalidArgError exception ERR_INVALID_ARG — refused locally, before any AWS call. Every trap closure lands here.
LaunchDiedError exception ERR_LAUNCH_DIED — the MicroVM reached a terminal state before RUNNING. Read the message’s stateReason.
PlatformError exception ERR_PLATFORM — a control-plane failure with no more specific class.
PreconditionError exception ERR_PRECONDITION — a prerequisite is missing.
ProtocolError exception ERR_PROTOCOL — the daemon rejected the request on its merits. Read .wire_kind to tell a 400 from a 404.
RetryableError exception ERR_RETRYABLE — transient. Run the identical request again.
TimeoutError exception ERR_TIMEOUT — a client-side deadline elapsed. The VM and the exec are untouched.
UnexpectedError exception ERR_UNEXPECTED — no handler claimed this. A bug in the client, not the platform.
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).

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.